text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
namespace ET { [Message] public class A2NetClient_Message: MessageObject, IMessage { public static A2NetClient_Message Create() { return ObjectPool.Instance.Fetch(typeof(A2NetClient_Message)) as A2NetClient_Message; } public override void Dispose() { this.MessageObject = default; ObjectPool.Instance.Recycle(this); } public IMessage MessageObject; } [Message] [ResponseType(nameof(A2NetClient_Response))] public class A2NetClient_Request: MessageObject, IRequest { public static A2NetClient_Request Create() { return ObjectPool.Instance.Fetch(typeof(A2NetClient_Request)) as A2NetClient_Request; } public override void Dispose() { this.RpcId = default; this.MessageObject = default; ObjectPool.Instance.Recycle(this); } public int RpcId { get; set; } public IRequest MessageObject; } [Message] public class A2NetClient_Response: MessageObject, IResponse { public static A2NetClient_Response Create() { return ObjectPool.Instance.Fetch(typeof(A2NetClient_Response)) as A2NetClient_Response; } public override void Dispose() { this.RpcId = default; this.Error = default; this.Message = default; this.MessageObject = default; ObjectPool.Instance.Recycle(this); } public int RpcId { get; set; } public int Error { get; set; } public string Message { get; set; } public IResponse MessageObject; } [Message] public class NetClient2Main_SessionDispose: MessageObject, IMessage { public static NetClient2Main_SessionDispose Create() { return ObjectPool.Instance.Fetch(typeof(NetClient2Main_SessionDispose)) as NetClient2Main_SessionDispose; } public override void Dispose() { ObjectPool.Instance.Recycle(this); } public int Error { get; set; } } }
ET/Unity/Assets/Scripts/Model/Client/Demo/NetClient/A2NetClient_Message.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/Demo/NetClient/A2NetClient_Message.cs", "repo_id": "ET", "token_count": 1005 }
147
namespace ET.Client { public struct LSSceneChangeStart { public Room Room; } public struct LSSceneInitFinish { } }
ET/Unity/Assets/Scripts/Model/Client/LockStep/EventType.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/LockStep/EventType.cs", "repo_id": "ET", "token_count": 69 }
148
fileFormatVersion: 2 guid: 45bbe48eea3422945a554d1b4f923a6f folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Generate.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate.meta", "repo_id": "ET", "token_count": 71 }
149
fileFormatVersion: 2 guid: f6cb781d7426010449c63c186cc69c24 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Generate/ClientServer.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/ClientServer.meta", "repo_id": "ET", "token_count": 67 }
150
using System; using System.Collections.Generic; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Options; using System.ComponentModel; namespace ET { [Config] public partial class AIConfigCategory : Singleton<AIConfigCategory>, IMerge { [BsonElement] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)] private Dictionary<int, AIConfig> dict = new(); public void Merge(object o) { AIConfigCategory s = o as AIConfigCategory; foreach (var kv in s.dict) { this.dict.Add(kv.Key, kv.Value); } } public AIConfig Get(int id) { this.dict.TryGetValue(id, out AIConfig item); if (item == null) { throw new Exception($"配置找不到,配置表名: {nameof (AIConfig)},配置id: {id}"); } return item; } public bool Contain(int id) { return this.dict.ContainsKey(id); } public Dictionary<int, AIConfig> GetAll() { return this.dict; } public AIConfig GetOne() { if (this.dict == null || this.dict.Count <= 0) { return null; } return this.dict.Values.GetEnumerator().Current; } } public partial class AIConfig: ProtoObject, IConfig { /// <summary>Id</summary> public int Id { get; set; } /// <summary>所属ai</summary> public int AIConfigId { get; set; } /// <summary>此ai中的顺序</summary> public int Order { get; set; } /// <summary>节点名字</summary> public string Name { get; set; } /// <summary>节点参数</summary> public int[] NodeParams { get; set; } } }
ET/Unity/Assets/Scripts/Model/Generate/Server/Config/AIConfig.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/Server/Config/AIConfig.cs", "repo_id": "ET", "token_count": 922 }
151
fileFormatVersion: 2 guid: 2328265af4362554bb7e63612eafcc2e MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Generate/Server/ConfigPartial/StartSceneConfig.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/Server/ConfigPartial/StartSceneConfig.cs.meta", "repo_id": "ET", "token_count": 93 }
152
namespace ET.Server { [ComponentOf(typeof(Scene))] public class BenchmarkClientComponent: Entity, IAwake { } }
ET/Unity/Assets/Scripts/Model/Server/Benchmark/BenchmarkClientComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Benchmark/BenchmarkClientComponent.cs", "repo_id": "ET", "token_count": 52 }
153
fileFormatVersion: 2 guid: 886c7abbc951ad14197420f7db46033e folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/Demo/Watcher.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Demo/Watcher.meta", "repo_id": "ET", "token_count": 67 }
154
fileFormatVersion: 2 guid: 21a0976ebbc13407da27f69d27ed3976 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/LockStep/Match/MatchComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/LockStep/Match/MatchComponent.cs.meta", "repo_id": "ET", "token_count": 92 }
155
fileFormatVersion: 2 guid: 15d2e4888958d964399187bc1a29f0ec MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/Module/ActorLocation/LocationComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/ActorLocation/LocationComponent.cs.meta", "repo_id": "ET", "token_count": 94 }
156
fileFormatVersion: 2 guid: e0de2584d06993846b20ba44c51b8a0b MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/Module/Http/HttpComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/Http/HttpComponent.cs.meta", "repo_id": "ET", "token_count": 96 }
157
using System.Collections.Generic; namespace ET.Server { [ChildOf(typeof(RobotCaseComponent))] public class RobotCase: Entity, IAwake, IDestroy { public ETCancellationToken CancellationToken; public string CommandLine; public HashSet<long> Scenes { get; } = new HashSet<long>(); } }
ET/Unity/Assets/Scripts/Model/Server/Module/RobotCase/RobotCase.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/RobotCase/RobotCase.cs", "repo_id": "ET", "token_count": 127 }
158
namespace ET { public static class ConstFiberId { public const int Main = -1; public const int NetInner = -2; public const int NetClient = -3; public const int DB = -4; } }
ET/Unity/Assets/Scripts/Model/Share/ConstFiberId.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/ConstFiberId.cs", "repo_id": "ET", "token_count": 98 }
159
using System; namespace ET { public interface ILSUpdate { } public interface ILSUpdateSystem: ISystemType { void Run(LSEntity o); } [LSEntitySystem] public abstract class LSUpdateSystem<T>: SystemObject, ILSUpdateSystem where T: LSEntity, ILSUpdate { void ILSUpdateSystem.Run(LSEntity o) { this.LSUpdate((T)o); } Type ISystemType.Type() { return typeof(T); } Type ISystemType.SystemType() { return typeof(ILSUpdateSystem); } int ISystemType.GetInstanceQueueIndex() { return LSQueneUpdateIndex.LSUpdate; } protected abstract void LSUpdate(T self); } }
ET/Unity/Assets/Scripts/Model/Share/LockStep/ILSUpdateSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/ILSUpdateSystem.cs", "repo_id": "ET", "token_count": 370 }
160
using System; using MemoryPack; using MongoDB.Bson.Serialization.Attributes; using TrueSync; namespace ET { [ChildOf(typeof(LSUnitComponent))] [MemoryPackable] public partial class LSUnit: LSEntity, IAwake, ISerializeToEntity { public TSVector Position { get; set; } [MemoryPackIgnore] [BsonIgnore] public TSVector Forward { get => this.Rotation * TSVector.forward; set => this.Rotation = TSQuaternion.LookRotation(value, TSVector.up); } public TSQuaternion Rotation { get; set; } } }
ET/Unity/Assets/Scripts/Model/Share/LockStep/LSUnit.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/LSUnit.cs", "repo_id": "ET", "token_count": 339 }
161
using System; namespace ET { public class AIHandlerAttribute: BaseAttribute { } [AIHandler] public abstract class AAIHandler: HandlerObject { // 检查是否满足条件 public abstract int Check(AIComponent aiComponent, AIConfig aiConfig); // 协程编写必须可以取消 public abstract ETTask Execute(AIComponent aiComponent, AIConfig aiConfig, ETCancellationToken cancellationToken); } }
ET/Unity/Assets/Scripts/Model/Share/Module/AI/AAIHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/AI/AAIHandler.cs", "repo_id": "ET", "token_count": 201 }
162
fileFormatVersion: 2 guid: 0498d217572ef624cb2f066e11f028a9 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module/Console/IConsoleHandler.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Console/IConsoleHandler.cs.meta", "repo_id": "ET", "token_count": 94 }
163
using System; namespace ET { public class MessageSessionHandlerAttribute: BaseAttribute { public SceneType SceneType { get; } public MessageSessionHandlerAttribute(SceneType sceneType) { this.SceneType = sceneType; } } }
ET/Unity/Assets/Scripts/Model/Share/Module/Message/MessageSessionHandlerAttribute.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Message/MessageSessionHandlerAttribute.cs", "repo_id": "ET", "token_count": 112 }
164
namespace ET { public interface INumericWatcher { void Run(Unit unit, NumbericChange args); } }
ET/Unity/Assets/Scripts/Model/Share/Module/Numeric/INumericWatcher.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Numeric/INumericWatcher.cs", "repo_id": "ET", "token_count": 39 }
165
fileFormatVersion: 2 guid: ed3aaad9f0ba38b4882cf33a7a5cae86 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module/Scene.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Scene.meta", "repo_id": "ET", "token_count": 71 }
166
fileFormatVersion: 2 guid: 28950c95a2aee3c4782c59819479124a folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Plugins.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Plugins.meta", "repo_id": "ET", "token_count": 68 }
167
using UnityEngine; using UnityEngine.UI; namespace ET.Client { [ComponentOf(typeof(UI))] public class UIHelpComponent : Entity, IAwake { public Text text; } }
ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI/UIHelp/UIHelpComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI/UIHelp/UIHelpComponent.cs", "repo_id": "ET", "token_count": 64 }
168
using UnityEngine; namespace ET.Client { [ComponentOf(typeof(Unit))] public class GameObjectComponent: Entity, IAwake, IDestroy { private GameObject gameObject; public GameObject GameObject { get { return this.gameObject; } set { this.gameObject = value; this.Transform = value.transform; } } public Transform Transform { get; private set; } } }
ET/Unity/Assets/Scripts/ModelView/Client/Demo/Unit/GameObjectComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Demo/Unit/GameObjectComponent.cs", "repo_id": "ET", "token_count": 268 }
169
 using UnityEngine; using UnityEngine.UI; namespace ET.Client { [ComponentOf(typeof(UI))] public class UILSLobbyComponent : Entity, IAwake { public GameObject enterMap; public Text text; public Button replay; public InputField replayPath; } }
ET/Unity/Assets/Scripts/ModelView/Client/LockStep/UI/UILSLobby/UILSLobbyComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/LockStep/UI/UILSLobby/UILSLobbyComponent.cs", "repo_id": "ET", "token_count": 92 }
170
fileFormatVersion: 2 guid: f6f2376fee49a244889f2068ef220f29 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Module/UI/AUIEvent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Module/UI/AUIEvent.cs.meta", "repo_id": "ET", "token_count": 93 }
171
fileFormatVersion: 2 guid: 2d2febae4460b594db87d4653c77323d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Plugins/Example/ModelView.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Plugins/Example/ModelView.cs.meta", "repo_id": "ET", "token_count": 94 }
172
fileFormatVersion: 2 guid: 125579f6ccd4db0489697c78faddeeb7 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcAtomicInteger.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcAtomicInteger.cs.meta", "repo_id": "ET", "token_count": 94 }
173
fileFormatVersion: 2 guid: 5f1fa2c501e92ff419faa5ac39a8267d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcImmutableArray.Enumerable.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcImmutableArray.Enumerable.cs.meta", "repo_id": "ET", "token_count": 95 }
174
fileFormatVersion: 2 guid: 3fe28e25a997118408602e0d0030b9ee MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcTelemetry.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcTelemetry.cs.meta", "repo_id": "ET", "token_count": 93 }
175
namespace DotRecast.Detour.Crowd { public class DtObstacleAvoidanceParams { public float velBias; public float weightDesVel; public float weightCurVel; public float weightSide; public float weightToi; public float horizTime; public int gridSize; /// < grid public int adaptiveDivs; /// < adaptive public int adaptiveRings; /// < adaptive public int adaptiveDepth; /// < adaptive public DtObstacleAvoidanceParams() { velBias = 0.4f; weightDesVel = 2.0f; weightCurVel = 0.75f; weightSide = 0.75f; weightToi = 2.5f; horizTime = 2.5f; gridSize = 33; adaptiveDivs = 7; adaptiveRings = 2; adaptiveDepth = 5; } public DtObstacleAvoidanceParams(DtObstacleAvoidanceParams option) { velBias = option.velBias; weightDesVel = option.weightDesVel; weightCurVel = option.weightCurVel; weightSide = option.weightSide; weightToi = option.weightToi; horizTime = option.horizTime; gridSize = option.gridSize; adaptiveDivs = option.adaptiveDivs; adaptiveRings = option.adaptiveRings; adaptiveDepth = option.adaptiveDepth; } }; }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtObstacleAvoidanceParams.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtObstacleAvoidanceParams.cs", "repo_id": "ET", "token_count": 721 }
176
/* Copyright (c) 2009-2010 Mikko Mononen memon@inside.org recast4j copyright (c) 2015-2019 Piotr Piastucki piotr@jtilia.org DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace DotRecast.Detour.Crowd { public class DtProximityGrid { private readonly float _cellSize; private readonly float _invCellSize; private readonly Dictionary<long, List<DtCrowdAgent>> _items; public DtProximityGrid(float cellSize) { _cellSize = cellSize; _invCellSize = 1.0f / cellSize; _items = new Dictionary<long, List<DtCrowdAgent>>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long CombineKey(int x, int y) { uint ux = (uint)x; uint uy = (uint)y; return ((long)ux << 32) | uy; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void DecomposeKey(long key, out int x, out int y) { uint ux = (uint)(key >> 32); uint uy = (uint)key; x = (int)ux; y = (int)uy; } public void Clear() { _items.Clear(); } public void AddItem(DtCrowdAgent agent, float minx, float miny, float maxx, float maxy) { int iminx = (int)Math.Floor(minx * _invCellSize); int iminy = (int)Math.Floor(miny * _invCellSize); int imaxx = (int)Math.Floor(maxx * _invCellSize); int imaxy = (int)Math.Floor(maxy * _invCellSize); for (int y = iminy; y <= imaxy; ++y) { for (int x = iminx; x <= imaxx; ++x) { long key = CombineKey(x, y); if (!_items.TryGetValue(key, out var ids)) { ids = new List<DtCrowdAgent>(); _items.Add(key, ids); } ids.Add(agent); } } } // 해당 셀 사이즈의 크기로 x ~ y 영역을 찾아, 군집 에이전트를 가져오는 코드 public int QueryItems(float minx, float miny, float maxx, float maxy, ref HashSet<DtCrowdAgent> result) { int iminx = (int)Math.Floor(minx * _invCellSize); int iminy = (int)Math.Floor(miny * _invCellSize); int imaxx = (int)Math.Floor(maxx * _invCellSize); int imaxy = (int)Math.Floor(maxy * _invCellSize); for (int y = iminy; y <= imaxy; ++y) { for (int x = iminx; x <= imaxx; ++x) { long key = CombineKey(x, y); if (_items.TryGetValue(key, out var ids)) { for (int i = 0; i < ids.Count; ++i) { result.Add(ids[i]); } } } } return result.Count; } public IEnumerable<(long, int)> GetItemCounts() { return _items .Where(e => e.Value.Count > 0) .Select(e => (e.Key, e.Value.Count)); } public float GetCellSize() { return _cellSize; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtProximityGrid.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtProximityGrid.cs", "repo_id": "ET", "token_count": 2140 }
177
/* recast4j copyright (c) 2021 Piotr Piastucki piotr@jtilia.org DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using System.IO; using DotRecast.Core; using DotRecast.Detour.Io; namespace DotRecast.Detour.Dynamic.Io { public class VoxelFileWriter : DtWriter { private readonly IRcCompressor _compressor; public VoxelFileWriter(IRcCompressor compressor) { _compressor = compressor; } public void Write(BinaryWriter stream, VoxelFile f, bool compression) { Write(stream, f, VoxelFile.PREFERRED_BYTE_ORDER, compression); } public void Write(BinaryWriter stream, VoxelFile f, RcByteOrder byteOrder, bool compression) { Write(stream, VoxelFile.MAGIC, byteOrder); Write(stream, VoxelFile.VERSION_EXPORTER_RECAST4J | (compression ? VoxelFile.VERSION_COMPRESSION_LZ4 : 0), byteOrder); Write(stream, f.walkableRadius, byteOrder); Write(stream, f.walkableHeight, byteOrder); Write(stream, f.walkableClimb, byteOrder); Write(stream, f.walkableSlopeAngle, byteOrder); Write(stream, f.cellSize, byteOrder); Write(stream, f.maxSimplificationError, byteOrder); Write(stream, f.maxEdgeLen, byteOrder); Write(stream, f.minRegionArea, byteOrder); Write(stream, f.regionMergeArea, byteOrder); Write(stream, f.vertsPerPoly, byteOrder); Write(stream, f.buildMeshDetail); Write(stream, f.detailSampleDistance, byteOrder); Write(stream, f.detailSampleMaxError, byteOrder); Write(stream, f.useTiles); Write(stream, f.tileSizeX, byteOrder); Write(stream, f.tileSizeZ, byteOrder); Write(stream, f.rotation.x, byteOrder); Write(stream, f.rotation.y, byteOrder); Write(stream, f.rotation.z, byteOrder); Write(stream, f.bounds[0], byteOrder); Write(stream, f.bounds[1], byteOrder); Write(stream, f.bounds[2], byteOrder); Write(stream, f.bounds[3], byteOrder); Write(stream, f.bounds[4], byteOrder); Write(stream, f.bounds[5], byteOrder); Write(stream, f.tiles.Count, byteOrder); foreach (VoxelTile t in f.tiles) { WriteTile(stream, t, byteOrder, compression); } } public void WriteTile(BinaryWriter stream, VoxelTile tile, RcByteOrder byteOrder, bool compression) { Write(stream, tile.tileX, byteOrder); Write(stream, tile.tileZ, byteOrder); Write(stream, tile.width, byteOrder); Write(stream, tile.depth, byteOrder); Write(stream, tile.borderSize, byteOrder); Write(stream, tile.boundsMin.x, byteOrder); Write(stream, tile.boundsMin.y, byteOrder); Write(stream, tile.boundsMin.z, byteOrder); Write(stream, tile.boundsMax.x, byteOrder); Write(stream, tile.boundsMax.y, byteOrder); Write(stream, tile.boundsMax.z, byteOrder); Write(stream, tile.cellSize, byteOrder); Write(stream, tile.cellHeight, byteOrder); byte[] bytes = tile.spanData; if (compression) { bytes = _compressor.Compress(bytes); } Write(stream, bytes.Length, byteOrder); stream.Write(bytes); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/Io/VoxelFileWriter.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/Io/VoxelFileWriter.cs", "repo_id": "ET", "token_count": 1836 }
178
using System.Collections.Generic; using DotRecast.Core; using DotRecast.Recast; using static DotRecast.Recast.RcConstants; namespace DotRecast.Detour.Extras.Jumplink { public class EdgeExtractor { public JumpEdge[] ExtractEdges(RcPolyMesh mesh) { List<JumpEdge> edges = new List<JumpEdge>(); if (mesh != null) { RcVec3f orig = mesh.bmin; float cs = mesh.cs; float ch = mesh.ch; for (int i = 0; i < mesh.npolys; i++) { if (i > 41 || i < 41) { // continue; } int nvp = mesh.nvp; int p = i * 2 * nvp; for (int j = 0; j < nvp; ++j) { if (j != 1) { // continue; } if (mesh.polys[p + j] == RC_MESH_NULL_IDX) { break; } // Skip connected edges. if ((mesh.polys[p + nvp + j] & 0x8000) != 0) { int dir = mesh.polys[p + nvp + j] & 0xf; if (dir == 0xf) { // Border if (mesh.polys[p + nvp + j] != RC_MESH_NULL_IDX) { continue; } int nj = j + 1; if (nj >= nvp || mesh.polys[p + nj] == RC_MESH_NULL_IDX) { nj = 0; } int va = mesh.polys[p + j] * 3; int vb = mesh.polys[p + nj] * 3; JumpEdge e = new JumpEdge(); e.sp.x = orig.x + mesh.verts[vb] * cs; e.sp.y = orig.y + mesh.verts[vb + 1] * ch; e.sp.z = orig.z + mesh.verts[vb + 2] * cs; e.sq.x = orig.x + mesh.verts[va] * cs; e.sq.y = orig.y + mesh.verts[va + 1] * ch; e.sq.z = orig.z + mesh.verts[va + 2] * cs; edges.Add(e); } } } } } return edges.ToArray(); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/EdgeExtractor.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/EdgeExtractor.cs", "repo_id": "ET", "token_count": 2015 }
179
using System; using System.Collections.Generic; using System.Linq; using DotRecast.Core; using DotRecast.Recast; using static DotRecast.Core.RcMath; namespace DotRecast.Detour.Extras.Jumplink { public class JumpLinkBuilder { private readonly EdgeExtractor edgeExtractor = new EdgeExtractor(); private readonly EdgeSamplerFactory edgeSamplerFactory = new EdgeSamplerFactory(); private readonly IGroundSampler groundSampler = new NavMeshGroundSampler(); private readonly TrajectorySampler trajectorySampler = new TrajectorySampler(); private readonly JumpSegmentBuilder jumpSegmentBuilder = new JumpSegmentBuilder(); private readonly List<JumpEdge[]> edges; private readonly IList<RecastBuilderResult> results; public JumpLinkBuilder(IList<RecastBuilderResult> results) { this.results = results; edges = results.Select(r => edgeExtractor.ExtractEdges(r.GetMesh())).ToList(); } public List<JumpLink> Build(JumpLinkBuilderConfig acfg, JumpLinkType type) { List<JumpLink> links = new List<JumpLink>(); for (int tile = 0; tile < results.Count; tile++) { JumpEdge[] edges = this.edges[tile]; foreach (JumpEdge edge in edges) { links.AddRange(ProcessEdge(acfg, results[tile], type, edge)); } } return links; } private List<JumpLink> ProcessEdge(JumpLinkBuilderConfig acfg, RecastBuilderResult result, JumpLinkType type, JumpEdge edge) { EdgeSampler es = edgeSamplerFactory.Get(acfg, type, edge); groundSampler.Sample(acfg, result, es); trajectorySampler.Sample(acfg, result.GetSolidHeightfield(), es); JumpSegment[] jumpSegments = jumpSegmentBuilder.Build(acfg, es); return BuildJumpLinks(acfg, es, jumpSegments); } private List<JumpLink> BuildJumpLinks(JumpLinkBuilderConfig acfg, EdgeSampler es, JumpSegment[] jumpSegments) { List<JumpLink> links = new List<JumpLink>(); foreach (JumpSegment js in jumpSegments) { RcVec3f sp = es.start.gsamples[js.startSample].p; RcVec3f sq = es.start.gsamples[js.startSample + js.samples - 1].p; GroundSegment end = es.end[js.groundSegment]; RcVec3f ep = end.gsamples[js.startSample].p; RcVec3f eq = end.gsamples[js.startSample + js.samples - 1].p; float d = Math.Min(RcVec3f.Dist2DSqr(sp, sq), RcVec3f.Dist2DSqr(ep, eq)); if (d >= 4 * acfg.agentRadius * acfg.agentRadius) { JumpLink link = new JumpLink(); links.Add(link); link.startSamples = RcArrayUtils.CopyOf(es.start.gsamples, js.startSample, js.samples); link.endSamples = RcArrayUtils.CopyOf(end.gsamples, js.startSample, js.samples); link.start = es.start; link.end = end; link.trajectory = es.trajectory; for (int j = 0; j < link.nspine; ++j) { float u = ((float)j) / (link.nspine - 1); RcVec3f p = es.trajectory.Apply(sp, ep, u); link.spine0[j * 3] = p.x; link.spine0[j * 3 + 1] = p.y; link.spine0[j * 3 + 2] = p.z; p = es.trajectory.Apply(sq, eq, u); link.spine1[j * 3] = p.x; link.spine1[j * 3 + 1] = p.y; link.spine1[j * 3 + 2] = p.z; } } } return links; } public List<JumpEdge[]> GetEdges() { return edges; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpLinkBuilder.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpLinkBuilder.cs", "repo_id": "ET", "token_count": 2034 }
180
using System; using DotRecast.Core; namespace DotRecast.Detour.Extras.Jumplink { public class Trajectory { public float Lerp(float f, float g, float u) { return u * g + (1f - u) * f; } public virtual RcVec3f Apply(RcVec3f start, RcVec3f end, float u) { throw new NotImplementedException(); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/Trajectory.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/Trajectory.cs", "repo_id": "ET", "token_count": 193 }
181
fileFormatVersion: 2 guid: fd6e31654ac8b9146a4bd9487da362c2 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtObstacleState.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtObstacleState.cs.meta", "repo_id": "ET", "token_count": 95 }
182
fileFormatVersion: 2 guid: 6df6169bf50d87a40a3856473d6f7fbf MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/ObstacleRequest.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/ObstacleRequest.cs.meta", "repo_id": "ET", "token_count": 95 }
183
/* recast4j copyright (c) 2021 Piotr Piastucki piotr@jtilia.org DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using DotRecast.Core; using static DotRecast.Core.RcMath; namespace DotRecast.Detour { public class DefaultQueryHeuristic : IQueryHeuristic { public const float H_SCALE = 0.999f; // Search heuristic scale. public static readonly DefaultQueryHeuristic Default = new DefaultQueryHeuristic(H_SCALE); private readonly float scale; public DefaultQueryHeuristic(float scale) { this.scale = scale; } public float GetCost(RcVec3f neighbourPos, RcVec3f endPos) { return RcVec3f.Distance(neighbourPos, endPos) * scale; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DefaultQueryHeuristic.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DefaultQueryHeuristic.cs", "repo_id": "ET", "token_count": 495 }
184
/* Copyright (c) 2009-2010 Mikko Mononen memon@inside.org recast4j copyright (c) 2015-2019 Piotr Piastucki piotr@jtilia.org DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using DotRecast.Core; namespace DotRecast.Detour { /** Provides high level information related to a dtMeshTile object. */ public class DtMeshHeader { /** A magic number used to detect compatibility of navigation tile data. */ public const int DT_NAVMESH_MAGIC = 'D' << 24 | 'N' << 16 | 'A' << 8 | 'V'; /** A version number used to detect compatibility of navigation tile data. */ public const int DT_NAVMESH_VERSION = 7; public const int DT_NAVMESH_VERSION_RECAST4J_FIRST = 0x8807; public const int DT_NAVMESH_VERSION_RECAST4J_NO_POLY_FIRSTLINK = 0x8808; public const int DT_NAVMESH_VERSION_RECAST4J_32BIT_BVTREE = 0x8809; public const int DT_NAVMESH_VERSION_RECAST4J_LAST = 0x8809; /** A magic number used to detect the compatibility of navigation tile states. */ public const int DT_NAVMESH_STATE_MAGIC = 'D' << 24 | 'N' << 16 | 'M' << 8 | 'S'; /** A version number used to detect compatibility of navigation tile states. */ public const int DT_NAVMESH_STATE_VERSION = 1; /** Tile magic number. (Used to identify the data format.) */ public int magic; /** Tile data format version number. */ public int version; /** The x-position of the tile within the dtNavMesh tile grid. (x, y, layer) */ public int x; /** The y-position of the tile within the dtNavMesh tile grid. (x, y, layer) */ public int y; /** The layer of the tile within the dtNavMesh tile grid. (x, y, layer) */ public int layer; /** The user defined id of the tile. */ public int userId; /** The number of polygons in the tile. */ public int polyCount; /** The number of vertices in the tile. */ public int vertCount; /** The number of allocated links. */ public int maxLinkCount; /** The number of sub-meshes in the detail mesh. */ public int detailMeshCount; /** The number of unique vertices in the detail mesh. (In addition to the polygon vertices.) */ public int detailVertCount; /** The number of triangles in the detail mesh. */ public int detailTriCount; /** The number of bounding volume nodes. (Zero if bounding volumes are disabled.) */ public int bvNodeCount; /** The number of off-mesh connections. */ public int offMeshConCount; /** The index of the first polygon which is an off-mesh connection. */ public int offMeshBase; /** The height of the agents using the tile. */ public float walkableHeight; /** The radius of the agents using the tile. */ public float walkableRadius; /** The maximum climb height of the agents using the tile. */ public float walkableClimb; /** The minimum bounds of the tile's AABB. [(x, y, z)] */ public RcVec3f bmin = new RcVec3f(); /** The maximum bounds of the tile's AABB. [(x, y, z)] */ public RcVec3f bmax = new RcVec3f(); /** The bounding volume quantization factor. */ public float bvQuantFactor; } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtMeshHeader.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtMeshHeader.cs", "repo_id": "ET", "token_count": 1462 }
185
using DotRecast.Core; namespace DotRecast.Detour { public class DtNoOpDtPolygonByCircleConstraint : IDtPolygonByCircleConstraint { public static readonly DtNoOpDtPolygonByCircleConstraint Shared = new DtNoOpDtPolygonByCircleConstraint(); private DtNoOpDtPolygonByCircleConstraint() { } public float[] Apply(float[] polyVerts, RcVec3f circleCenter, float radius) { return polyVerts; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtNoOpDtPolygonByCircleConstraint.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtNoOpDtPolygonByCircleConstraint.cs", "repo_id": "ET", "token_count": 217 }
186
using System; using DotRecast.Core; namespace DotRecast.Detour { /** * Calculate the intersection between a polygon and a circle. A dodecagon is used as an approximation of the circle. */ public class DtStrictDtPolygonByCircleConstraint : IDtPolygonByCircleConstraint { private const int CIRCLE_SEGMENTS = 12; private static readonly float[] UnitCircle = MakeUnitCircle(); public static readonly IDtPolygonByCircleConstraint Shared = new DtStrictDtPolygonByCircleConstraint(); private DtStrictDtPolygonByCircleConstraint() { } private static float[] MakeUnitCircle() { var temp = new float[CIRCLE_SEGMENTS * 3]; for (int i = 0; i < CIRCLE_SEGMENTS; i++) { double a = i * Math.PI * 2 / CIRCLE_SEGMENTS; temp[3 * i] = (float)Math.Cos(a); temp[3 * i + 1] = 0; temp[3 * i + 2] = (float)-Math.Sin(a); } return temp; } public float[] Apply(float[] verts, RcVec3f center, float radius) { float radiusSqr = radius * radius; int outsideVertex = -1; for (int pv = 0; pv < verts.Length; pv += 3) { if (RcVec3f.Dist2DSqr(center, verts, pv) > radiusSqr) { outsideVertex = pv; break; } } if (outsideVertex == -1) { // polygon inside circle return verts; } float[] qCircle = Circle(center, radius); float[] intersection = ConvexConvexIntersection.Intersect(verts, qCircle); if (intersection == null && DtUtils.PointInPolygon(center, verts, verts.Length / 3)) { // circle inside polygon return qCircle; } return intersection; } private float[] Circle(RcVec3f center, float radius) { float[] circle = new float[12 * 3]; for (int i = 0; i < CIRCLE_SEGMENTS * 3; i += 3) { circle[i] = UnitCircle[i] * radius + center.x; circle[i + 1] = center.y; circle[i + 2] = UnitCircle[i + 2] * radius + center.z; } return circle; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtStrictDtPolygonByCircleConstraint.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtStrictDtPolygonByCircleConstraint.cs", "repo_id": "ET", "token_count": 1287 }
187
fileFormatVersion: 2 guid: 11e52dbda0081a04aaf92a7847e5078f folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Io.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Io.meta", "repo_id": "ET", "token_count": 69 }
188
fileFormatVersion: 2 guid: dfddead832c655640ad1fb76eec6e838 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Io/IOUtils.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Io/IOUtils.cs.meta", "repo_id": "ET", "token_count": 93 }
189
fileFormatVersion: 2 guid: bc3eafd30bb2057468b6ea063d9cab0d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcConstants.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcConstants.cs.meta", "repo_id": "ET", "token_count": 96 }
190
fileFormatVersion: 2 guid: 144c657f2a9a9fe41ac27487aebe805c MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcHeightfield.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcHeightfield.cs.meta", "repo_id": "ET", "token_count": 93 }
191
fileFormatVersion: 2 guid: 9d91b765fd48cb047baf8f36204c7c0e MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPolyMeshRaycast.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPolyMeshRaycast.cs.meta", "repo_id": "ET", "token_count": 95 }
192
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security; namespace ET { internal struct AsyncETVoidMethodBuilder { private IStateMachineWrap iStateMachineWrap; // 1. Static Create method. [DebuggerHidden] public static AsyncETVoidMethodBuilder Create() { AsyncETVoidMethodBuilder builder = new(); return builder; } // 2. TaskLike Task property(void) [DebuggerHidden] public ETVoid Task => default; // 3. SetException [DebuggerHidden] public void SetException(Exception e) { if (this.iStateMachineWrap != null) { this.iStateMachineWrap.Recycle(); this.iStateMachineWrap = null; } ETTask.ExceptionHandler.Invoke(e); } // 4. SetResult [DebuggerHidden] public void SetResult() { if (this.iStateMachineWrap != null) { this.iStateMachineWrap.Recycle(); this.iStateMachineWrap = null; } } // 5. AwaitOnCompleted [DebuggerHidden] public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { this.iStateMachineWrap ??= StateMachineWrap<TStateMachine>.Fetch(ref stateMachine); awaiter.OnCompleted(this.iStateMachineWrap.MoveNext); } // 6. AwaitUnsafeOnCompleted [DebuggerHidden] [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { this.iStateMachineWrap ??= StateMachineWrap<TStateMachine>.Fetch(ref stateMachine); awaiter.UnsafeOnCompleted(this.iStateMachineWrap.MoveNext); } // 7. Start [DebuggerHidden] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); } // 8. SetStateMachine [DebuggerHidden] public void SetStateMachine(IAsyncStateMachine stateMachine) { } } }
ET/Unity/Assets/Scripts/ThirdParty/ETTask/AsyncETVoidMethodBuilder.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/ETTask/AsyncETVoidMethodBuilder.cs", "repo_id": "ET", "token_count": 1102 }
193
fileFormatVersion: 2 guid: 96533933eb80840fea1fde1774562a3d folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/Kcp.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/Kcp.meta", "repo_id": "ET", "token_count": 68 }
194
fileFormatVersion: 2 guid: 4444b255d2b878f47895e6e0a19ba413 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/Map.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/Map.meta", "repo_id": "ET", "token_count": 70 }
195
fileFormatVersion: 2 guid: d94ea1ea18a27b34f8ccb7f5db9533bc MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/SortedSet/Node.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/SortedSet/Node.cs.meta", "repo_id": "ET", "token_count": 96 }
196
/* Copyright (C) <2009-2011> <Thorben Linneweber, Jitter Physics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; namespace TrueSync { /// <summary> /// A vector structure. /// </summary> [Serializable] public struct TSVector4 { private static FP ZeroEpsilonSq = TSMath.Epsilon; internal static TSVector4 InternalZero; /// <summary>The X component of the vector.</summary> public FP x; /// <summary>The Y component of the vector.</summary> public FP y; /// <summary>The Z component of the vector.</summary> public FP z; /// <summary>The W component of the vector.</summary> public FP w; #region Static readonly variables /// <summary> /// A vector with components (0,0,0,0); /// </summary> public static readonly TSVector4 zero; /// <summary> /// A vector with components (1,1,1,1); /// </summary> public static readonly TSVector4 one; /// <summary> /// A vector with components /// (FP.MinValue,FP.MinValue,FP.MinValue); /// </summary> public static readonly TSVector4 MinValue; /// <summary> /// A vector with components /// (FP.MaxValue,FP.MaxValue,FP.MaxValue); /// </summary> public static readonly TSVector4 MaxValue; #endregion #region Private static constructor static TSVector4() { one = new TSVector4(1, 1, 1, 1); zero = new TSVector4(0, 0, 0, 0); MinValue = new TSVector4(FP.MinValue); MaxValue = new TSVector4(FP.MaxValue); InternalZero = zero; } #endregion public static TSVector4 Abs(TSVector4 other) { return new TSVector4(FP.Abs(other.x), FP.Abs(other.y), FP.Abs(other.z), FP.Abs(other.z)); } /// <summary> /// Gets the squared length of the vector. /// </summary> /// <returns>Returns the squared length of the vector.</returns> public FP sqrMagnitude { get { return (((this.x * this.x) + (this.y * this.y)) + (this.z * this.z) + (this.w * this.w)); } } /// <summary> /// Gets the length of the vector. /// </summary> /// <returns>Returns the length of the vector.</returns> public FP magnitude { get { FP num = sqrMagnitude; return FP.Sqrt(num); } } public static TSVector4 ClampMagnitude(TSVector4 vector, FP maxLength) { return Normalize(vector) * maxLength; } /// <summary> /// Gets a normalized version of the vector. /// </summary> /// <returns>Returns a normalized version of the vector.</returns> public TSVector4 normalized { get { TSVector4 result = new TSVector4(this.x, this.y, this.z, this.w); result.Normalize(); return result; } } /// <summary> /// Constructor initializing a new instance of the structure /// </summary> /// <param name="x">The X component of the vector.</param> /// <param name="y">The Y component of the vector.</param> /// <param name="z">The Z component of the vector.</param> /// <param name="w">The W component of the vector.</param> public TSVector4(int x, int y, int z, int w) { this.x = (FP)x; this.y = (FP)y; this.z = (FP)z; this.w = (FP)w; } public TSVector4(FP x, FP y, FP z, FP w) { this.x = x; this.y = y; this.z = z; this.w = w; } /// <summary> /// Multiplies each component of the vector by the same components of the provided vector. /// </summary> public void Scale(TSVector4 other) { this.x = x * other.x; this.y = y * other.y; this.z = z * other.z; this.w = w * other.w; } /// <summary> /// Sets all vector component to specific values. /// </summary> /// <param name="x">The X component of the vector.</param> /// <param name="y">The Y component of the vector.</param> /// <param name="z">The Z component of the vector.</param> /// <param name="w">The W component of the vector.</param> public void Set(FP x, FP y, FP z, FP w) { this.x = x; this.y = y; this.z = z; this.w = w; } /// <summary> /// Constructor initializing a new instance of the structure /// </summary> /// <param name="xyz">All components of the vector are set to xyz</param> public TSVector4(FP xyzw) { this.x = xyzw; this.y = xyzw; this.z = xyzw; this.w = xyzw; } public static TSVector4 Lerp(TSVector4 from, TSVector4 to, FP percent) { return from + (to - from) * percent; } /// <summary> /// Builds a string from the JVector. /// </summary> /// <returns>A string containing all three components.</returns> #region public override string ToString() public override string ToString() { return string.Format("({0:f1}, {1:f1}, {2:f1}, {3:f1})", x.AsFloat(), y.AsFloat(), z.AsFloat(), w.AsFloat()); } #endregion /// <summary> /// Tests if an object is equal to this vector. /// </summary> /// <param name="obj">The object to test.</param> /// <returns>Returns true if they are euqal, otherwise false.</returns> #region public override bool Equals(object obj) public override bool Equals(object obj) { if (!(obj is TSVector4)) return false; TSVector4 other = (TSVector4)obj; return (((x == other.x) && (y == other.y)) && (z == other.z) && (w == other.w)); } #endregion /// <summary> /// Multiplies each component of the vector by the same components of the provided vector. /// </summary> public static TSVector4 Scale(TSVector4 vecA, TSVector4 vecB) { TSVector4 result; result.x = vecA.x * vecB.x; result.y = vecA.y * vecB.y; result.z = vecA.z * vecB.z; result.w = vecA.w * vecB.w; return result; } /// <summary> /// Tests if two JVector are equal. /// </summary> /// <param name="value1">The first value.</param> /// <param name="value2">The second value.</param> /// <returns>Returns true if both values are equal, otherwise false.</returns> #region public static bool operator ==(JVector value1, JVector value2) public static bool operator ==(TSVector4 value1, TSVector4 value2) { return (((value1.x == value2.x) && (value1.y == value2.y)) && (value1.z == value2.z) && (value1.w == value2.w)); } #endregion /// <summary> /// Tests if two JVector are not equal. /// </summary> /// <param name="value1">The first value.</param> /// <param name="value2">The second value.</param> /// <returns>Returns false if both values are equal, otherwise true.</returns> #region public static bool operator !=(JVector value1, JVector value2) public static bool operator !=(TSVector4 value1, TSVector4 value2) { if ((value1.x == value2.x) && (value1.y == value2.y) && (value1.z == value2.z)) { return (value1.w != value2.w); } return true; } #endregion /// <summary> /// Gets a vector with the minimum x,y and z values of both vectors. /// </summary> /// <param name="value1">The first value.</param> /// <param name="value2">The second value.</param> /// <returns>A vector with the minimum x,y and z values of both vectors.</returns> #region public static JVector Min(JVector value1, JVector value2) public static TSVector4 Min(TSVector4 value1, TSVector4 value2) { TSVector4 result; TSVector4.Min(ref value1, ref value2, out result); return result; } /// <summary> /// Gets a vector with the minimum x,y and z values of both vectors. /// </summary> /// <param name="value1">The first value.</param> /// <param name="value2">The second value.</param> /// <param name="result">A vector with the minimum x,y and z values of both vectors.</param> public static void Min(ref TSVector4 value1, ref TSVector4 value2, out TSVector4 result) { result.x = (value1.x < value2.x) ? value1.x : value2.x; result.y = (value1.y < value2.y) ? value1.y : value2.y; result.z = (value1.z < value2.z) ? value1.z : value2.z; result.w = (value1.w < value2.w) ? value1.w : value2.w; } #endregion /// <summary> /// Gets a vector with the maximum x,y and z values of both vectors. /// </summary> /// <param name="value1">The first value.</param> /// <param name="value2">The second value.</param> /// <returns>A vector with the maximum x,y and z values of both vectors.</returns> #region public static JVector Max(JVector value1, JVector value2) public static TSVector4 Max(TSVector4 value1, TSVector4 value2) { TSVector4 result; TSVector4.Max(ref value1, ref value2, out result); return result; } public static FP Distance(TSVector4 v1, TSVector4 v2) { return FP.Sqrt((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y - v2.y) + (v1.z - v2.z) * (v1.z - v2.z) + (v1.w - v2.w) * (v1.w - v2.w)); } /// <summary> /// Gets a vector with the maximum x,y and z values of both vectors. /// </summary> /// <param name="value1">The first value.</param> /// <param name="value2">The second value.</param> /// <param name="result">A vector with the maximum x,y and z values of both vectors.</param> public static void Max(ref TSVector4 value1, ref TSVector4 value2, out TSVector4 result) { result.x = (value1.x > value2.x) ? value1.x : value2.x; result.y = (value1.y > value2.y) ? value1.y : value2.y; result.z = (value1.z > value2.z) ? value1.z : value2.z; result.w = (value1.w > value2.w) ? value1.w : value2.w; } #endregion /// <summary> /// Sets the length of the vector to zero. /// </summary> #region public void MakeZero() public void MakeZero() { x = FP.Zero; y = FP.Zero; z = FP.Zero; w = FP.Zero; } #endregion /// <summary> /// Checks if the length of the vector is zero. /// </summary> /// <returns>Returns true if the vector is zero, otherwise false.</returns> #region public bool IsZero() public bool IsZero() { return (this.sqrMagnitude == FP.Zero); } /// <summary> /// Checks if the length of the vector is nearly zero. /// </summary> /// <returns>Returns true if the vector is nearly zero, otherwise false.</returns> public bool IsNearlyZero() { return (this.sqrMagnitude < ZeroEpsilonSq); } #endregion /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The vector to transform.</param> /// <param name="matrix">The transform matrix.</param> /// <returns>The transformed vector.</returns> #region public static JVector Transform(JVector position, JMatrix matrix) public static TSVector4 Transform(TSVector4 position, TSMatrix4x4 matrix) { TSVector4 result; TSVector4.Transform(ref position, ref matrix, out result); return result; } public static TSVector4 Transform(TSVector position, TSMatrix4x4 matrix) { TSVector4 result; TSVector4.Transform(ref position, ref matrix, out result); return result; } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="vector">The vector to transform.</param> /// <param name="matrix">The transform matrix.</param> /// <param name="result">The transformed vector.</param> public static void Transform(ref TSVector vector, ref TSMatrix4x4 matrix, out TSVector4 result) { result.x = vector.x * matrix.M11 + vector.y * matrix.M12 + vector.z * matrix.M13 + matrix.M14; result.y = vector.x * matrix.M21 + vector.y * matrix.M22 + vector.z * matrix.M23 + matrix.M24; result.z = vector.x * matrix.M31 + vector.y * matrix.M32 + vector.z * matrix.M33 + matrix.M34; result.w = vector.x * matrix.M41 + vector.y * matrix.M42 + vector.z * matrix.M43 + matrix.M44; } public static void Transform(ref TSVector4 vector, ref TSMatrix4x4 matrix, out TSVector4 result) { result.x = vector.x * matrix.M11 + vector.y * matrix.M12 + vector.z * matrix.M13 + vector.w * matrix.M14; result.y = vector.x * matrix.M21 + vector.y * matrix.M22 + vector.z * matrix.M23 + vector.w * matrix.M24; result.z = vector.x * matrix.M31 + vector.y * matrix.M32 + vector.z * matrix.M33 + vector.w * matrix.M34; result.w = vector.x * matrix.M41 + vector.y * matrix.M42 + vector.z * matrix.M43 + vector.w * matrix.M44; } #endregion /// <summary> /// Calculates the dot product of two vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>Returns the dot product of both vectors.</returns> #region public static FP Dot(JVector vector1, JVector vector2) public static FP Dot(TSVector4 vector1, TSVector4 vector2) { return TSVector4.Dot(ref vector1, ref vector2); } /// <summary> /// Calculates the dot product of both vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>Returns the dot product of both vectors.</returns> public static FP Dot(ref TSVector4 vector1, ref TSVector4 vector2) { return ((vector1.x * vector2.x) + (vector1.y * vector2.y)) + (vector1.z * vector2.z) + (vector1.w * vector2.w); } #endregion /// <summary> /// Adds two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The sum of both vectors.</returns> #region public static void Add(JVector value1, JVector value2) public static TSVector4 Add(TSVector4 value1, TSVector4 value2) { TSVector4 result; TSVector4.Add(ref value1, ref value2, out result); return result; } /// <summary> /// Adds to vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="result">The sum of both vectors.</param> public static void Add(ref TSVector4 value1, ref TSVector4 value2, out TSVector4 result) { result.x = value1.x + value2.x; result.y = value1.y + value2.y; result.z = value1.z + value2.z; result.w = value1.w + value2.w; } #endregion /// <summary> /// Divides a vector by a factor. /// </summary> /// <param name="value1">The vector to divide.</param> /// <param name="scaleFactor">The scale factor.</param> /// <returns>Returns the scaled vector.</returns> public static TSVector4 Divide(TSVector4 value1, FP scaleFactor) { TSVector4 result; TSVector4.Divide(ref value1, scaleFactor, out result); return result; } /// <summary> /// Divides a vector by a factor. /// </summary> /// <param name="value1">The vector to divide.</param> /// <param name="scaleFactor">The scale factor.</param> /// <param name="result">Returns the scaled vector.</param> public static void Divide(ref TSVector4 value1, FP scaleFactor, out TSVector4 result) { result.x = value1.x / scaleFactor; result.y = value1.y / scaleFactor; result.z = value1.z / scaleFactor; result.w = value1.w / scaleFactor; } /// <summary> /// Subtracts two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The difference of both vectors.</returns> #region public static JVector Subtract(JVector value1, JVector value2) public static TSVector4 Subtract(TSVector4 value1, TSVector4 value2) { TSVector4 result; TSVector4.Subtract(ref value1, ref value2, out result); return result; } /// <summary> /// Subtracts to vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="result">The difference of both vectors.</param> public static void Subtract(ref TSVector4 value1, ref TSVector4 value2, out TSVector4 result) { result.x = value1.x - value2.x; result.y = value1.y - value2.y; result.z = value1.z - value2.z; result.w = value1.w - value2.w; } #endregion /// <summary> /// Gets the hashcode of the vector. /// </summary> /// <returns>Returns the hashcode of the vector.</returns> #region public override int GetHashCode() public override int GetHashCode() { return x.GetHashCode() ^ y.GetHashCode() ^ z.GetHashCode() ^ w.GetHashCode(); } #endregion /// <summary> /// Inverses the direction of the vector. /// </summary> #region public static JVector Negate(JVector value) public void Negate() { this.x = -this.x; this.y = -this.y; this.z = -this.z; this.w = -this.w; } /// <summary> /// Inverses the direction of a vector. /// </summary> /// <param name="value">The vector to inverse.</param> /// <returns>The negated vector.</returns> public static TSVector4 Negate(TSVector4 value) { TSVector4 result; TSVector4.Negate(ref value, out result); return result; } /// <summary> /// Inverses the direction of a vector. /// </summary> /// <param name="value">The vector to inverse.</param> /// <param name="result">The negated vector.</param> public static void Negate(ref TSVector4 value, out TSVector4 result) { result.x = -value.x; result.y = -value.y; result.z = -value.z; result.w = -value.w; } #endregion /// <summary> /// Normalizes the given vector. /// </summary> /// <param name="value">The vector which should be normalized.</param> /// <returns>A normalized vector.</returns> #region public static JVector Normalize(JVector value) public static TSVector4 Normalize(TSVector4 value) { TSVector4 result; TSVector4.Normalize(ref value, out result); return result; } /// <summary> /// Normalizes this vector. /// </summary> public void Normalize() { FP num2 = ((this.x * this.x) + (this.y * this.y)) + (this.z * this.z) + (this.w * this.w); FP num = FP.One / FP.Sqrt(num2); this.x *= num; this.y *= num; this.z *= num; this.w *= num; } /// <summary> /// Normalizes the given vector. /// </summary> /// <param name="value">The vector which should be normalized.</param> /// <param name="result">A normalized vector.</param> public static void Normalize(ref TSVector4 value, out TSVector4 result) { FP num2 = ((value.x * value.x) + (value.y * value.y)) + (value.z * value.z) + (value.w * value.w); FP num = FP.One / FP.Sqrt(num2); result.x = value.x * num; result.y = value.y * num; result.z = value.z * num; result.w = value.w * num; } #endregion #region public static void Swap(ref JVector vector1, ref JVector vector2) /// <summary> /// Swaps the components of both vectors. /// </summary> /// <param name="vector1">The first vector to swap with the second.</param> /// <param name="vector2">The second vector to swap with the first.</param> public static void Swap(ref TSVector4 vector1, ref TSVector4 vector2) { FP temp; temp = vector1.x; vector1.x = vector2.x; vector2.x = temp; temp = vector1.y; vector1.y = vector2.y; vector2.y = temp; temp = vector1.z; vector1.z = vector2.z; vector2.z = temp; temp = vector1.w; vector1.w = vector2.w; vector2.w = temp; } #endregion /// <summary> /// Multiply a vector with a factor. /// </summary> /// <param name="value1">The vector to multiply.</param> /// <param name="scaleFactor">The scale factor.</param> /// <returns>Returns the multiplied vector.</returns> #region public static JVector Multiply(JVector value1, FP scaleFactor) public static TSVector4 Multiply(TSVector4 value1, FP scaleFactor) { TSVector4 result; TSVector4.Multiply(ref value1, scaleFactor, out result); return result; } /// <summary> /// Multiply a vector with a factor. /// </summary> /// <param name="value1">The vector to multiply.</param> /// <param name="scaleFactor">The scale factor.</param> /// <param name="result">Returns the multiplied vector.</param> public static void Multiply(ref TSVector4 value1, FP scaleFactor, out TSVector4 result) { result.x = value1.x * scaleFactor; result.y = value1.y * scaleFactor; result.z = value1.z * scaleFactor; result.w = value1.w * scaleFactor; } #endregion /// <summary> /// Calculates the dot product of two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>Returns the dot product of both.</returns> #region public static FP operator *(JVector value1, JVector value2) public static FP operator *(TSVector4 value1, TSVector4 value2) { return TSVector4.Dot(ref value1, ref value2); } #endregion /// <summary> /// Multiplies a vector by a scale factor. /// </summary> /// <param name="value1">The vector to scale.</param> /// <param name="value2">The scale factor.</param> /// <returns>Returns the scaled vector.</returns> #region public static JVector operator *(JVector value1, FP value2) public static TSVector4 operator *(TSVector4 value1, FP value2) { TSVector4 result; TSVector4.Multiply(ref value1, value2, out result); return result; } #endregion /// <summary> /// Multiplies a vector by a scale factor. /// </summary> /// <param name="value2">The vector to scale.</param> /// <param name="value1">The scale factor.</param> /// <returns>Returns the scaled vector.</returns> #region public static JVector operator *(FP value1, JVector value2) public static TSVector4 operator *(FP value1, TSVector4 value2) { TSVector4 result; TSVector4.Multiply(ref value2, value1, out result); return result; } #endregion /// <summary> /// Subtracts two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The difference of both vectors.</returns> #region public static JVector operator -(JVector value1, JVector value2) public static TSVector4 operator -(TSVector4 value1, TSVector4 value2) { TSVector4 result; TSVector4.Subtract(ref value1, ref value2, out result); return result; } #endregion /// <summary> /// Adds two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The sum of both vectors.</returns> #region public static JVector operator +(JVector value1, JVector value2) public static TSVector4 operator +(TSVector4 value1, TSVector4 value2) { TSVector4 result; TSVector4.Add(ref value1, ref value2, out result); return result; } #endregion /// <summary> /// Divides a vector by a factor. /// </summary> /// <param name="value1">The vector to divide.</param> /// <param name="scaleFactor">The scale factor.</param> /// <returns>Returns the scaled vector.</returns> public static TSVector4 operator /(TSVector4 value1, FP value2) { TSVector4 result; TSVector4.Divide(ref value1, value2, out result); return result; } public TSVector2 ToTSVector2() { return new TSVector2(this.x, this.y); } public TSVector ToTSVector() { return new TSVector(this.x, this.y, this.z); } } }
ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSVector4.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSVector4.cs", "repo_id": "ET", "token_count": 12668 }
197
fileFormatVersion: 2 guid: 34e4bdcc77fe10844b9018f1b0ebde27 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Settings/IgnoreAsmdef/Hotfix/Server.meta/0
{ "file_path": "ET/Unity/Assets/Settings/IgnoreAsmdef/Hotfix/Server.meta", "repo_id": "ET", "token_count": 69 }
198
<linker> <assembly fullname="Unity.Core" preserve="all"/> <assembly fullname="Unity.Mono" preserve="all"/> <assembly fullname="Unity.ThirdParty" preserve="all"/> <assembly fullname="UnityEngine" preserve="all"/> <assembly fullname="System" preserve="all"/> <assembly fullname="CommandLine" preserve="all"/> <assembly fullname="ICSharpCode.SharpZipLib" preserve="all"/> <assembly fullname="MongoDB.Bson" preserve="all"/> <assembly fullname="System.Runtime.CompilerServices.Unsafe" preserve="all"/> <assembly fullname="UnityEngine.AnimationModule" preserve="all" /> <assembly fullname="System.Net.Http" preserve="all" /> <assembly fullname="mscorlib" preserve="all" /> <assembly fullname="UnityEngine.AssetBundleModule" preserve="all" /> <assembly fullname="NLog" preserve="all" /> <assembly fullname="UnityEngine.CoreModule" preserve="all" /> <assembly fullname="UnityEngine.InputLegacyModule" preserve="all" /> </linker>
ET/Unity/Assets/link.xml/0
{ "file_path": "ET/Unity/Assets/link.xml", "repo_id": "ET", "token_count": 313 }
199
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!30 &1 GraphicsSettings: m_ObjectHideFlags: 0 serializedVersion: 14 m_Deferred: m_Mode: 1 m_Shader: {fileID: 69, guid: 0000000000000000f000000000000000, type: 0} m_DeferredReflections: m_Mode: 1 m_Shader: {fileID: 74, guid: 0000000000000000f000000000000000, type: 0} m_ScreenSpaceShadows: m_Mode: 1 m_Shader: {fileID: 64, guid: 0000000000000000f000000000000000, type: 0} m_LegacyDeferred: m_Mode: 1 m_Shader: {fileID: 63, guid: 0000000000000000f000000000000000, type: 0} m_DepthNormals: m_Mode: 1 m_Shader: {fileID: 62, guid: 0000000000000000f000000000000000, type: 0} m_MotionVectors: m_Mode: 1 m_Shader: {fileID: 75, guid: 0000000000000000f000000000000000, type: 0} m_LightHalo: m_Mode: 1 m_Shader: {fileID: 105, guid: 0000000000000000f000000000000000, type: 0} m_LensFlare: m_Mode: 1 m_Shader: {fileID: 102, guid: 0000000000000000f000000000000000, type: 0} m_VideoShadersIncludeMode: 2 m_AlwaysIncludedShaders: - {fileID: 7, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 15104, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 15105, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 15106, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 10782, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 16000, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 17000, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 16001, guid: 0000000000000000f000000000000000, type: 0} m_PreloadedShaders: [] m_PreloadShadersBatchTimeLimit: -1 m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} m_CustomRenderPipeline: {fileID: 11400000, guid: 313955cd6271f5c4985cba4adc30fc8e, type: 2} m_TransparencySortMode: 0 m_TransparencySortAxis: {x: 0, y: 0, z: 1} m_DefaultRenderingPath: 1 m_DefaultMobileRenderingPath: 1 m_TierSettings: [] m_LightmapStripping: 1 m_FogStripping: 1 m_InstancingStripping: 2 m_LightmapKeepPlain: 1 m_LightmapKeepDirCombined: 0 m_LightmapKeepDynamicPlain: 0 m_LightmapKeepDynamicDirCombined: 0 m_LightmapKeepShadowMask: 0 m_LightmapKeepSubtractive: 0 m_FogKeepLinear: 0 m_FogKeepExp: 0 m_FogKeepExp2: 0 m_AlbedoSwatchInfos: [] m_LightsUseLinearIntensity: 1 m_LightsUseColorTemperature: 1 m_DefaultRenderingLayerMask: 1 m_LogWhenShaderIsCompiled: 0 m_SRPDefaultSettings: UnityEngine.Rendering.Universal.UniversalRenderPipeline: {fileID: 11400000, guid: 7995cfbbc1fea9d49b9d9e9b1a4bee57, type: 2}
ET/Unity/ProjectSettings/GraphicsSettings.asset/0
{ "file_path": "ET/Unity/ProjectSettings/GraphicsSettings.asset", "repo_id": "ET", "token_count": 1066 }
200
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!5 &1 TimeManager: m_ObjectHideFlags: 0 Fixed Timestep: 0.02 Maximum Allowed Timestep: 0.33333334 m_TimeScale: 1
ET/Unity/ProjectSettings/TimeManager.asset/0
{ "file_path": "ET/Unity/ProjectSettings/TimeManager.asset", "repo_id": "ET", "token_count": 77 }
201
/* Copyright (c) 2015 Ki Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace ICSharpCode.BamlDecompiler.Baml { internal abstract class BamlNode { public BamlBlockNode Parent { get; set; } public abstract BamlRecordType Type { get; } public object Annotation { get; set; } public abstract BamlRecord Record { get; } public static bool IsHeader(BamlRecord rec) { switch (rec.Type) { case BamlRecordType.ConstructorParametersStart: case BamlRecordType.DocumentStart: case BamlRecordType.ElementStart: case BamlRecordType.KeyElementStart: case BamlRecordType.NamedElementStart: case BamlRecordType.PropertyArrayStart: case BamlRecordType.PropertyComplexStart: case BamlRecordType.PropertyDictionaryStart: case BamlRecordType.PropertyListStart: case BamlRecordType.StaticResourceStart: return true; } return false; } public static bool IsFooter(BamlRecord rec) { switch (rec.Type) { case BamlRecordType.ConstructorParametersEnd: case BamlRecordType.DocumentEnd: case BamlRecordType.ElementEnd: case BamlRecordType.KeyElementEnd: case BamlRecordType.PropertyArrayEnd: case BamlRecordType.PropertyComplexEnd: case BamlRecordType.PropertyDictionaryEnd: case BamlRecordType.PropertyListEnd: case BamlRecordType.StaticResourceEnd: return true; } return false; } public static bool IsMatch(BamlRecord header, BamlRecord footer) { switch (header.Type) { case BamlRecordType.ConstructorParametersStart: return footer.Type == BamlRecordType.ConstructorParametersEnd; case BamlRecordType.DocumentStart: return footer.Type == BamlRecordType.DocumentEnd; case BamlRecordType.KeyElementStart: return footer.Type == BamlRecordType.KeyElementEnd; case BamlRecordType.PropertyArrayStart: return footer.Type == BamlRecordType.PropertyArrayEnd; case BamlRecordType.PropertyComplexStart: return footer.Type == BamlRecordType.PropertyComplexEnd; case BamlRecordType.PropertyDictionaryStart: return footer.Type == BamlRecordType.PropertyDictionaryEnd; case BamlRecordType.PropertyListStart: return footer.Type == BamlRecordType.PropertyListEnd; case BamlRecordType.StaticResourceStart: return footer.Type == BamlRecordType.StaticResourceEnd; case BamlRecordType.ElementStart: case BamlRecordType.NamedElementStart: return footer.Type == BamlRecordType.ElementEnd; } return false; } public static BamlNode Parse(BamlDocument document, CancellationToken token) { Debug.Assert(document.Count > 0 && document[0].Type == BamlRecordType.DocumentStart); BamlBlockNode current = null; var stack = new Stack<BamlBlockNode>(); for (int i = 0; i < document.Count; i++) { token.ThrowIfCancellationRequested(); if (IsHeader(document[i])) { var prev = current; current = new BamlBlockNode { Header = document[i] }; if (prev != null) { prev.Children.Add(current); current.Parent = prev; stack.Push(prev); } } else if (IsFooter(document[i])) { if (current == null) throw new Exception("Unexpected footer."); while (!IsMatch(current.Header, document[i])) { // End record can be omited (sometimes). if (stack.Count > 0) current = stack.Pop(); } current.Footer = document[i]; if (stack.Count > 0) current = stack.Pop(); } else current.Children.Add(new BamlRecordNode(document[i]) { Parent = current }); } Debug.Assert(stack.Count == 0); return current; } } internal class BamlRecordNode : BamlNode { BamlRecord record; public override BamlRecord Record => record; public override BamlRecordType Type => Record.Type; public BamlRecordNode(BamlRecord record) => this.record = record; } internal class BamlBlockNode : BamlNode { public BamlRecord Header { get; set; } public IList<BamlNode> Children { get; } public BamlRecord Footer { get; set; } public override BamlRecord Record => Header; public override BamlRecordType Type => Header.Type; public BamlBlockNode() => Children = new List<BamlNode>(); } }
ILSpy/ICSharpCode.BamlDecompiler/Baml/BamlNode.cs/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/Baml/BamlNode.cs", "repo_id": "ILSpy", "token_count": 1895 }
202
/* Copyright (c) 2015 Ki Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Xml.Linq; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.BamlDecompiler.Baml; using ICSharpCode.BamlDecompiler.Xaml; namespace ICSharpCode.BamlDecompiler { internal class XamlContext { XamlContext(IDecompilerTypeSystem typeSystem) { TypeSystem = typeSystem; NodeMap = new Dictionary<BamlRecord, BamlBlockNode>(); XmlNs = new XmlnsDictionary(); GeneratedMembers = new List<EntityHandle>(); XClassNames = new List<string>(); } Dictionary<ushort, XamlType> typeMap = new Dictionary<ushort, XamlType>(); Dictionary<ushort, XamlProperty> propertyMap = new Dictionary<ushort, XamlProperty>(); Dictionary<string, XNamespace> xmlnsMap = new Dictionary<string, XNamespace>(); public IDecompilerTypeSystem TypeSystem { get; } public CancellationToken CancellationToken { get; private set; } public BamlDecompilerSettings Settings { get; private set; } public BamlContext Baml { get; private set; } public BamlNode RootNode { get; private set; } public IDictionary<BamlRecord, BamlBlockNode> NodeMap { get; } public List<string> XClassNames { get; } public List<EntityHandle> GeneratedMembers { get; } public XmlnsDictionary XmlNs { get; } public static XamlContext Construct(IDecompilerTypeSystem typeSystem, BamlDocument document, CancellationToken token, BamlDecompilerSettings bamlDecompilerOptions) { var ctx = new XamlContext(typeSystem); ctx.CancellationToken = token; ctx.Settings = bamlDecompilerOptions ?? new BamlDecompilerSettings(); ctx.Baml = BamlContext.ConstructContext(typeSystem, document, token); ctx.RootNode = BamlNode.Parse(document, token); ctx.BuildPIMappings(document); ctx.BuildNodeMap(ctx.RootNode as BamlBlockNode); return ctx; } void BuildNodeMap(BamlBlockNode node) { if (node == null) return; NodeMap[node.Header] = node; foreach (var child in node.Children) { if (child is BamlBlockNode childBlock) BuildNodeMap(childBlock); } } void BuildPIMappings(BamlDocument document) { foreach (var record in document) { var piMap = record as PIMappingRecord; if (piMap == null) continue; XmlNs.SetPIMapping(piMap.XmlNamespace, piMap.ClrNamespace, Baml.ResolveAssembly(piMap.AssemblyId).FullAssemblyName); } } public XamlType ResolveType(ushort id) { if (typeMap.TryGetValue(id, out var xamlType)) return xamlType; IType type; IModule assembly; string fullAssemblyName; if (id > 0x7fff) { type = Baml.KnownThings.Types((KnownTypes)(short)-unchecked((short)id)); assembly = type.GetDefinition().ParentModule; fullAssemblyName = assembly.FullAssemblyName; } else { var typeRec = Baml.TypeIdMap[id]; (fullAssemblyName, assembly) = Baml.ResolveAssembly(typeRec.AssemblyId); type = ReflectionHelper.ParseReflectionName(typeRec.TypeFullName).Resolve(new SimpleTypeResolveContext(TypeSystem)); } var clrNs = type.Namespace; var xmlNs = XmlNs.LookupXmlns(fullAssemblyName, clrNs); typeMap[id] = xamlType = new XamlType(assembly, fullAssemblyName, clrNs, type.Name, GetXmlNamespace(xmlNs)) { ResolvedType = type }; return xamlType; } public XamlProperty ResolveProperty(ushort id) { if (propertyMap.TryGetValue(id, out var xamlProp)) return xamlProp; XamlType type; string name; IMember member; if (id > 0x7fff) { var knownProp = Baml.KnownThings.Members((KnownMembers)unchecked((short)-(short)id)); type = ResolveType(unchecked((ushort)(short)-(short)knownProp.Parent)); name = knownProp.Name; member = knownProp.Property; } else { var attrRec = Baml.AttributeIdMap[id]; type = ResolveType(attrRec.OwnerTypeId); name = attrRec.Name; member = null; } propertyMap[id] = xamlProp = new XamlProperty(type, name) { ResolvedMember = member }; xamlProp.TryResolve(); return xamlProp; } public string ResolveString(ushort id) { if (id > 0x7fff) return Baml.KnownThings.Strings(unchecked((short)-id)); else if (Baml.StringIdMap.ContainsKey(id)) return Baml.StringIdMap[id].Value; return null; } public XNamespace GetXmlNamespace(string xmlns) { if (xmlns == null) return null; if (!xmlnsMap.TryGetValue(xmlns, out var ns)) xmlnsMap[xmlns] = ns = XNamespace.Get(xmlns); return ns; } public const string KnownNamespace_Xaml = "http://schemas.microsoft.com/winfx/2006/xaml"; public const string KnownNamespace_Presentation = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; public const string KnownNamespace_PresentationOptions = "http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"; public string TryGetXmlNamespace(IModule assembly, string typeNamespace) { if (assembly == null) return null; HashSet<string> possibleXmlNs = new HashSet<string>(); foreach (var attr in assembly.GetAssemblyAttributes().Where(a => a.AttributeType.FullName == "System.Windows.Markup.XmlnsDefinitionAttribute")) { Debug.Assert(attr.FixedArguments.Length == 2); if (attr.FixedArguments.Length != 2) continue; var xmlNs = attr.FixedArguments[0].Value as string; var typeNs = attr.FixedArguments[1].Value as string; Debug.Assert((object)xmlNs != null && (object)typeNs != null); if ((object)xmlNs == null || (object)typeNs == null) continue; if (typeNamespace == typeNs) possibleXmlNs.Add(xmlNs); } if (possibleXmlNs.Contains(KnownNamespace_Presentation)) return KnownNamespace_Presentation; return possibleXmlNs.FirstOrDefault(); } public XName GetKnownNamespace(string name, string xmlNamespace, XElement context = null) { var xNs = GetXmlNamespace(xmlNamespace); XName xName; if (context != null && xNs == context.GetDefaultNamespace()) xName = name; else xName = xNs + name; return xName; } public XName GetPseudoName(string name) => XNamespace.Get("https://github.com/icsharpcode/ILSpy").GetName(name); } }
ILSpy/ICSharpCode.BamlDecompiler/XamlContext.cs/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/XamlContext.cs", "repo_id": "ILSpy", "token_count": 2649 }
203
// Copyright (c) 2022 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Reflection; using System.Runtime.Loader; namespace ICSharpCode.Decompiler.TestRunner; public static class Program { static int Main(string[] args) { AssemblyLoadContext context = new("TestRunner", isCollectible: true); context.Resolving += ContextResolving; try { var mainAssembly = context.LoadFromAssemblyPath(args[0]); int paramCount = mainAssembly.EntryPoint!.GetParameters().Length; object? result = mainAssembly.EntryPoint!.Invoke(null, paramCount == 0 ? new object[0] : new object[1] { new string[0] }); return result is int i ? i : 0; } catch (Exception ex) { Console.Error.WriteLine("TestRunner crashed:"); Console.Error.WriteLine(ex.ToString()); return -1; } finally { context.Unload(); context.Resolving -= ContextResolving; } } private static Assembly? ContextResolving(AssemblyLoadContext context, AssemblyName name) { return null; } }
ILSpy/ICSharpCode.Decompiler.TestRunner/Program.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.TestRunner/Program.cs", "repo_id": "ILSpy", "token_count": 607 }
204
// Copyright (c) 2020 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using ICSharpCode.Decompiler.CSharp.ProjectDecompiler; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests { [TestFixture] public sealed class TargetFrameworkTests { [TestCase(-1)] [TestCase(0)] [TestCase(1)] [TestCase(99)] [TestCase(int.MinValue)] public void VerifyThrowsForInvalidVersion(int invalidVersion) { // Arrange - nothing // Act void CreateInstance() => new TargetFramework(identifier: null, invalidVersion, profile: null); // Assert Assert.Throws<ArgumentException>(CreateInstance); } [TestCase(100, "v1.0")] [TestCase(102, "v1.0.2")] [TestCase(130, "v1.3")] [TestCase(145, "v1.4.5")] [TestCase(1670, "v16.7")] [TestCase(1800, "v18.0")] public void VerifyVersion(int version, string expectedVersion) { // Arrange - nothing // Act var targetFramework = new TargetFramework(identifier: null, version, profile: null); // Assert Assert.That(targetFramework.VersionNumber, Is.EqualTo(version)); Assert.That(targetFramework.VersionString, Is.EqualTo(expectedVersion)); } [Test] public void VerifyPortableLibrary() { // Arrange const string identifier = ".NETPortable"; // Act var targetFramework = new TargetFramework(identifier, 100, profile: null); // Assert Assert.That(targetFramework.IsPortableClassLibrary); Assert.That(targetFramework.Identifier, Is.EqualTo(identifier)); } [Test] [Pairwise] public void VerifyIdentifierAndProfile( [Values(null, "", ".NETFramework")] string identifier, [Values(null, "", ".Client")] string profile) { // Arrange - nothing // Act var targetFramework = new TargetFramework(identifier, 100, profile); // Assert Assert.That(targetFramework.Identifier, Is.EqualTo(identifier)); Assert.That(targetFramework.Profile, Is.EqualTo(profile)); } [TestCase(null, 350, "net35")] [TestCase(".NETFramework", 350, "net35")] [TestCase(".NETFramework", 400, "net40")] [TestCase(".NETFramework", 451, "net451")] [TestCase(".NETCoreApp", 200, "netcoreapp2.0")] [TestCase(".NETCoreApp", 310, "netcoreapp3.1")] [TestCase(".NETStandard", 130, "netstandard1.3")] [TestCase(".NETStandard", 200, "netstandard2.0")] [TestCase("Silverlight", 400, "sl4")] [TestCase("Silverlight", 550, "sl5")] [TestCase(".NETCore", 450, "netcore45")] [TestCase(".NETCore", 451, "netcore451")] [TestCase("WindowsPhone", 700, "wp7")] [TestCase("WindowsPhone", 810, "wp81")] [TestCase(".NETMicroFramework", 100, "netmf")] [TestCase(".NETMicroFramework", 210, "netmf")] [TestCase(".NETPortable", 100, null)] [TestCase("Unsupported", 100, null)] public void VerifyMoniker(string identifier, int version, string expectedMoniker) { // Arrange - nothing // Act var targetFramework = new TargetFramework(identifier, version, profile: null); // Assert Assert.That(targetFramework.Moniker, Is.EqualTo(expectedMoniker)); } } }
ILSpy/ICSharpCode.Decompiler.Tests/ProjectDecompiler/TargetFrameworkTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/ProjectDecompiler/TargetFrameworkTests.cs", "repo_id": "ILSpy", "token_count": 1441 }
205
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness { class DeconstructionTests { public static void Main() { new DeconstructionTests().Test(); } public struct MyInt { public static implicit operator int(MyInt x) { Console.WriteLine("int op_Implicit(MyInt)"); return 0; } public static implicit operator MyInt(int x) { Console.WriteLine("MyInt op_Implicit(int)"); return default(MyInt); } } private class DeconstructionSource<T, T2> { public int Dummy { get; set; } public void Deconstruct(out T a, out T2 b) { Console.WriteLine("Deconstruct"); a = default(T); b = default(T2); } } private class AssignmentTargets { int id; public AssignmentTargets(int id) { this.id = id; } public int IntField; public int? NullableIntField; public MyInt MyIntField; public MyInt? NullableMyIntField; public MyInt My { get { Console.WriteLine($"{id}.get_My()"); return default(MyInt); } set { Console.WriteLine($"{id}.set_My({value})"); } } public MyInt? NMy { get { Console.WriteLine($"{id}.get_NMy()"); return default(MyInt?); } set { Console.WriteLine($"{id}.set_NMy({value})"); } } public int IntProperty { get { Console.WriteLine($"{id}.get_IntProperty()"); return default(int); } set { Console.WriteLine($"{id}.set_IntProperty({value})"); } } public uint UIntProperty { get { Console.WriteLine($"{id}.get_UIntProperty()"); return default(uint); } set { Console.WriteLine($"{id}.set_UIntProperty({value})"); } } } private DeconstructionSource<T, T2> GetSource<T, T2>() { Console.WriteLine("GetSource()"); return new DeconstructionSource<T, T2>(); } private (T, T2) GetTuple<T, T2>() { Console.WriteLine("GetTuple<T, T2>()"); return default(ValueTuple<T, T2>); } private (T, T2, T3) GetTuple<T, T2, T3>() { Console.WriteLine("GetTuple<T, T2, T3>()"); return default(ValueTuple<T, T2, T3>); } private AssignmentTargets Get(int i) { Console.WriteLine($"Get({i})"); return new AssignmentTargets(i); } public void Test() { Property_NoDeconstruction_SwappedAssignments(); Property_NoDeconstruction_SwappedInits(); Property_IntToUIntConversion(); NoDeconstruction_NotUsingConver(); NoDeconstruction_NotUsingConver_Tuple(); NullReferenceException_Field_Deconstruction(out _); NullReferenceException_RefLocalReferencesField_Deconstruction(out _); NullReferenceException_RefLocalReferencesArrayElement_Deconstruction(out _, null); DeconstructTupleSameVar(("a", "b")); DeconstructTupleListForEachSameVar(new List<(string, string)> { ("a", "b") }); } public void Property_NoDeconstruction_SwappedAssignments() { Console.WriteLine("Property_NoDeconstruction_SwappedAssignments:"); AssignmentTargets customDeconstructionAndConversion = Get(0); AssignmentTargets customDeconstructionAndConversion2 = Get(1); GetSource<MyInt?, MyInt>().Deconstruct(out MyInt? x, out MyInt y); MyInt myInt2 = customDeconstructionAndConversion2.My = y; MyInt? myInt4 = customDeconstructionAndConversion.NMy = x; } public void Property_NoDeconstruction_SwappedInits() { Console.WriteLine("Property_NoDeconstruction_SwappedInits:"); AssignmentTargets customDeconstructionAndConversion = Get(1); (Get(0).NMy, customDeconstructionAndConversion.My) = GetSource<MyInt?, MyInt>(); } public void Property_IntToUIntConversion() { Console.WriteLine("Property_IntToUIntConversion:"); AssignmentTargets t0 = Get(0); AssignmentTargets t1 = Get(1); int a; uint b; GetSource<int, uint>().Deconstruct(out a, out b); t0.UIntProperty = (uint)a; t1.IntProperty = (int)b; } public void NoDeconstruction_NotUsingConver() { Console.WriteLine("NoDeconstruction_NotUsingConver:"); AssignmentTargets t0 = Get(0); int a; uint b; GetSource<int, uint>().Deconstruct(out a, out b); long c = a; t0.IntProperty = a; t0.UIntProperty = b; Console.WriteLine(c); } public void NoDeconstruction_NotUsingConver_Tuple() { Console.WriteLine("NoDeconstruction_NotUsingConver_Tuple:"); AssignmentTargets t0 = Get(0); var t = GetTuple<int, uint>(); long c = t.Item1; t0.IntProperty = t.Item1; t0.UIntProperty = t.Item2; Console.WriteLine(c); } public void NullReferenceException_Field_Deconstruction(out int a) { try { AssignmentTargets t0 = null; (t0.IntField, a) = GetSource<int, int>(); } catch (Exception ex) { a = 0; Console.WriteLine(ex.GetType().FullName); } } public void NullReferenceException_RefLocalReferencesField_Deconstruction(out int a) { try { AssignmentTargets t0 = null; ref int i = ref t0.IntField; (i, a) = GetSource<int, int>(); } catch (Exception ex) { a = 0; Console.WriteLine(ex.GetType().FullName); } } public void NullReferenceException_RefLocalReferencesArrayElement_Deconstruction(out int a, int[] arr) { try { ref int i = ref arr[0]; (i, a) = GetSource<int, int>(); } catch (Exception ex) { a = 0; Console.WriteLine(ex.GetType().FullName); } } public void DeconstructTupleSameVar((string, string) tuple) { Console.WriteLine("DeconstructTupleSameVar:"); string a; a = tuple.Item1; a = tuple.Item2; Console.WriteLine(a); } public void DeconstructTupleListForEachSameVar(List<(string, string)> tuples) { Console.WriteLine("DeconstructTupleListForEachSameVar:"); foreach (var tuple in tuples) { string a; a = tuple.Item1; a = tuple.Item2; Console.WriteLine(a); } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/DeconstructionTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/DeconstructionTests.cs", "repo_id": "ILSpy", "token_count": 2579 }
206
open System let disposable() = { new IDisposable with member x.Dispose() = () } let getSeq() = seq { yield 1; } let getList() = [ 1 ] let getArray() = [| 1 |] [<EntryPoint>] let main argv = // nested using scopes? use disp1 = use disp2 = disposable() Console.WriteLine "Hello 1" disposable() // for loop over seq for i in getSeq() do Console.WriteLine i // for loop over list for i in getList() do Console.WriteLine i // for loop over array for i in getArray() do Console.WriteLine i 0 // return an integer exit code
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpLoops.fs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpLoops.fs", "repo_id": "ILSpy", "token_count": 274 }
207
using System; public sealed class EvType : MulticastDelegate { } [Serializable] public class OwningClass { public event EvType EvName; }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1145.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1145.cs", "repo_id": "ILSpy", "token_count": 47 }
208
// Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly ConsoleApp11 { .ver 1:0:0:0 } .module ConsoleApp11.exe // MVID: {B973FCD6-A9C4-48A9-8291-26DDC248E208} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00020003 // ILONLY 32BITPREFERRED // Image base: 0x000001C4B6C90000 .class private auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.ILPretty.BaseClass extends [mscorlib]System.Object { .field public int32 importsClausePosition } .class private auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1681 extends ICSharpCode.Decompiler.Tests.TestCases.ILPretty.BaseClass { .method public hidebysig instance void Test() cil managed { // Code size 18 (0x12) .maxstack 8 ldarg.0 ldfld int32 class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.BaseClass::importsClausePosition pop ret } // end of method Issue1681::Test }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1681.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1681.il", "repo_id": "ILSpy", "token_count": 461 }
209
.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly Issue684 { .ver 1:0:0:0 } .module Issue684.exe .class public auto ansi abstract sealed Issue684 extends [mscorlib]System.Object { // Methods .method static privatescope int32 Main$PST06000001 ( string[] '' ) cil managed { // Method begins at RVA 0x2050 // Code size 196 (0xc4) .maxstack 11 .entrypoint .locals init ( [0] int32, [1] int32, [2] int32, [3] int32[], [4] int32 ) IL_0000: ldc.i4 1000 IL_0005: newarr [mscorlib]System.Int32 IL_000a: stloc.3 IL_000b: call string [mscorlib]System.Console::ReadLine() IL_0010: call int32 [mscorlib]System.Int32::Parse(string) IL_0015: stloc.2 IL_0016: ldloc.2 IL_0017: ldc.i4 1000 IL_001c: clt IL_001e: ldc.i4.0 IL_001f: ceq IL_0021: dup IL_0022: brtrue IL_0030 IL_0027: pop IL_0028: ldloc.2 IL_0029: ldc.i4 2 IL_002e: clt IL_0030: brfalse IL_0045 IL_0035: ldc.i4 1 IL_003a: neg IL_003b: call void [mscorlib]System.Console::WriteLine(int32) IL_0040: br IL_00c2 IL_0045: ldc.i4 2 IL_004a: stloc.0 IL_004b: ldc.i4 2 IL_0050: stloc.1 // loop start (head: IL_0051) IL_0051: ldloc.1 IL_0052: ldloc.2 IL_0053: cgt IL_0055: ldc.i4.0 IL_0056: ceq IL_0058: brfalse IL_00c2 IL_005d: ldloc.1 IL_005e: call void [mscorlib]System.Console::WriteLine(int32) // loop start (head: IL_0063) IL_0063: ldloc.0 IL_0064: ldloc.2 IL_0065: cgt IL_0067: ldc.i4.0 IL_0068: ceq IL_006a: brfalse IL_0088 IL_006f: ldc.i4 1 IL_0074: stloc.s 4 IL_0076: ldloc.3 IL_0077: ldloc.0 IL_0078: ldloc.s 4 IL_007a: stelem.any [mscorlib]System.Int32 IL_007f: ldloc.0 IL_0080: ldloc.1 IL_0081: add IL_0082: stloc.0 IL_0083: br IL_0063 // end loop IL_0088: ldloc.1 IL_0089: stloc.0 // loop start (head: IL_008a) IL_008a: ldloc.0 IL_008b: ldloc.2 IL_008c: cgt IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: dup IL_0092: brfalse IL_00a9 IL_0097: pop IL_0098: ldloc.3 IL_0099: ldloc.0 IL_009a: ldelem.any [mscorlib]System.Int32 IL_009f: ldc.i4 0 IL_00a4: ceq IL_00a6: ldc.i4.0 IL_00a7: ceq IL_00a9: brfalse IL_00bb IL_00ae: ldloc.0 IL_00af: ldc.i4 1 IL_00b4: add IL_00b5: stloc.0 IL_00b6: br IL_008a // end loop IL_00bb: ldloc.0 IL_00bc: stloc.1 IL_00bd: br IL_0051 // end loop IL_00c2: ldc.i4.0 IL_00c3: ret } // end of method Program::Main } // end of class Issue684
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue684.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue684.il", "repo_id": "ILSpy", "token_count": 1513 }
210
<?xml version="1.0" encoding="utf-8"?> <symbols> <files> <file id="1" name="ICSharpCode.Decompiler.Tests.TestCases.PdbGen\CustomPdbId.cs" language="C#" checksumAlgorithm="SHA256"><![CDATA[using System; namespace ICSharpCode.Decompiler.Tests.TestCases.PdbGen; public class CustomPdbId { public static void Main(string[] args) { Console.ReadKey(); Console.WriteLine("Hello World!"); Console.ReadKey(); } } ]]></file> </files> </symbols>
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/PdbGen/CustomPdbId.xml/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/PdbGen/CustomPdbId.xml", "repo_id": "ILSpy", "token_count": 181 }
211
#pragma warning disable format // Copyright (c) 2018 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Runtime.InteropServices; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class CS73_StackAllocInitializers { [StructLayout(LayoutKind.Sequential, Size = 5)] private struct StructWithSize5 { public byte a; public byte b; public byte c; public byte d; public byte e; public StructWithSize5(byte a, byte b, byte c, byte d, byte e) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; } } #if CS80 private class NestedContext1 { public NestedContext1(object result) { } public NestedContext1() : this(UseNested(GetInt(), stackalloc int[2] { GetInt(), GetInt() })) { } } public static object UseNested(object a, Span<int> span) { return null; } public static int GetInt() { return 42; } #endif public unsafe string SimpleStackAllocStruct1() { StructWithSize5* ptr = stackalloc StructWithSize5[4] { new StructWithSize5(1, 2, 3, 4, 5), new StructWithSize5(11, 22, 33, 44, 55), new StructWithSize5(1, 4, 8, 6, 2), new StructWithSize5(12, 23, 34, 45, 56) }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocBool() { bool* ptr = stackalloc bool[4] { false, true, false, true }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string DoNotInlineTest() { bool* ptr = stackalloc bool[4] { false, true, false, true }; return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocByte() { byte* ptr = stackalloc byte[2] { 0, 1 }; Console.WriteLine(*ptr); return UsePointer(ptr); } public unsafe string SimpleStackAllocPrimesAsBytes() { byte* ptr = stackalloc byte[55] { 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 }; Console.WriteLine(*ptr); return UsePointer(ptr); } public unsafe string SimpleStackAllocChar() { char* ptr = stackalloc char[4] { '1', '2', '3', '4' }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocCharAlphabet() { char* ptr = stackalloc char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocSByte() { sbyte* ptr = stackalloc sbyte[3] { 1, 2, 3 }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocInt16() { short* ptr = stackalloc short[3] { 1, 2, 3 }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocUInt16() { ushort* ptr = stackalloc ushort[3] { 1, 2, 3 }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocInt32() { int* ptr = stackalloc int[3] { 1, 2, 3 }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocInt32(int a, int b, int c) { int* ptr = stackalloc int[6] { 1, a, 2, b, 3, c }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocInt32Fibonacci() { int* ptr = stackalloc int[17] { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597 }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocUInt32() { uint* ptr = stackalloc uint[3] { 1u, 2u, 3u }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocInt64() { long* ptr = stackalloc long[3] { 1L, 2L, 3L }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocUInt64() { ulong* ptr = stackalloc ulong[3] { 1uL, 2uL, 3uL }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string SimpleStackAllocInt32NonConstant(int a, int b, int c) { int* ptr = stackalloc int[6] { 0, 1, 0, a, b, c }; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string NotAnInitializer(int a, int b, int c) { int* ptr = stackalloc int[6]; ptr[1] = a; ptr[3] = b; ptr[5] = c; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); } public unsafe string NegativeOffsets(int a, int b, int c) { #if OPT byte* num = stackalloc byte[12]; *(int*)num = 1; *(int*)(num - 4) = 2; *(int*)(num - 8) = 3; int* ptr = (int*)num; Console.WriteLine(*ptr); return UsePointer((byte*)ptr); #else byte* ptr = stackalloc byte[12]; *(int*)ptr = 1; *(int*)(ptr - 4) = 2; *(int*)(ptr - 8) = 3; int* ptr2 = (int*)ptr; Console.WriteLine(*ptr2); return UsePointer((byte*)ptr2); #endif } public unsafe string UsePointer(byte* ptr) { return ptr->ToString(); } public string GetSpan() { Span<int> span = stackalloc int[GetSize()]; return UseSpan(span); } public string GetSpan2() { Span<int> span = stackalloc int[4] { 1, 2, 3, 4 }; return UseSpan(span); } public string GetSpan3() { Span<decimal> span = stackalloc decimal[GetSize()]; return UseSpan(span); } public string GetSpan4() { Span<decimal> span = stackalloc decimal[4] { 1m, 2m, 3m, 4m }; return UseSpan(span); } public void Issue2103a() { Span<byte> span = stackalloc byte[3] { 1, 2, 3 }; Console.WriteLine(span[2] + span[0]); } public void Issue2103b() { Span<byte> span = stackalloc byte[3]; Console.WriteLine(span[0] + span[1]); } public void Issue2103c() { Console.WriteLine((stackalloc byte[3] { 1, 2, 3 })[2]); } public void Issue2103d() { Console.WriteLine((stackalloc byte[3])[1]); } public string UseSpan(Span<int> span) { throw new NotImplementedException(); } public string UseSpan(Span<decimal> span) { throw new NotImplementedException(); } public int GetSize() { throw new NotImplementedException(); } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/CS73_StackAllocInitializers.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/CS73_StackAllocInitializers.cs", "repo_id": "ILSpy", "token_count": 3094 }
212
using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class DynamicTests { private class Base { public Base(object baseObj) { } } private class Derived : Base { public Derived(dynamic d) : base((object)d) { } } private struct MyValueType { private readonly dynamic _getOnlyProperty; public dynamic Field; #if CS60 public dynamic GetOnlyProperty => _getOnlyProperty; #else public dynamic GetOnlyProperty { get { return _getOnlyProperty; } } #endif public dynamic Property { get; set; } public void Method(dynamic a) { } } public interface I { } private static dynamic field; private static volatile dynamic volatileField; private static object objectField; public dynamic Property { get; set; } public DynamicTests() { } public DynamicTests(dynamic test) { } public DynamicTests(DynamicTests test) { } private static void CallWithOut(out dynamic d) { d = null; } #if CS70 private static void CallWithIn(in dynamic d) { } #endif private static void CallWithRef(ref dynamic d) { } private static void RefCallSiteTests() { #if CS70 CallWithOut(out var d); CallWithIn(in d); #else dynamic d; CallWithOut(out d); #endif CallWithRef(ref d); d.SomeCall(); } private static void InvokeConstructor() { DynamicTests dynamicTests = new DynamicTests(); dynamic val = new DynamicTests(); val.Test(new UnauthorizedAccessException()); dynamic val2 = new DynamicTests(val); val2.Get(new DynamicTests((DynamicTests)val)); val2.Call(new DynamicTests((dynamic)dynamicTests)); } private static dynamic InlineAssign(object a, out dynamic b) { return b = ((dynamic)a).Test; } private static dynamic SelfReference(dynamic d) { return d[d, d] = d; } private static dynamic LongArgumentListFunc(dynamic d) { // Func`13 return d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } private static void LongArgumentListAction(dynamic d) { // Action`13 d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); } private static void DynamicThrow() { try { throw (Exception)field; } catch (Exception ex) { Console.WriteLine(ex.ToString()); throw; } } private static void MemberAccess(dynamic a) { a.Test1(); a.GenericTest<int, int>(); a.Test2(1); a.Test3(a.InnerTest(1, 2, 3, 4, 5)); a.Test4(2, null, a.Index[0]); a.Test5(a, a.Number, a.String); a[0] = 3; a.Index[a.Number] = 5; a.Index[a.Number] += 5; a.Setter = new DynamicTests(); a.Setter2 = 5; } private static void StructMemberAccess(MyValueType valueType) { valueType.Field = 0; valueType.Field += 5; valueType.Field[1] = 5; valueType.Field.CallMe(); DynamicTests.Casts(valueType.GetOnlyProperty); valueType.GetOnlyProperty.CallMe(); valueType.Property = 0; valueType.Property += 5; valueType.Property[1] = 5; valueType.Property.CallMe(5.ToDynamic((object)valueType.Property.Call())); valueType.Method(valueType.GetOnlyProperty + valueType.Field); } private static void RequiredCasts() { ((dynamic)objectField).A = 5; ((dynamic)objectField).B += 5; ((dynamic)objectField).Call(); ((object)field).ToString(); field.Call("Hello World"); field.Call((object)"Hello World"); field.Call((dynamic)"Hello World"); } private void StaticCallWithDynamicArgument(dynamic d) { M3(d + 5); } private static void StaticCallWithDynamicArgumentInStaticContext(dynamic d) { DynamicTests.M3(d + 5); } private static void DynamicCallWithString() { field.Call("Hello World"); } private static void DynamicCallWithNamedArgs() { field.Call(a: "Hello World"); } private static void DynamicCallWithRefOutArg(int a, out int b) { field.Call(ref a, out b); } private static void DynamicCallWithStringCastToObj() { field.Call((object)"Hello World"); } private static void DynamicCallWithStringCastToDynamic() { field.Call((dynamic)"Hello World"); } private static void DynamicCallWithStringCastToDynamic2() { field.Call((dynamic)"Hello World", 5, null); } private static void DynamicCallWithStringCastToDynamic3() { field.Call((dynamic)"Hello World", 5u, null); } private static void Invocation(dynamic a, dynamic b) { a(null, b.Test()); } private static dynamic Test1(dynamic a) { dynamic val = a.IndexedProperty; return val[0]; } private static dynamic Test2(dynamic a) { return a.IndexedProperty[0]; } private static void ArithmeticBinaryOperators(dynamic a, dynamic b) { DynamicTests.MemberAccess(a + b); DynamicTests.MemberAccess(a + 1); DynamicTests.MemberAccess(a + null); DynamicTests.MemberAccess(a - b); DynamicTests.MemberAccess(a - 1); DynamicTests.MemberAccess(a - null); DynamicTests.MemberAccess(a * b); DynamicTests.MemberAccess(a * 1); DynamicTests.MemberAccess(a * null); DynamicTests.MemberAccess(a / b); DynamicTests.MemberAccess(a / 1); DynamicTests.MemberAccess(a / null); DynamicTests.MemberAccess(a % b); DynamicTests.MemberAccess(a % 1); DynamicTests.MemberAccess(a % null); } private static void CheckedArithmeticBinaryOperators(dynamic a, dynamic b) { checked { DynamicTests.MemberAccess(a + b); DynamicTests.MemberAccess(a + 1); DynamicTests.MemberAccess(a + null); DynamicTests.MemberAccess(a - b); DynamicTests.MemberAccess(a - 1); DynamicTests.MemberAccess(a - null); DynamicTests.MemberAccess(a * b); DynamicTests.MemberAccess(a * 1); DynamicTests.MemberAccess(a * null); DynamicTests.MemberAccess(a / b); DynamicTests.MemberAccess(a / 1); DynamicTests.MemberAccess(a / null); DynamicTests.MemberAccess(a % b); DynamicTests.MemberAccess(a % 1); DynamicTests.MemberAccess(a % null); } } private static void UncheckedArithmeticBinaryOperators(dynamic a, dynamic b) { checked { DynamicTests.MemberAccess(a + b); DynamicTests.MemberAccess(a + 1); DynamicTests.MemberAccess(a + null); DynamicTests.MemberAccess(unchecked(a - b)); DynamicTests.MemberAccess(a - 1); DynamicTests.MemberAccess(a - null); DynamicTests.MemberAccess(unchecked(a * b)); DynamicTests.MemberAccess(a * 1); DynamicTests.MemberAccess(a * null); DynamicTests.MemberAccess(a / b); DynamicTests.MemberAccess(a / 1); DynamicTests.MemberAccess(a / null); DynamicTests.MemberAccess(a % b); DynamicTests.MemberAccess(a % 1); DynamicTests.MemberAccess(a % null); } } private static void RelationalOperators(dynamic a, dynamic b) { DynamicTests.MemberAccess(a == b); DynamicTests.MemberAccess(a == 1); DynamicTests.MemberAccess(a == null); DynamicTests.MemberAccess(a != b); DynamicTests.MemberAccess(a != 1); DynamicTests.MemberAccess(a != null); DynamicTests.MemberAccess(a < b); DynamicTests.MemberAccess(a < 1); DynamicTests.MemberAccess(a < null); DynamicTests.MemberAccess(a > b); DynamicTests.MemberAccess(a > 1); DynamicTests.MemberAccess(a > null); DynamicTests.MemberAccess(a >= b); DynamicTests.MemberAccess(a >= 1); DynamicTests.MemberAccess(a >= null); DynamicTests.MemberAccess(a <= b); DynamicTests.MemberAccess(a <= 1); DynamicTests.MemberAccess(a <= null); } private static void Casts(dynamic a) { Console.WriteLine(); MemberAccess((int)a); MemberAccess(checked((int)a)); } private static void M(object o) { } private static void M2(dynamic d) { } private static void M3(int i) { } private static void NotDynamicDispatch(dynamic d) { DynamicTests.M(d); M((object)d); DynamicTests.M2(d); M2((object)d); } private static void CompoundAssignment(dynamic a, dynamic b) { a.Setter2 += 5; a.Setter2 -= 1; a.Setter2 *= 2; a.Setter2 /= 5; a.Setter2 += b; a.Setter2 -= b; a.Setter2 *= b; a.Setter2 /= b; field.Setter += 5; field.Setter -= 5; } private static void InlineCompoundAssignment(dynamic a, dynamic b) { Console.WriteLine(a.Setter2 += 5); Console.WriteLine(a.Setter2 -= 1); Console.WriteLine(a.Setter2 *= 2); Console.WriteLine(a.Setter2 /= 5); Console.WriteLine(a.Setter2 += b); Console.WriteLine(a.Setter2 -= b); Console.WriteLine(a.Setter2 *= b); Console.WriteLine(a.Setter2 /= b); } private static void UnaryOperators(dynamic a) { // TODO : beautify inc/dec on locals and fields //a--; //a++; //--a; //++a; DynamicTests.Casts(-a); DynamicTests.Casts(+a); } private static void Loops(dynamic list) { foreach (dynamic item in list) { DynamicTests.UnaryOperators(item); } } private static void If(dynamic a, dynamic b) { if (a == b) { Console.WriteLine("Equal"); } } private static void If2(dynamic a, dynamic b) { if (a == null || b == null) { Console.WriteLine("One is null"); } } private static void If3(dynamic a, dynamic b) { if (a == null && b == null) { Console.WriteLine("Both are null"); } } private static void If4(dynamic a, dynamic b) { if ((a == null || b == null) && GetDynamic(1) && !(GetDynamic(2) && GetDynamic(3))) { Console.WriteLine("then"); } else { Console.WriteLine("else"); } } private static bool ConstantTarget(dynamic a) { return true.Equals(a); } #if CS110 && NET70 private static nint NewIntPtr(dynamic a) { return new nint(a); } #else private static IntPtr NewIntPtr(dynamic a) { return new IntPtr(a); } #endif private static dynamic GetDynamic(int i) { return null; } private static bool GetBool(int i) { return false; } private static dynamic LogicAnd() { return GetDynamic(1) && GetDynamic(2); } private static dynamic LogicAnd(dynamic a, dynamic b) { return a && b; } private static void LogicAndExtended(int i, dynamic d) { Console.WriteLine(GetDynamic(1) && GetDynamic(2)); Console.WriteLine(GetDynamic(1) && GetBool(2)); Console.WriteLine(GetBool(1) && GetDynamic(2)); Console.WriteLine(i == 1 && d == null); } private static dynamic LogicOr() { return GetDynamic(1) || GetDynamic(2); } private static dynamic LogicOr(dynamic a, dynamic b) { return a || b; } private static void LogicOrExtended(int i, dynamic d) { Console.WriteLine(GetDynamic(1) || GetDynamic(2)); Console.WriteLine(GetDynamic(1) || GetBool(2)); Console.WriteLine(GetBool(1) || GetDynamic(2)); Console.WriteLine(i == 1 || d == null); } private static int ImplicitCast(object o) { return (dynamic)o; } private static int ExplicitCast(object o) { return (int)(dynamic)o; } private static dynamic GetI() { return null; } public I Test() { return GetI(); } public I Test1() { return (I)GetI(); } public I Test2() { return (I)(object)GetI(); } #if CS72 public void RefParams(ref object a, ref dynamic b, ref dynamic c) { } public void RefParams2(in object a, ref dynamic b, out dynamic c) { c = null; } public ref dynamic RefReturn(ref object o) { return ref o; } public ref readonly dynamic RefReadonlyReturn(in object o) { return ref o; } #endif } internal static class Extension { public static dynamic ToDynamic(this int i, dynamic info) { throw null; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/DynamicTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/DynamicTests.cs", "repo_id": "ILSpy", "token_count": 4820 }
213
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public struct Maybe<T> { public T Value; public bool HasValue; } public static class MaybeExtensions { public static Maybe<TResult> Select<T, TResult>(this Maybe<T> a, Func<T, TResult> fn) { return default(Maybe<TResult>); } public static Maybe<T> Where<T>(this Maybe<T> a, Func<T, bool> predicate) { return default(Maybe<T>); } } public class QueryExpressions { public class HbmParam { public string Name { get; set; } public string[] Text { get; set; } } public class Customer { public int CustomerID; public IEnumerable<Order> Orders; public string Name; public string Country; public string City; } public class Order { public int OrderID; public DateTime OrderDate; public Customer Customer; public int CustomerID; public decimal Total; public IEnumerable<OrderDetail> Details; } public class OrderDetail { public decimal UnitPrice; public int Quantity; } public IEnumerable<Customer> customers; public IEnumerable<Order> orders; public object MultipleWhere() { return from c in customers where c.Orders.Count() > 10 where c.Country == "DE" select c; } public object SelectManyFollowedBySelect() { return from c in customers from o in c.Orders select new { c.Name, o.OrderID, o.Total }; } public object SelectManyFollowedByOrderBy() { return from c in customers from o in c.Orders orderby o.Total descending select new { c.Name, o.OrderID, o.Total }; } public object MultipleSelectManyFollowedBySelect() { return from c in customers from o in c.Orders from d in o.Details select new { c.Name, o.OrderID, d.Quantity }; } public object MultipleSelectManyFollowedByLet() { return from c in customers from o in c.Orders from d in o.Details let x = (decimal)d.Quantity * d.UnitPrice select new { c.Name, o.OrderID, x }; } public object FromLetWhereSelect() { return from o in orders let t = o.Details.Sum((OrderDetail d) => d.UnitPrice * (decimal)d.Quantity) where t >= 1000m select new { OrderID = o.OrderID, Total = t }; } public object MultipleLet() { return from a in customers let b = a.Country let c = a.Name select b + c; } public object HibernateApplyGeneratorQuery() { return (from pi in customers.GetType().GetProperties() let pname = pi.Name let pvalue = pi.GetValue(customers, null) select new HbmParam { Name = pname, Text = new string[1] { (pvalue == null) ? "null" : pvalue.ToString() } }).ToArray(); } public object Join() { return from c in customers join o in orders on c.CustomerID equals o.CustomerID select new { c.Name, o.OrderDate, o.Total }; } public object JoinInto() { return from c in customers join o in orders on c.CustomerID equals o.CustomerID into co let n = co.Count() where n >= 10 select new { Name = c.Name, OrderCount = n }; } public object OrderBy() { return from o in orders orderby o.Customer.Name, o.Total descending select o; } public object GroupBy() { return from c in customers group c.Name by c.Country; } public object ExplicitType() { return from Customer c in customers where c.City == "London" select c; } public object QueryContinuation() { return from c in customers group c by c.Country into g select new { Country = g.Key, CustCount = g.Count() }; } public object Issue437(bool[] bools) { return from x in bools where x select (x); } #if CS60 private List<string> Issue2545(List<string> arglist) { return arglist?.OrderByDescending((string f) => f.Length).ThenBy((string f) => f.ToLower()).ToList(); } #endif public static IEnumerable<char> Issue1310a(bool test) { #if ROSLYN && OPT IEnumerable<char> obj = (test ? (from c in Enumerable.Range(0, 255) where char.IsLetter((char)c) select (char)c) : (from c in Enumerable.Range(0, 255) where char.IsDigit((char)c) select (char)c)); return obj.Concat(obj); #else IEnumerable<char> enumerable = (test ? (from c in Enumerable.Range(0, 255) where char.IsLetter((char)c) select (char)c) : (from c in Enumerable.Range(0, 255) where char.IsDigit((char)c) select (char)c)); return enumerable.Concat(enumerable); #endif } public static Maybe<TB> Cast<TA, TB>(Maybe<TA> a) where TB : class { return from m in a let t = m as TB where t != null select t; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/QueryExpressions.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/QueryExpressions.cs", "repo_id": "ILSpy", "token_count": 2416 }
214
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; #if !NET40 && ROSLYN using System.Runtime.CompilerServices; #endif using System.Runtime.InteropServices; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class SizeofTest { private struct StructWithStaticField { public static object StaticObj; #if CS110 && NET70 public nint A; #else public IntPtr A; #endif } private struct UnmanagedStruct { public StructWithStaticField Value; } private struct ManagedStruct { public object Obj; } #if CS73 private unsafe int GenericMethod<T>() where T : unmanaged { return sizeof(T); } #endif private unsafe void Test(out int s1, out int s2, out int s3) { s1 = 0; s2 = 0; s3 = 0; #if CS73 GenericMethod<UnmanagedStruct>(); #endif s1 = sizeof(UnmanagedStruct); #if !NET40 && ROSLYN s2 = Unsafe.SizeOf<UnmanagedStruct>(); s3 = Unsafe.SizeOf<ManagedStruct>(); #endif } } public class UnsafeCode { public struct SimpleStruct { public int X; public double Y; } public struct ResultStruct { public unsafe byte* ptr1; public unsafe byte* ptr2; public unsafe ResultStruct(byte* ptr1, byte* ptr2) { this.ptr1 = ptr1; this.ptr2 = ptr2; } } public struct StructWithFixedSizeMembers { public unsafe fixed int Integers[100]; public int NormalMember; public unsafe fixed double Doubles[200]; [Obsolete("another attribute")] public unsafe fixed byte Old[1]; } private struct Data { public Vector Position; } [StructLayout(LayoutKind.Sequential, Size = 1)] private struct Vector { public override int GetHashCode() { return 0; } } #if CS73 public class CustomPinnable { public ref int GetPinnableReference() { throw new NotImplementedException(); } } #endif public unsafe delegate void UnsafeDelegate(byte* ptr); private UnsafeDelegate unsafeDelegate; private static UnsafeDelegate staticUnsafeDelegate; #if CS60 public unsafe int* NullPointer => null; #else public unsafe int* NullPointer { get { return null; } } #endif unsafe static UnsafeCode() { staticUnsafeDelegate = UnsafeStaticMethod; } public unsafe UnsafeCode() { unsafeDelegate = UnsafeMethod; } public unsafe int SizeOf() { return sizeof(SimpleStruct); } private static void UseBool(bool b) { } private unsafe void UnsafeMethod(byte* ptr) { } private unsafe static void UnsafeStaticMethod(byte* ptr) { } public unsafe void PointerComparison(int* a, double* b) { UseBool(a == b); UseBool(a != b); UseBool(a < b); UseBool(a > b); UseBool(a <= b); UseBool(a >= b); } public unsafe void PointerComparisonWithNull(int* a) { UseBool(a == null); UseBool(a != null); } public unsafe int* PointerCast(long* p) { return (int*)p; } public unsafe long ConvertDoubleToLong(double d) { return *(long*)(&d); } public unsafe double ConvertLongToDouble(long d) { return *(double*)(&d); } public unsafe int ConvertFloatToInt(float d) { return *(int*)(&d); } public unsafe float ConvertIntToFloat(int d) { return *(float*)(&d); } public unsafe int PointerCasts() { int result = 0; *(float*)(&result) = 0.5f; ((byte*)(&result))[3] = 3; return result; } public unsafe void PassRefParameterAsPointer(ref int p) { fixed (int* ptr = &p) { UsePointer(ptr); } } public unsafe void PassPointerAsRefParameter(int* p) { UseReference(ref *p); } public unsafe void PassPointerCastAsRefParameter(uint* p) { UseReference(ref *(int*)p); } public unsafe void AddressInMultiDimensionalArray(double[,] matrix) { fixed (double* d = &matrix[1, 2]) { PointerReferenceExpression(d); PointerReferenceExpression(d); } } public unsafe void FixedStringAccess(string text) { fixed (char* ptr = text) { for (char* ptr2 = ptr; *ptr2 == 'a'; ptr2++) { *ptr2 = 'A'; } } } public unsafe void FixedStringNoPointerUse(string text) { fixed (char* ptr = text) { } } #if !(LEGACY_CSC && OPT) // legacy csc manages to optimize out the pinned variable altogether in this case; // leaving no pinned region we could detect. public unsafe void FixedArrayNoPointerUse(int[] arr) { fixed (int* ptr = arr) { } } #endif public unsafe void PutDoubleIntoLongArray1(long[] array, int index, double val) { fixed (long* ptr = array) { *(double*)(ptr + index) = val; } } public unsafe void PutDoubleIntoLongArray2(long[] array, int index, double val) { fixed (long* ptr = &array[index]) { *(double*)ptr = val; } } public unsafe string PointerReferenceExpression(double* d) { return d->ToString(); } public unsafe string PointerReferenceExpression2(long addr) { return ((int*)addr)->ToString(); } public unsafe int* PointerArithmetic(int* p) { return p + 2; } public unsafe long* PointerArithmetic2(long* p) { return 3 + p; } public unsafe long* PointerArithmetic3(long* p) { return (long*)((byte*)p + 3); } public unsafe long* PointerArithmetic4(void* p) { return (long*)((byte*)p + 3); } public unsafe int PointerArithmetic5(void* p, byte* q, int i) { return q[i] + *(byte*)p; } public unsafe int PointerArithmetic6(SimpleStruct* p, int i) { return p[i].X; } public unsafe int* PointerArithmeticLong1(int* p, long offset) { return p + offset; } public unsafe int* PointerArithmeticLong2(int* p, long offset) { return offset + p; } public unsafe int* PointerArithmeticLong3(int* p, long offset) { return p - offset; } public unsafe SimpleStruct* PointerArithmeticLong1s(SimpleStruct* p, long offset) { return p + offset; } public unsafe SimpleStruct* PointerArithmeticLong2s(SimpleStruct* p, long offset) { return offset + p; } public unsafe SimpleStruct* PointerArithmeticLong3s(SimpleStruct* p, long offset) { return p - offset; } public unsafe int PointerSubtraction(long* p, long* q) { return (int)(p - q); } public unsafe long PointerSubtractionLong(long* p, long* q) { return p - q; } public unsafe int PointerSubtraction2(long* p, short* q) { return (int)((byte*)p - (byte*)q); } public unsafe int PointerSubtraction3(void* p, void* q) { return (int)((byte*)p - (byte*)q); } public unsafe long PointerSubtraction4(sbyte* p, sbyte* q) { return p - q; } public unsafe long PointerSubtraction5(SimpleStruct* p, SimpleStruct* q) { return p - q; } public unsafe long Issue2158a(void* p, void* q) { return (long)p - (long)q; } public unsafe long Issue2158b(sbyte* p, sbyte* q) { return (long)p - (long)q; } public unsafe long Issue2158c(int* p, int* q) { return (long)p - (long)q; } public unsafe long Issue2158d(SimpleStruct* p, SimpleStruct* q) { return (long)p - (long)q; } public unsafe double FixedMemberAccess(StructWithFixedSizeMembers* m, int i) { return (double)m->Integers[i] + m->Doubles[i]; } public unsafe double* FixedMemberBasePointer(StructWithFixedSizeMembers* m) { return m->Doubles; } public unsafe void UseFixedMemberAsPointer(StructWithFixedSizeMembers* m) { UsePointer(m->Integers); } public unsafe void UseFixedMemberAsReference(StructWithFixedSizeMembers* m) { UseReference(ref *m->Integers); UseReference(ref m->Integers[1]); } public unsafe void PinFixedMember(ref StructWithFixedSizeMembers m) { fixed (int* ptr = m.Integers) { UsePointer(ptr); } } private void UseReference(ref int i) { } public unsafe string UsePointer(int* ptr) { return ptr->ToString(); } public unsafe string UsePointer(double* ptr) { return ptr->ToString(); } public unsafe void FixedMultiDimArray(int[,] arr) { fixed (int* ptr = arr) { UsePointer(ptr); } } #if CS73 && !NET40 public unsafe void FixedSpan(Span<int> span) { fixed (int* ptr = span) { UsePointer(ptr); } } #endif #if CS73 public unsafe void FixedCustomReferenceType(CustomPinnable mem) { fixed (int* ptr = mem) { UsePointer(ptr); } } public unsafe void FixedCustomReferenceTypeNoPointerUse(CustomPinnable mem) { fixed (int* ptr = mem) { Console.WriteLine("Hello World!"); } } public unsafe void FixedCustomReferenceTypeExplicitGetPinnableReference(CustomPinnable mem) { fixed (int* ptr = &mem.GetPinnableReference()) { UsePointer(ptr); } } #endif public unsafe string StackAlloc(int count) { char* ptr = stackalloc char[count]; char* ptr2 = stackalloc char[100]; for (int i = 0; i < count; i++) { ptr[i] = (char)i; ptr2[i] = '\0'; } return UsePointer((double*)ptr); } public unsafe string StackAllocStruct(int count) { SimpleStruct* ptr = stackalloc SimpleStruct[checked(count * 2)]; #if !(ROSLYN && OPT) // unused stackalloc gets optimized out by roslyn SimpleStruct* ptr2 = stackalloc SimpleStruct[10]; #endif ptr->X = count; ptr[1].X = ptr->X; for (int i = 2; i < 10; i++) { ptr[i].X = count; } return UsePointer(&ptr->Y); } unsafe ~UnsafeCode() { PassPointerAsRefParameter(NullPointer); } private unsafe void Issue990() { Data data = default(Data); Data* ptr = &data; ConvertIntToFloat(ptr->Position.GetHashCode()); } private unsafe static void Issue1021(ref byte* bytePtr, ref short* shortPtr) { bytePtr += 4; shortPtr += 2; bytePtr -= 4; shortPtr = (short*)((byte*)shortPtr - 3); } private static T Get<T>() { return default(T); } private unsafe static ResultStruct NestedFixedBlocks(byte[] array) { try { fixed (byte* ptr = array) { fixed (byte* ptr2 = Get<byte[]>()) { return new ResultStruct(ptr, ptr2); } } } finally { Console.WriteLine("Finally"); } } private unsafe static object CreateBuffer(int length, byte* ptr) { throw new NotImplementedException(); } private unsafe static object Issue1386(int arraySize, bool createFirstBuffer) { if (createFirstBuffer) { byte[] array = new byte[arraySize]; Console.WriteLine("first fixed"); fixed (byte* ptr = array) { return CreateBuffer(array.Length, ptr); } } byte[] array2 = new byte[arraySize]; Console.WriteLine("second fixed"); fixed (byte* ptr2 = array2) { return CreateBuffer(array2.Length, ptr2); } } private unsafe static void Issue1499(StructWithFixedSizeMembers value, int index) { int num = value.Integers[index]; num.ToString(); } #if CS73 private unsafe static int Issue2287(ref StructWithFixedSizeMembers value) { return value.Integers[0] + value.Integers[1]; } #endif private unsafe static int Issue2305(StructWithFixedSizeMembers value, StringComparison s) { return value.Integers[(int)s]; } #if CS90 private unsafe static void* CastNIntToVoidPtr(nint intptr) { return (void*)intptr; } private unsafe static void* CastNIntToVoidPtr(nuint intptr) { return (void*)intptr; } #endif #if !(CS110 && NET70) private unsafe static void* CastToVoidPtr(IntPtr intptr) { return (void*)intptr; } private unsafe static void* CastToVoidPtr(UIntPtr intptr) { return (void*)intptr; } #endif private unsafe static void* CastToVoidPtr(int* intptr) { return intptr; } public unsafe void ConditionalPointer(bool a, int* ptr) { UsePointer(a ? ptr : null); } public unsafe void UseArrayOfPointers(int*[] arr) { for (int i = 0; i < arr.Length; i++) { arr[i] = null; } } public unsafe void PassNullPointer1() { PointerReferenceExpression(null); } public unsafe void PassNullPointer2() { UseArrayOfPointers(null); } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/UnsafeCode.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/UnsafeCode.cs", "repo_id": "ILSpy", "token_count": 5279 }
215
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [CompilerGenerated] internal sealed class _003CPrivateImplementationDetails_003E { [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 12)] private struct __StaticArrayInitTypeSize_003D12 { } internal static readonly __StaticArrayInitTypeSize_003D12 _4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D/* Not supported: data(01 00 00 00 02 00 00 00 03 00 00 00) */; } namespace ICSharpCode.Decompiler.Tests.TestCases.Ugly { public class NoArrayInitializers { public int[] LiteralArray() { int[] array = new int[3]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); return array; } public int[] VariableArray(int a, int b) { int[] array = new int[2]; array[0] = a; array[1] = b; return array; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoArrayInitializers.Expected.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoArrayInitializers.Expected.cs", "repo_id": "ILSpy", "token_count": 348 }
216
Imports System Module Program Sub SelectOnString() Select Case Environment.CommandLine Case "123" Console.WriteLine("a") Case "444" Console.WriteLine("b") Case "222" Console.WriteLine("c") Case "11" Console.WriteLine("d") Case "dd" Console.WriteLine("e") Case "sss" Console.WriteLine("f") Case "aa" Console.WriteLine("g") Case "" Console.WriteLine("empty") End Select End Sub End Module
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Select.vb/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Select.vb", "repo_id": "ILSpy", "token_count": 195 }
217
// Copyright (c) 2017 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using ICSharpCode.Decompiler.Util; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests.Util { [TestFixture] public class BitSetTests { [Test] public void SetRange() { var bitset = new BitSet(302); bitset.Set(2, 300); Assert.That(!bitset[0]); Assert.That(!bitset[1]); for (int i = 2; i < 300; ++i) { Assert.That(bitset[i]); } Assert.That(!bitset[301]); } [Test] public void ClearRange() { var bitset = new BitSet(300); bitset.Set(0, 300); bitset.Clear(1, 299); Assert.That(bitset[0]); for (int i = 1; i < 299; ++i) { Assert.That(!bitset[i]); } Assert.That(bitset[299]); } [Test] public void AllInRange() { var bitset = new BitSet(300); bitset.Set(1, 299); Assert.That(bitset.All(1, 299)); Assert.That(bitset.All(10, 290)); Assert.That(bitset.All(100, 200)); Assert.That(!bitset.All(0, 200)); Assert.That(!bitset.All(0, 1)); Assert.That(!bitset.All(1, 300)); bitset[200] = false; Assert.That(!bitset.All(1, 299)); } [Test] public void NextBitSet() { var bitset = new BitSet(300); bitset.Set(0); bitset.Set(2); bitset.Set(3); bitset.Set(130); bitset.Set(135); bitset.Set(150); bitset.Set(190); Assert.That(bitset.SetBits(0, 300), Is.EqualTo(new[] { 0, 2, 3, 130, 135, 150, 190 })); Assert.That(bitset.SetBits(1, 5), Is.EqualTo(new[] { 2, 3 })); Assert.That(bitset.SetBits(5, 132), Is.EqualTo(new[] { 130 })); } } }
ILSpy/ICSharpCode.Decompiler.Tests/Util/BitSetTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/Util/BitSetTests.cs", "repo_id": "ILSpy", "token_count": 1037 }
218
// Copyright (c) 2020 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Linq; using ICSharpCode.Decompiler.CSharp.Syntax; namespace ICSharpCode.Decompiler.CSharp.OutputVisitor { /// <summary> /// Used to test for the "F(G&lt;A,B&gt;(7));" grammar ambiguity. /// </summary> class GenericGrammarAmbiguityVisitor : DepthFirstAstVisitor<bool> { /// <summary> /// Resolves ambiguities in the specified syntax tree. /// This method must be called after the InsertParenthesesVisitor, because the ambiguity depends on whether the /// final `>` in the possible-type-argument is followed by an opening parenthesis. /// </summary> public static void ResolveAmbiguities(AstNode rootNode) { foreach (var node in rootNode.Descendants.OfType<BinaryOperatorExpression>()) { if (CausesAmbiguityWithGenerics(node)) { node.ReplaceWith(n => new ParenthesizedExpression(n)); } } } public static bool CausesAmbiguityWithGenerics(BinaryOperatorExpression binaryOperatorExpression) { if (binaryOperatorExpression.Operator != BinaryOperatorType.LessThan) return false; var v = new GenericGrammarAmbiguityVisitor(); v.genericNestingLevel = 1; for (AstNode node = binaryOperatorExpression.Right; node != null; node = node.GetNextNode()) { if (node.AcceptVisitor(v)) return v.ambiguityFound; } return false; } int genericNestingLevel; bool ambiguityFound; protected override bool VisitChildren(AstNode node) { // unhandled node: probably not syntactically valid in a typename // These are preconditions for all recursive Visit() calls. Debug.Assert(genericNestingLevel > 0); Debug.Assert(!ambiguityFound); // The return value merely indicates whether to stop visiting. return true; // stop visiting, no ambiguity found } public override bool VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression) { if (binaryOperatorExpression.Left.AcceptVisitor(this)) return true; Debug.Assert(genericNestingLevel > 0); switch (binaryOperatorExpression.Operator) { case BinaryOperatorType.LessThan: genericNestingLevel += 1; break; case BinaryOperatorType.GreaterThan: genericNestingLevel--; break; case BinaryOperatorType.ShiftRight when genericNestingLevel >= 2: genericNestingLevel -= 2; break; case BinaryOperatorType.UnsignedShiftRight when genericNestingLevel >= 3: genericNestingLevel -= 3; break; default: return true; // stop visiting, no ambiguity found } if (genericNestingLevel == 0) { // Of the all tokens that might follow `>` and trigger the ambiguity to be resolved in favor of generics, // `(` is the only one that might start an expression. ambiguityFound = binaryOperatorExpression.Right is ParenthesizedExpression; return true; // stop visiting } return binaryOperatorExpression.Right.AcceptVisitor(this); } public override bool VisitIdentifierExpression(IdentifierExpression identifierExpression) { // identifier could also be valid in a type argument return false; // keep visiting } public override bool VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression) { return false; // keep visiting } public override bool VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression) { // MRE could also be valid in a type argument return memberReferenceExpression.Target.AcceptVisitor(this); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs", "repo_id": "ILSpy", "token_count": 1471 }
219
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using ICSharpCode.Decompiler.Semantics; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.TypeSystem.Implementation; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.CSharp.Resolver { public enum TypeInferenceAlgorithm { /// <summary> /// C# 4.0 type inference. /// </summary> CSharp4, /// <summary> /// Improved algorithm (not part of any specification) using FindTypeInBounds for fixing. /// </summary> Improved, /// <summary> /// Improved algorithm (not part of any specification) using FindTypeInBounds for fixing; /// uses <see cref="IntersectionType"/> to report all results (in case of ambiguities). /// </summary> ImprovedReturnAllResults } /// <summary> /// Implements C# 4.0 Type Inference (§7.5.2). /// </summary> public sealed class TypeInference { readonly ICompilation compilation; readonly CSharpConversions conversions; TypeInferenceAlgorithm algorithm = TypeInferenceAlgorithm.CSharp4; // determines the maximum generic nesting level; necessary to avoid infinite recursion in 'Improved' mode. const int maxNestingLevel = 5; int nestingLevel; #region Constructor public TypeInference(ICompilation compilation) { if (compilation == null) throw new ArgumentNullException(nameof(compilation)); this.compilation = compilation; this.conversions = CSharpConversions.Get(compilation); } internal TypeInference(ICompilation compilation, CSharpConversions conversions) { Debug.Assert(compilation != null); Debug.Assert(conversions != null); this.compilation = compilation; this.conversions = conversions; } #endregion #region Properties /// <summary> /// Gets/Sets the type inference algorithm used. /// </summary> public TypeInferenceAlgorithm Algorithm { get { return algorithm; } set { algorithm = value; } } TypeInference CreateNestedInstance() { TypeInference c = new TypeInference(compilation, conversions); c.algorithm = algorithm; c.nestingLevel = nestingLevel + 1; return c; } #endregion TP[] typeParameters; IType[] parameterTypes; ResolveResult[] arguments; bool[,] dependencyMatrix; IReadOnlyList<IType> classTypeArguments; #region InferTypeArguments (main function) /// <summary> /// Performs type inference. /// </summary> /// <param name="typeParameters">The method type parameters that should be inferred.</param> /// <param name="arguments">The arguments passed to the method.</param> /// <param name="parameterTypes">The parameter types of the method.</param> /// <param name="success">Out: whether type inference was successful</param> /// <param name="classTypeArguments"> /// Class type arguments. These are substituted for class type parameters in the formal parameter types /// when inferring a method group or lambda. /// </param> /// <returns>The inferred type arguments.</returns> public IType[] InferTypeArguments(IReadOnlyList<ITypeParameter> typeParameters, IReadOnlyList<ResolveResult> arguments, IReadOnlyList<IType> parameterTypes, out bool success, IReadOnlyList<IType> classTypeArguments = null) { if (typeParameters == null) throw new ArgumentNullException(nameof(typeParameters)); if (arguments == null) throw new ArgumentNullException(nameof(arguments)); if (parameterTypes == null) throw new ArgumentNullException(nameof(parameterTypes)); try { this.typeParameters = new TP[typeParameters.Count]; for (int i = 0; i < this.typeParameters.Length; i++) { if (i != typeParameters[i].Index) throw new ArgumentException("Type parameter has wrong index"); if (typeParameters[i].OwnerType != SymbolKind.Method) throw new ArgumentException("Type parameter must be owned by a method"); this.typeParameters[i] = new TP(typeParameters[i]); } this.parameterTypes = new IType[Math.Min(arguments.Count, parameterTypes.Count)]; this.arguments = new ResolveResult[this.parameterTypes.Length]; for (int i = 0; i < this.parameterTypes.Length; i++) { if (arguments[i] == null || parameterTypes[i] == null) throw new ArgumentNullException(); this.arguments[i] = arguments[i]; this.parameterTypes[i] = parameterTypes[i]; } this.classTypeArguments = classTypeArguments; Log.WriteLine("Type Inference"); Log.WriteLine(" Signature: M<" + string.Join<TP>(", ", this.typeParameters) + ">" + "(" + string.Join<IType>(", ", this.parameterTypes) + ")"); Log.WriteCollection(" Arguments: ", arguments); Log.Indent(); PhaseOne(); success = PhaseTwo(); Log.Unindent(); Log.WriteLine(" Type inference finished " + (success ? "successfully" : "with errors") + ": " + "M<" + string.Join(", ", this.typeParameters.Select(tp => tp.FixedTo ?? SpecialType.UnknownType)) + ">"); return this.typeParameters.Select(tp => tp.FixedTo ?? SpecialType.UnknownType).ToArray(); } finally { Reset(); } } void Reset() { // clean up so that memory used by the operation can be garbage collected as soon as possible this.typeParameters = null; this.parameterTypes = null; this.arguments = null; this.dependencyMatrix = null; this.classTypeArguments = null; } /// <summary> /// Infers type arguments for the <paramref name="typeParameters"/> occurring in the <paramref name="targetType"/> /// so that the resulting type (after substition) satisfies the given bounds. /// </summary> public IType[] InferTypeArgumentsFromBounds(IReadOnlyList<ITypeParameter> typeParameters, IType targetType, IEnumerable<IType> lowerBounds, IEnumerable<IType> upperBounds, out bool success) { if (typeParameters == null) throw new ArgumentNullException(nameof(typeParameters)); if (targetType == null) throw new ArgumentNullException(nameof(targetType)); if (lowerBounds == null) throw new ArgumentNullException(nameof(lowerBounds)); if (upperBounds == null) throw new ArgumentNullException(nameof(upperBounds)); this.typeParameters = new TP[typeParameters.Count]; for (int i = 0; i < this.typeParameters.Length; i++) { if (i != typeParameters[i].Index) throw new ArgumentException("Type parameter has wrong index"); this.typeParameters[i] = new TP(typeParameters[i]); } foreach (IType b in lowerBounds) { MakeLowerBoundInference(b, targetType); } foreach (IType b in upperBounds) { MakeUpperBoundInference(b, targetType); } IType[] result = new IType[this.typeParameters.Length]; success = true; for (int i = 0; i < result.Length; i++) { success &= Fix(this.typeParameters[i]); result[i] = this.typeParameters[i].FixedTo ?? SpecialType.UnknownType; } Reset(); return result; } #endregion sealed class TP { public readonly HashSet<IType> LowerBounds = new HashSet<IType>(); public readonly HashSet<IType> UpperBounds = new HashSet<IType>(); public IType ExactBound; public bool MultipleDifferentExactBounds; public readonly ITypeParameter TypeParameter; public IType FixedTo; public bool IsFixed { get { return FixedTo != null; } } public bool HasBounds { get { return LowerBounds.Count > 0 || UpperBounds.Count > 0 || ExactBound != null; } } public TP(ITypeParameter typeParameter) { if (typeParameter == null) throw new ArgumentNullException(nameof(typeParameter)); this.TypeParameter = typeParameter; } public void AddExactBound(IType type) { // Exact bounds need to stored separately, not just as Lower+Upper bounds, // due to TypeInferenceTests.GenericArgumentImplicitlyConvertibleToAndFromAnotherTypeList (see #281) if (ExactBound == null) ExactBound = type; else if (!ExactBound.Equals(type)) MultipleDifferentExactBounds = true; } public override string ToString() { return TypeParameter.Name; } } sealed class OccursInVisitor : TypeVisitor { readonly TP[] tp; public readonly bool[] Occurs; public OccursInVisitor(TypeInference typeInference) { this.tp = typeInference.typeParameters; this.Occurs = new bool[tp.Length]; } public override IType VisitTypeParameter(ITypeParameter type) { int index = type.Index; if (index < tp.Length && tp[index].TypeParameter == type) Occurs[index] = true; return base.VisitTypeParameter(type); } } #region Inference Phases void PhaseOne() { // C# 4.0 spec: §7.5.2.1 The first phase Log.WriteLine("Phase One"); for (int i = 0; i < arguments.Length; i++) { ResolveResult Ei = arguments[i]; IType Ti = parameterTypes[i]; LambdaResolveResult lrr = Ei as LambdaResolveResult; if (lrr != null) { MakeExplicitParameterTypeInference(lrr, Ti); } if (lrr != null || Ei is MethodGroupResolveResult) { // this is not in the spec??? if (OutputTypeContainsUnfixed(Ei, Ti) && !InputTypesContainsUnfixed(Ei, Ti)) { MakeOutputTypeInference(Ei, Ti); } } if (IsValidType(Ei.Type)) { if (Ti is ByReferenceType) { MakeExactInference(Ei.Type, Ti); } else { MakeLowerBoundInference(Ei.Type, Ti); } } } } static bool IsValidType(IType type) { return type.Kind != TypeKind.Unknown && type.Kind != TypeKind.Null && type.Kind != TypeKind.None; } bool PhaseTwo() { // C# 4.0 spec: §7.5.2.2 The second phase Log.WriteLine("Phase Two"); // All unfixed type variables Xi which do not depend on any Xj are fixed. List<TP> typeParametersToFix = new List<TP>(); foreach (TP Xi in typeParameters) { if (Xi.IsFixed == false) { if (!typeParameters.Any((TP Xj) => !Xj.IsFixed && DependsOn(Xi, Xj))) { typeParametersToFix.Add(Xi); } } } // If no such type variables exist, all unfixed type variables Xi are fixed for which all of the following hold: if (typeParametersToFix.Count == 0) { Log.WriteLine("Type parameters cannot be fixed due to dependency cycles"); Log.WriteLine("Trying to break the cycle by fixing any TPs that have non-empty bounds..."); foreach (TP Xi in typeParameters) { // Xi has a non­empty set of bounds if (!Xi.IsFixed && Xi.HasBounds) { // There is at least one type variable Xj that depends on Xi if (typeParameters.Any((TP Xj) => DependsOn(Xj, Xi))) { typeParametersToFix.Add(Xi); } } } } // now fix 'em bool errorDuringFix = false; foreach (TP tp in typeParametersToFix) { if (!Fix(tp)) errorDuringFix = true; } if (errorDuringFix) return false; bool unfixedTypeVariablesExist = typeParameters.Any((TP X) => X.IsFixed == false); if (typeParametersToFix.Count == 0 && unfixedTypeVariablesExist) { // If no such type variables exist and there are still unfixed type variables, type inference fails. Log.WriteLine("Type inference fails: there are still unfixed TPs remaining"); return false; } else if (!unfixedTypeVariablesExist) { // Otherwise, if no further unfixed type variables exist, type inference succeeds. return true; } else { // Otherwise, for all arguments ei with corresponding parameter type Ti for (int i = 0; i < arguments.Length; i++) { ResolveResult Ei = arguments[i]; IType Ti = parameterTypes[i]; // where the output types (§7.4.2.4) contain unfixed type variables Xj // but the input types (§7.4.2.3) do not if (OutputTypeContainsUnfixed(Ei, Ti) && !InputTypesContainsUnfixed(Ei, Ti)) { // an output type inference (§7.4.2.6) is made for ei with type Ti. Log.WriteLine("MakeOutputTypeInference for argument #" + i); MakeOutputTypeInference(Ei, Ti); } } // Then the second phase is repeated. return PhaseTwo(); } } #endregion #region Input Types / Output Types (§7.5.2.3 + §7.5.2.4) IType[] InputTypes(ResolveResult e, IType t) { // C# 4.0 spec: §7.5.2.3 Input types LambdaResolveResult lrr = e as LambdaResolveResult; if (lrr != null && lrr.IsImplicitlyTyped || e is MethodGroupResolveResult) { IMethod m = GetDelegateOrExpressionTreeSignature(t); if (m != null) { IType[] inputTypes = new IType[m.Parameters.Count]; for (int i = 0; i < inputTypes.Length; i++) { inputTypes[i] = m.Parameters[i].Type; } return inputTypes; } } return Empty<IType>.Array; } IType[] OutputTypes(ResolveResult e, IType t) { // C# 4.0 spec: §7.5.2.4 Output types LambdaResolveResult lrr = e as LambdaResolveResult; if (lrr != null || e is MethodGroupResolveResult) { IMethod m = GetDelegateOrExpressionTreeSignature(t); if (m != null) { return new[] { m.ReturnType }; } } return Empty<IType>.Array; } static IMethod GetDelegateOrExpressionTreeSignature(IType t) { if (t.TypeParameterCount == 1 && t.Name == "Expression" && t.Namespace == "System.Linq.Expressions") { t = t.TypeArguments[0]; } return t.GetDelegateInvokeMethod(); } bool InputTypesContainsUnfixed(ResolveResult argument, IType parameterType) { return AnyTypeContainsUnfixedParameter(InputTypes(argument, parameterType)); } bool OutputTypeContainsUnfixed(ResolveResult argument, IType parameterType) { return AnyTypeContainsUnfixedParameter(OutputTypes(argument, parameterType)); } bool AnyTypeContainsUnfixedParameter(IEnumerable<IType> types) { OccursInVisitor o = new OccursInVisitor(this); foreach (var type in types) { type.AcceptVisitor(o); } for (int i = 0; i < typeParameters.Length; i++) { if (!typeParameters[i].IsFixed && o.Occurs[i]) return true; } return false; } #endregion #region DependsOn (§7.5.2.5) // C# 4.0 spec: §7.5.2.5 Dependance void CalculateDependencyMatrix() { int n = typeParameters.Length; dependencyMatrix = new bool[n, n]; for (int k = 0; k < arguments.Length; k++) { OccursInVisitor input = new OccursInVisitor(this); OccursInVisitor output = new OccursInVisitor(this); foreach (var type in InputTypes(arguments[k], parameterTypes[k])) { type.AcceptVisitor(input); } foreach (var type in OutputTypes(arguments[k], parameterTypes[k])) { type.AcceptVisitor(output); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dependencyMatrix[i, j] |= input.Occurs[j] && output.Occurs[i]; } } } // calculate transitive closure using Warshall's algorithm: for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dependencyMatrix[i, j]) { for (int k = 0; k < n; k++) { if (dependencyMatrix[j, k]) dependencyMatrix[i, k] = true; } } } } } bool DependsOn(TP x, TP y) { if (dependencyMatrix == null) CalculateDependencyMatrix(); // x depends on y return dependencyMatrix[x.TypeParameter.Index, y.TypeParameter.Index]; } #endregion #region MakeOutputTypeInference (§7.5.2.6) void MakeOutputTypeInference(ResolveResult e, IType t) { Log.WriteLine(" MakeOutputTypeInference from " + e + " to " + t); // If E is an anonymous function with inferred return type U (§7.5.2.12) and T is a delegate type or expression // tree type with return type Tb, then a lower-bound inference (§7.5.2.9) is made from U to Tb. LambdaResolveResult lrr = e as LambdaResolveResult; if (lrr != null) { IMethod m = GetDelegateOrExpressionTreeSignature(t); if (m != null) { IType inferredReturnType; if (lrr.IsImplicitlyTyped) { if (m.Parameters.Count != lrr.Parameters.Count) return; // cannot infer due to mismatched parameter lists TypeParameterSubstitution substitution = GetSubstitutionForFixedTPs(); IType[] inferredParameterTypes = new IType[m.Parameters.Count]; for (int i = 0; i < inferredParameterTypes.Length; i++) { IType parameterType = m.Parameters[i].Type; inferredParameterTypes[i] = parameterType.AcceptVisitor(substitution); } inferredReturnType = lrr.GetInferredReturnType(inferredParameterTypes); } else { inferredReturnType = lrr.GetInferredReturnType(null); } MakeLowerBoundInference(inferredReturnType, m.ReturnType); return; } } // Otherwise, if E is a method group and T is a delegate type or expression tree type // with parameter types T1…Tk and return type Tb, and overload resolution // of E with the types T1…Tk yields a single method with return type U, then a lower­-bound // inference is made from U to Tb. MethodGroupResolveResult mgrr = e as MethodGroupResolveResult; if (mgrr != null) { IMethod m = GetDelegateOrExpressionTreeSignature(t); if (m != null) { ResolveResult[] args = new ResolveResult[m.Parameters.Count]; TypeParameterSubstitution substitution = GetSubstitutionForFixedTPs(); for (int i = 0; i < args.Length; i++) { IParameter param = m.Parameters[i]; IType parameterType = param.Type.AcceptVisitor(substitution); if ((param.ReferenceKind != ReferenceKind.None) && parameterType.Kind == TypeKind.ByReference) { parameterType = ((ByReferenceType)parameterType).ElementType; args[i] = new ByReferenceResolveResult(parameterType, param.ReferenceKind); } else { args[i] = new ResolveResult(parameterType); } } var or = mgrr.PerformOverloadResolution( compilation, args, allowExpandingParams: false, allowOptionalParameters: false, allowImplicitIn: false ); if (or.FoundApplicableCandidate && or.BestCandidateAmbiguousWith == null) { IType returnType = or.GetBestCandidateWithSubstitutedTypeArguments().ReturnType; MakeLowerBoundInference(returnType, m.ReturnType); } } return; } // Otherwise, if E is an expression with type U, then a lower-bound inference is made from U to T. if (IsValidType(e.Type)) { MakeLowerBoundInference(e.Type, t); } } TypeParameterSubstitution GetSubstitutionForFixedTPs() { IType[] fixedTypes = new IType[typeParameters.Length]; for (int i = 0; i < fixedTypes.Length; i++) { fixedTypes[i] = typeParameters[i].FixedTo ?? SpecialType.UnknownType; } return new TypeParameterSubstitution(classTypeArguments, fixedTypes); } #endregion #region MakeExplicitParameterTypeInference (§7.5.2.7) void MakeExplicitParameterTypeInference(LambdaResolveResult e, IType t) { // C# 4.0 spec: §7.5.2.7 Explicit parameter type inferences if (e.IsImplicitlyTyped || !e.HasParameterList) return; Log.WriteLine(" MakeExplicitParameterTypeInference from " + e + " to " + t); IMethod m = GetDelegateOrExpressionTreeSignature(t); if (m == null) return; for (int i = 0; i < e.Parameters.Count && i < m.Parameters.Count; i++) { MakeExactInference(e.Parameters[i].Type, m.Parameters[i].Type); } } #endregion #region MakeExactInference (§7.5.2.8) /// <summary> /// Make exact inference from U to V. /// C# 4.0 spec: §7.5.2.8 Exact inferences /// </summary> void MakeExactInference(IType U, IType V) { Log.WriteLine("MakeExactInference from " + U + " to " + V); if (U.Nullability == V.Nullability) { U = U.WithoutNullability(); V = V.WithoutNullability(); } // If V is one of the unfixed Xi then U is added to the set of bounds for Xi. TP tp = GetTPForType(V); if (tp != null && tp.IsFixed == false) { Log.WriteLine(" Add exact bound '" + U + "' to " + tp); tp.AddExactBound(U); return; } // Handle by reference types: ByReferenceType brU = U as ByReferenceType; ByReferenceType brV = V as ByReferenceType; if (brU != null && brV != null) { MakeExactInference(brU.ElementType, brV.ElementType); return; } // Handle array types: ArrayType arrU = U as ArrayType; ArrayType arrV = V as ArrayType; if (arrU != null && arrV != null && arrU.Dimensions == arrV.Dimensions) { MakeExactInference(arrU.ElementType, arrV.ElementType); return; } // Handle parameterized type: ParameterizedType pU = U.TupleUnderlyingTypeOrSelf() as ParameterizedType; ParameterizedType pV = V.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (pU != null && pV != null && object.Equals(pU.GenericType, pV.GenericType) && pU.TypeParameterCount == pV.TypeParameterCount) { Log.Indent(); for (int i = 0; i < pU.TypeParameterCount; i++) { MakeExactInference(pU.GetTypeArgument(i), pV.GetTypeArgument(i)); } Log.Unindent(); return; } // Handle pointer types: if (U is PointerType ptrU && V is PointerType ptrV) { MakeExactInference(ptrU.ElementType, ptrV.ElementType); return; } if (U is FunctionPointerType fnPtrU && V is FunctionPointerType fnPtrV) { MakeExactInference(fnPtrU.ReturnType, fnPtrV.ReturnType); foreach (var (ptU, ptV) in fnPtrU.ParameterTypes.Zip(fnPtrV.ParameterTypes)) { MakeExactInference(ptU, ptV); } return; } } TP GetTPForType(IType v) { if (v is NullabilityAnnotatedTypeParameter natp) { v = natp.OriginalTypeParameter; } if (v is ITypeParameter p) { int index = p.Index; if (index < typeParameters.Length && typeParameters[index].TypeParameter == p) return typeParameters[index]; } return null; } #endregion #region MakeLowerBoundInference (§7.5.2.9) /// <summary> /// Make lower bound inference from U to V. /// C# 4.0 spec: §7.5.2.9 Lower-bound inferences /// </summary> void MakeLowerBoundInference(IType U, IType V) { Log.WriteLine(" MakeLowerBoundInference from " + U + " to " + V); if (U.Nullability == V.Nullability) { U = U.WithoutNullability(); V = V.WithoutNullability(); } // If V is one of the unfixed Xi then U is added to the set of bounds for Xi. TP tp = GetTPForType(V); if (tp != null && tp.IsFixed == false) { Log.WriteLine(" Add lower bound '" + U + "' to " + tp); tp.LowerBounds.Add(U); return; } // Handle nullable covariance: if (NullableType.IsNullable(U) && NullableType.IsNullable(V)) { MakeLowerBoundInference(NullableType.GetUnderlyingType(U), NullableType.GetUnderlyingType(V)); return; } // Handle by reference types: ByReferenceType brU = U as ByReferenceType; ByReferenceType brV = V as ByReferenceType; if (brU != null && brV != null) { MakeExactInference(brU.ElementType, brV.ElementType); return; } // Handle array types: ArrayType arrU = U as ArrayType; ArrayType arrV = V as ArrayType; ParameterizedType pV = V.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (arrU != null && arrV != null && arrU.Dimensions == arrV.Dimensions) { MakeLowerBoundInference(arrU.ElementType, arrV.ElementType); return; } else if (arrU != null && IsGenericInterfaceImplementedByArray(pV) && arrU.Dimensions == 1) { MakeLowerBoundInference(arrU.ElementType, pV.GetTypeArgument(0)); return; } // Handle parameterized types: if (pV != null) { ParameterizedType uniqueBaseType = null; foreach (IType baseU in U.GetAllBaseTypes()) { ParameterizedType pU = baseU.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (pU != null && object.Equals(pU.GenericType, pV.GenericType) && pU.TypeParameterCount == pV.TypeParameterCount) { if (uniqueBaseType == null) uniqueBaseType = pU; else return; // cannot make an inference because it's not unique } } Log.Indent(); if (uniqueBaseType != null) { for (int i = 0; i < uniqueBaseType.TypeParameterCount; i++) { IType Ui = uniqueBaseType.GetTypeArgument(i); IType Vi = pV.GetTypeArgument(i); if (Ui.IsReferenceType == true) { // look for variance ITypeParameter Xi = pV.TypeParameters[i]; switch (Xi.Variance) { case VarianceModifier.Covariant: MakeLowerBoundInference(Ui, Vi); break; case VarianceModifier.Contravariant: MakeUpperBoundInference(Ui, Vi); break; default: // invariant MakeExactInference(Ui, Vi); break; } } else { // not known to be a reference type MakeExactInference(Ui, Vi); } } } Log.Unindent(); return; } // Handle pointer types: if (U is PointerType ptrU && V is PointerType ptrV) { MakeExactInference(ptrU.ElementType, ptrV.ElementType); return; } if (U is FunctionPointerType fnPtrU && V is FunctionPointerType fnPtrV) { MakeLowerBoundInference(fnPtrU.ReturnType, fnPtrV.ReturnType); foreach (var (ptU, ptV) in fnPtrU.ParameterTypes.Zip(fnPtrV.ParameterTypes)) { MakeUpperBoundInference(ptU, ptV); } return; } } static bool IsGenericInterfaceImplementedByArray(ParameterizedType rt) { if (rt == null || rt.TypeParameterCount != 1) return false; switch (rt.GetDefinition()?.KnownTypeCode) { case KnownTypeCode.IEnumerableOfT: case KnownTypeCode.ICollectionOfT: case KnownTypeCode.IListOfT: case KnownTypeCode.IReadOnlyCollectionOfT: case KnownTypeCode.IReadOnlyListOfT: return true; default: return false; } } #endregion #region MakeUpperBoundInference (§7.5.2.10) /// <summary> /// Make upper bound inference from U to V. /// C# 4.0 spec: §7.5.2.10 Upper-bound inferences /// </summary> void MakeUpperBoundInference(IType U, IType V) { Log.WriteLine(" MakeUpperBoundInference from " + U + " to " + V); if (U.Nullability == V.Nullability) { U = U.WithoutNullability(); V = V.WithoutNullability(); } // If V is one of the unfixed Xi then U is added to the set of bounds for Xi. TP tp = GetTPForType(V); if (tp != null && tp.IsFixed == false) { Log.WriteLine(" Add upper bound '" + U + "' to " + tp); tp.UpperBounds.Add(U); return; } // Handle array types: ArrayType arrU = U as ArrayType; ArrayType arrV = V as ArrayType; ParameterizedType pU = U.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (arrV != null && arrU != null && arrU.Dimensions == arrV.Dimensions) { MakeUpperBoundInference(arrU.ElementType, arrV.ElementType); return; } else if (arrV != null && IsGenericInterfaceImplementedByArray(pU) && arrV.Dimensions == 1) { MakeUpperBoundInference(pU.GetTypeArgument(0), arrV.ElementType); return; } // Handle parameterized types: if (pU != null) { ParameterizedType uniqueBaseType = null; foreach (IType baseV in V.GetAllBaseTypes()) { ParameterizedType pV = baseV.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (pV != null && object.Equals(pU.GenericType, pV.GenericType) && pU.TypeParameterCount == pV.TypeParameterCount) { if (uniqueBaseType == null) uniqueBaseType = pV; else return; // cannot make an inference because it's not unique } } Log.Indent(); if (uniqueBaseType != null) { for (int i = 0; i < uniqueBaseType.TypeParameterCount; i++) { IType Ui = pU.GetTypeArgument(i); IType Vi = uniqueBaseType.GetTypeArgument(i); if (Ui.IsReferenceType == true) { // look for variance ITypeParameter Xi = pU.TypeParameters[i]; switch (Xi.Variance) { case VarianceModifier.Covariant: MakeUpperBoundInference(Ui, Vi); break; case VarianceModifier.Contravariant: MakeLowerBoundInference(Ui, Vi); break; default: // invariant MakeExactInference(Ui, Vi); break; } } else { // not known to be a reference type MakeExactInference(Ui, Vi); } } } Log.Unindent(); return; } // Handle pointer types: if (U is PointerType ptrU && V is PointerType ptrV) { MakeExactInference(ptrU.ElementType, ptrV.ElementType); return; } if (U is FunctionPointerType fnPtrU && V is FunctionPointerType fnPtrV) { MakeUpperBoundInference(fnPtrU.ReturnType, fnPtrV.ReturnType); foreach (var (ptU, ptV) in fnPtrU.ParameterTypes.Zip(fnPtrV.ParameterTypes)) { MakeLowerBoundInference(ptU, ptV); } return; } } #endregion #region Fixing (§7.5.2.11) bool Fix(TP tp) { Log.WriteLine(" Trying to fix " + tp); Debug.Assert(!tp.IsFixed); if (tp.ExactBound != null) { // the exact bound will always be the result tp.FixedTo = tp.ExactBound; // check validity if (tp.MultipleDifferentExactBounds) return false; return tp.LowerBounds.All(b => conversions.ImplicitConversion(b, tp.FixedTo).IsValid) && tp.UpperBounds.All(b => conversions.ImplicitConversion(tp.FixedTo, b).IsValid); } Log.Indent(); var types = CreateNestedInstance().FindTypesInBounds(tp.LowerBounds.ToArray(), tp.UpperBounds.ToArray()); Log.Unindent(); if (algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults) { tp.FixedTo = IntersectionType.Create(types); Log.WriteLine(" T was fixed " + (types.Count >= 1 ? "successfully" : "(with errors)") + " to " + tp.FixedTo); return types.Count >= 1; } else { tp.FixedTo = GetFirstTypePreferNonInterfaces(types); Log.WriteLine(" T was fixed " + (types.Count == 1 ? "successfully" : "(with errors)") + " to " + tp.FixedTo); return types.Count == 1; } } #endregion #region Finding the best common type of a set of expresssions /// <summary> /// Gets the best common type (C# 4.0 spec: §7.5.2.14) of a set of expressions. /// </summary> public IType GetBestCommonType(IList<ResolveResult> expressions, out bool success) { if (expressions == null) throw new ArgumentNullException(nameof(expressions)); if (expressions.Count == 1) { success = IsValidType(expressions[0].Type); return expressions[0].Type; } Log.WriteCollection("GetBestCommonType() for ", expressions); try { ITypeParameter tp = DummyTypeParameter.GetMethodTypeParameter(0); this.typeParameters = new TP[1] { new TP(tp) }; foreach (ResolveResult r in expressions) { MakeOutputTypeInference(r, tp); } success = Fix(typeParameters[0]); return typeParameters[0].FixedTo ?? SpecialType.UnknownType; } finally { Reset(); } } #endregion #region FindTypeInBounds /// <summary> /// Finds a type that satisfies the given lower and upper bounds. /// </summary> public IType FindTypeInBounds(IReadOnlyList<IType> lowerBounds, IReadOnlyList<IType> upperBounds) { if (lowerBounds == null) throw new ArgumentNullException(nameof(lowerBounds)); if (upperBounds == null) throw new ArgumentNullException(nameof(upperBounds)); var result = FindTypesInBounds(lowerBounds, upperBounds); if (algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults) { return IntersectionType.Create(result); } else { // return any of the candidates (prefer non-interfaces) return GetFirstTypePreferNonInterfaces(result); } } static IType GetFirstTypePreferNonInterfaces(IReadOnlyList<IType> result) { return result.FirstOrDefault(c => c.Kind != TypeKind.Interface) ?? result.FirstOrDefault() ?? SpecialType.UnknownType; } IReadOnlyList<IType> FindTypesInBounds(IReadOnlyList<IType> lowerBounds, IReadOnlyList<IType> upperBounds) { // If there's only a single type; return that single type. // If both inputs are empty, return the empty list. if (lowerBounds.Count == 0 && upperBounds.Count <= 1) return upperBounds; if (upperBounds.Count == 0 && lowerBounds.Count <= 1) return lowerBounds; if (nestingLevel > maxNestingLevel) return EmptyList<IType>.Instance; // Finds a type X so that "LB <: X <: UB" Log.WriteCollection("FindTypesInBound, LowerBounds=", lowerBounds); Log.WriteCollection("FindTypesInBound, UpperBounds=", upperBounds); // First try the Fixing algorithm from the C# spec (§7.5.2.11) List<IType> candidateTypes = lowerBounds.Union(upperBounds) .Where(c => lowerBounds.All(b => conversions.ImplicitConversion(b, c).IsValid)) .Where(c => upperBounds.All(b => conversions.ImplicitConversion(c, b).IsValid)) .ToList(); // evaluate the query only once Log.WriteCollection("FindTypesInBound, Candidates=", candidateTypes); // According to the C# specification, we need to pick the most specific // of the candidate types. (the type which has conversions to all others) // However, csc actually seems to choose the least specific. candidateTypes = candidateTypes.Where( c => candidateTypes.All(o => conversions.ImplicitConversion(o, c).IsValid) ).ToList(); // If the specified algorithm produces a single candidate, we return // that candidate. // We also return the whole candidate list if we're not using the improved // algorithm. if (candidateTypes.Count == 1 || !(algorithm == TypeInferenceAlgorithm.Improved || algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults)) { return candidateTypes; } candidateTypes.Clear(); // Now try the improved algorithm Log.Indent(); List<ITypeDefinition> candidateTypeDefinitions; if (lowerBounds.Count > 0) { // Find candidates by using the lower bounds: var hashSet = new HashSet<ITypeDefinition>(lowerBounds[0].GetAllBaseTypeDefinitions()); for (int i = 1; i < lowerBounds.Count; i++) { hashSet.IntersectWith(lowerBounds[i].GetAllBaseTypeDefinitions()); } candidateTypeDefinitions = hashSet.ToList(); } else { // Find candidates by looking at all classes in the project: candidateTypeDefinitions = compilation.GetAllTypeDefinitions().ToList(); } // Now filter out candidates that violate the upper bounds: foreach (IType ub in upperBounds) { ITypeDefinition ubDef = ub.GetDefinition(); if (ubDef != null) { candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef)); } } foreach (ITypeDefinition candidateDef in candidateTypeDefinitions) { // determine the type parameters for the candidate: IType candidate; if (candidateDef.TypeParameterCount == 0) { candidate = candidateDef; } else { Log.WriteLine("Inferring arguments for candidate type definition: " + candidateDef); bool success; IType[] result = InferTypeArgumentsFromBounds( candidateDef.TypeParameters, new ParameterizedType(candidateDef, candidateDef.TypeParameters), lowerBounds, upperBounds, out success); if (success) { candidate = new ParameterizedType(candidateDef, result); } else { Log.WriteLine("Inference failed; ignoring candidate"); continue; } } Log.WriteLine("Candidate type: " + candidate); if (upperBounds.Count == 0) { // if there were only lower bounds, we aim for the most specific candidate: // if this candidate isn't made redundant by an existing, more specific candidate: if (!candidateTypes.Any(c => c.GetDefinition().IsDerivedFrom(candidateDef))) { // remove all existing candidates made redundant by this candidate: candidateTypes.RemoveAll(c => candidateDef.IsDerivedFrom(c.GetDefinition())); // add new candidate candidateTypes.Add(candidate); } } else { // if there were upper bounds, we aim for the least specific candidate: // if this candidate isn't made redundant by an existing, less specific candidate: if (!candidateTypes.Any(c => candidateDef.IsDerivedFrom(c.GetDefinition()))) { // remove all existing candidates made redundant by this candidate: candidateTypes.RemoveAll(c => c.GetDefinition().IsDerivedFrom(candidateDef)); // add new candidate candidateTypes.Add(candidate); } } } Log.Unindent(); return candidateTypes; } #endregion } }
ILSpy/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs", "repo_id": "ILSpy", "token_count": 15136 }
220
// // AssignmentExpression.cs // // Author: // Mike Krüger <mkrueger@novell.com> // // Copyright (c) 2009 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq.Expressions; namespace ICSharpCode.Decompiler.CSharp.Syntax { /// <summary> /// Left Operator= Right /// </summary> public class AssignmentExpression : Expression { // reuse roles from BinaryOperatorExpression public readonly static Role<Expression> LeftRole = BinaryOperatorExpression.LeftRole; public readonly static Role<Expression> RightRole = BinaryOperatorExpression.RightRole; public readonly static TokenRole AssignRole = new TokenRole("="); public readonly static TokenRole AddRole = new TokenRole("+="); public readonly static TokenRole SubtractRole = new TokenRole("-="); public readonly static TokenRole MultiplyRole = new TokenRole("*="); public readonly static TokenRole DivideRole = new TokenRole("/="); public readonly static TokenRole ModulusRole = new TokenRole("%="); public readonly static TokenRole ShiftLeftRole = new TokenRole("<<="); public readonly static TokenRole ShiftRightRole = new TokenRole(">>="); public readonly static TokenRole UnsignedShiftRightRole = new TokenRole(">>>="); public readonly static TokenRole BitwiseAndRole = new TokenRole("&="); public readonly static TokenRole BitwiseOrRole = new TokenRole("|="); public readonly static TokenRole ExclusiveOrRole = new TokenRole("^="); public AssignmentExpression() { } public AssignmentExpression(Expression left, Expression right) { this.Left = left; this.Right = right; } public AssignmentExpression(Expression left, AssignmentOperatorType op, Expression right) { this.Left = left; this.Operator = op; this.Right = right; } public AssignmentOperatorType Operator { get; set; } public Expression Left { get { return GetChildByRole(LeftRole); } set { SetChildByRole(LeftRole, value); } } public CSharpTokenNode OperatorToken { get { return GetChildByRole(GetOperatorRole(Operator)); } } public Expression Right { get { return GetChildByRole(RightRole); } set { SetChildByRole(RightRole, value); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitAssignmentExpression(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitAssignmentExpression(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitAssignmentExpression(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { AssignmentExpression o = other as AssignmentExpression; return o != null && (this.Operator == AssignmentOperatorType.Any || this.Operator == o.Operator) && this.Left.DoMatch(o.Left, match) && this.Right.DoMatch(o.Right, match); } public static TokenRole GetOperatorRole(AssignmentOperatorType op) { switch (op) { case AssignmentOperatorType.Assign: return AssignRole; case AssignmentOperatorType.Add: return AddRole; case AssignmentOperatorType.Subtract: return SubtractRole; case AssignmentOperatorType.Multiply: return MultiplyRole; case AssignmentOperatorType.Divide: return DivideRole; case AssignmentOperatorType.Modulus: return ModulusRole; case AssignmentOperatorType.ShiftLeft: return ShiftLeftRole; case AssignmentOperatorType.ShiftRight: return ShiftRightRole; case AssignmentOperatorType.UnsignedShiftRight: return UnsignedShiftRightRole; case AssignmentOperatorType.BitwiseAnd: return BitwiseAndRole; case AssignmentOperatorType.BitwiseOr: return BitwiseOrRole; case AssignmentOperatorType.ExclusiveOr: return ExclusiveOrRole; default: throw new NotSupportedException("Invalid value for AssignmentOperatorType"); } } /// <summary> /// Gets the binary operator for the specified compound assignment operator. /// Returns null if 'op' is not a compound assignment. /// </summary> public static BinaryOperatorType? GetCorrespondingBinaryOperator(AssignmentOperatorType op) { switch (op) { case AssignmentOperatorType.Assign: return null; case AssignmentOperatorType.Add: return BinaryOperatorType.Add; case AssignmentOperatorType.Subtract: return BinaryOperatorType.Subtract; case AssignmentOperatorType.Multiply: return BinaryOperatorType.Multiply; case AssignmentOperatorType.Divide: return BinaryOperatorType.Divide; case AssignmentOperatorType.Modulus: return BinaryOperatorType.Modulus; case AssignmentOperatorType.ShiftLeft: return BinaryOperatorType.ShiftLeft; case AssignmentOperatorType.ShiftRight: return BinaryOperatorType.ShiftRight; case AssignmentOperatorType.UnsignedShiftRight: return BinaryOperatorType.UnsignedShiftRight; case AssignmentOperatorType.BitwiseAnd: return BinaryOperatorType.BitwiseAnd; case AssignmentOperatorType.BitwiseOr: return BinaryOperatorType.BitwiseOr; case AssignmentOperatorType.ExclusiveOr: return BinaryOperatorType.ExclusiveOr; default: throw new NotSupportedException("Invalid value for AssignmentOperatorType"); } } public static ExpressionType GetLinqNodeType(AssignmentOperatorType op, bool checkForOverflow) { switch (op) { case AssignmentOperatorType.Assign: return ExpressionType.Assign; case AssignmentOperatorType.Add: return checkForOverflow ? ExpressionType.AddAssignChecked : ExpressionType.AddAssign; case AssignmentOperatorType.Subtract: return checkForOverflow ? ExpressionType.SubtractAssignChecked : ExpressionType.SubtractAssign; case AssignmentOperatorType.Multiply: return checkForOverflow ? ExpressionType.MultiplyAssignChecked : ExpressionType.MultiplyAssign; case AssignmentOperatorType.Divide: return ExpressionType.DivideAssign; case AssignmentOperatorType.Modulus: return ExpressionType.ModuloAssign; case AssignmentOperatorType.ShiftLeft: return ExpressionType.LeftShiftAssign; case AssignmentOperatorType.ShiftRight: return ExpressionType.RightShiftAssign; case AssignmentOperatorType.UnsignedShiftRight: return ExpressionType.Extension; case AssignmentOperatorType.BitwiseAnd: return ExpressionType.AndAssign; case AssignmentOperatorType.BitwiseOr: return ExpressionType.OrAssign; case AssignmentOperatorType.ExclusiveOr: return ExpressionType.ExclusiveOrAssign; default: throw new NotSupportedException("Invalid value for AssignmentOperatorType"); } } public static AssignmentOperatorType? GetAssignmentOperatorTypeFromExpressionType(ExpressionType expressionType) { switch (expressionType) { case ExpressionType.AddAssign: case ExpressionType.AddAssignChecked: return AssignmentOperatorType.Add; case ExpressionType.AndAssign: return AssignmentOperatorType.BitwiseAnd; case ExpressionType.DivideAssign: return AssignmentOperatorType.Divide; case ExpressionType.ExclusiveOrAssign: return AssignmentOperatorType.ExclusiveOr; case ExpressionType.LeftShiftAssign: return AssignmentOperatorType.ShiftLeft; case ExpressionType.ModuloAssign: return AssignmentOperatorType.Modulus; case ExpressionType.MultiplyAssign: case ExpressionType.MultiplyAssignChecked: return AssignmentOperatorType.Multiply; case ExpressionType.OrAssign: return AssignmentOperatorType.BitwiseOr; case ExpressionType.RightShiftAssign: return AssignmentOperatorType.ShiftRight; case ExpressionType.SubtractAssign: case ExpressionType.SubtractAssignChecked: return AssignmentOperatorType.Subtract; default: return null; } } } public enum AssignmentOperatorType { /// <summary>left = right</summary> Assign, /// <summary>left += right</summary> Add, /// <summary>left -= right</summary> Subtract, /// <summary>left *= right</summary> Multiply, /// <summary>left /= right</summary> Divide, /// <summary>left %= right</summary> Modulus, /// <summary>left &lt;&lt;= right</summary> ShiftLeft, /// <summary>left >>= right</summary> ShiftRight, /// <summary>left >>>= right</summary> UnsignedShiftRight, /// <summary>left &amp;= right</summary> BitwiseAnd, /// <summary>left |= right</summary> BitwiseOr, /// <summary>left ^= right</summary> ExclusiveOr, /// <summary>Any operator (for pattern matching)</summary> Any } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs", "repo_id": "ILSpy", "token_count": 3272 }
221
// // LambdaExpression.cs // // Author: // Mike Krüger <mkrueger@novell.com> // // Copyright (c) 2010 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace ICSharpCode.Decompiler.CSharp.Syntax { /// <summary> /// [async] Parameters => Body /// </summary> public class LambdaExpression : Expression { public static readonly Role<AttributeSection> AttributeRole = new Role<AttributeSection>("Attribute", null); public readonly static TokenRole AsyncModifierRole = new TokenRole("async"); public static readonly Role<AstNode> BodyRole = new Role<AstNode>("Body", AstNode.Null); bool isAsync; public AstNodeCollection<AttributeSection> Attributes { get { return base.GetChildrenByRole(AttributeRole); } } public bool IsAsync { get { return isAsync; } set { ThrowIfFrozen(); isAsync = value; } } public CSharpTokenNode LParToken { get { return GetChildByRole(Roles.LPar); } } public AstNodeCollection<ParameterDeclaration> Parameters { get { return GetChildrenByRole(Roles.Parameter); } } public CSharpTokenNode RParToken { get { return GetChildByRole(Roles.RPar); } } public CSharpTokenNode ArrowToken { get { return GetChildByRole(Roles.Arrow); } } public AstNode Body { get { return GetChildByRole(BodyRole); } set { SetChildByRole(BodyRole, value); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitLambdaExpression(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitLambdaExpression(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitLambdaExpression(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { LambdaExpression o = other as LambdaExpression; return o != null && this.IsAsync == o.IsAsync && this.Parameters.DoMatch(o.Parameters, match) && this.Body.DoMatch(o.Body, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs", "repo_id": "ILSpy", "token_count": 980 }
222
// Copyright (c) 2017 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. namespace ICSharpCode.Decompiler.CSharp.Syntax { /// <summary> /// throw Expression /// </summary> public class ThrowExpression : Expression { public static readonly TokenRole ThrowKeywordRole = ThrowStatement.ThrowKeywordRole; public CSharpTokenNode ThrowToken { get { return GetChildByRole(ThrowKeywordRole); } } public Expression Expression { get { return GetChildByRole(Roles.Expression); } set { SetChildByRole(Roles.Expression, value); } } public ThrowExpression() { } public ThrowExpression(Expression expression) { AddChild(expression, Roles.Expression); } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitThrowExpression(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitThrowExpression(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitThrowExpression(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { ThrowExpression o = other as ThrowExpression; return o != null && this.Expression.DoMatch(o.Expression, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs", "repo_id": "ILSpy", "token_count": 695 }
223
// // PreProcessorDirective.cs // // Author: // Mike Krüger <mkrueger@xamarin.com> // // Copyright (c) 2011 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Linq; namespace ICSharpCode.Decompiler.CSharp.Syntax { public enum PreProcessorDirectiveType : byte { Invalid = 0, Region = 1, Endregion = 2, If = 3, Endif = 4, Elif = 5, Else = 6, Define = 7, Undef = 8, Error = 9, Warning = 10, Pragma = 11, Line = 12 } public class LinePreprocessorDirective : PreProcessorDirective { public int LineNumber { get; set; } public string FileName { get; set; } public LinePreprocessorDirective(TextLocation startLocation, TextLocation endLocation) : base(PreProcessorDirectiveType.Line, startLocation, endLocation) { } public LinePreprocessorDirective(string argument = null) : base(PreProcessorDirectiveType.Line, argument) { } } public class PragmaWarningPreprocessorDirective : PreProcessorDirective { public static readonly Role<PrimitiveExpression> WarningRole = new Role<PrimitiveExpression>("Warning", null); public static readonly TokenRole PragmaKeywordRole = new TokenRole("#pragma"); public static readonly TokenRole WarningKeywordRole = new TokenRole("warning"); public static readonly TokenRole DisableKeywordRole = new TokenRole("disable"); public static readonly TokenRole RestoreKeywordRole = new TokenRole("restore"); public bool Disable { get { return !DisableToken.IsNull; } } public CSharpTokenNode PragmaToken { get { return GetChildByRole(PragmaKeywordRole); } } public CSharpTokenNode WarningToken { get { return GetChildByRole(WarningKeywordRole); } } public CSharpTokenNode DisableToken { get { return GetChildByRole(DisableKeywordRole); } } public CSharpTokenNode RestoreToken { get { return GetChildByRole(RestoreKeywordRole); } } public AstNodeCollection<PrimitiveExpression> Warnings { get { return GetChildrenByRole(WarningRole); } } public override TextLocation EndLocation { get { var child = LastChild; if (child == null) return base.EndLocation; return child.EndLocation; } } public PragmaWarningPreprocessorDirective(TextLocation startLocation, TextLocation endLocation) : base(PreProcessorDirectiveType.Pragma, startLocation, endLocation) { } public PragmaWarningPreprocessorDirective(string argument = null) : base(PreProcessorDirectiveType.Pragma, argument) { } public bool IsDefined(int pragmaWarning) { return Warnings.Select(w => (int)w.Value).Any(n => n == pragmaWarning); } } public class PreProcessorDirective : AstNode { public override NodeType NodeType { get { return NodeType.Whitespace; } } public PreProcessorDirectiveType Type { get; set; } public string Argument { get; set; } /// <summary> /// For an '#if' directive, specifies whether the condition evaluated to true. /// </summary> public bool Take { get; set; } TextLocation startLocation; public override TextLocation StartLocation { get { return startLocation; } } TextLocation endLocation; public override TextLocation EndLocation { get { return endLocation; } } public PreProcessorDirective(PreProcessorDirectiveType type, TextLocation startLocation, TextLocation endLocation) { this.Type = type; this.startLocation = startLocation; this.endLocation = endLocation; } public PreProcessorDirective(PreProcessorDirectiveType type, string argument = null) { this.Type = type; this.Argument = argument; } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitPreProcessorDirective(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitPreProcessorDirective(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitPreProcessorDirective(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { PreProcessorDirective o = other as PreProcessorDirective; return o != null && Type == o.Type && MatchString(Argument, o.Argument); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs", "repo_id": "ILSpy", "token_count": 1776 }
224
// // UncheckedStatement.cs // // Author: // Mike Krüger <mkrueger@novell.com> // // Copyright (c) 2009 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace ICSharpCode.Decompiler.CSharp.Syntax { /// <summary> /// unchecked BodyBlock /// </summary> public class UncheckedStatement : Statement { public static readonly TokenRole UncheckedKeywordRole = new TokenRole("unchecked"); public CSharpTokenNode UncheckedToken { get { return GetChildByRole(UncheckedKeywordRole); } } public BlockStatement Body { get { return GetChildByRole(Roles.Body); } set { SetChildByRole(Roles.Body, value); } } public UncheckedStatement() { } public UncheckedStatement(BlockStatement body) { AddChild(body, Roles.Body); } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitUncheckedStatement(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitUncheckedStatement(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitUncheckedStatement(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { UncheckedStatement o = other as UncheckedStatement; return o != null && this.Body.DoMatch(o.Body, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs", "repo_id": "ILSpy", "token_count": 754 }
225
// // EnumMemberDeclaration.cs // // Author: // Mike Krüger <mkrueger@novell.com> // // Copyright (c) 2010 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.CSharp.Syntax { public class EnumMemberDeclaration : EntityDeclaration { public static readonly Role<Expression> InitializerRole = new Role<Expression>("Initializer", Expression.Null); public override SymbolKind SymbolKind { get { return SymbolKind.Field; } } public CSharpTokenNode AssignToken { get { return GetChildByRole(Roles.Assign); } } public Expression Initializer { get { return GetChildByRole(InitializerRole); } set { SetChildByRole(InitializerRole, value); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitEnumMemberDeclaration(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitEnumMemberDeclaration(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitEnumMemberDeclaration(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { EnumMemberDeclaration o = other as EnumMemberDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && MatchString(this.Name, o.Name) && this.Initializer.DoMatch(o.Initializer, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs", "repo_id": "ILSpy", "token_count": 779 }
226
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.CSharp.Transforms { /// <summary> /// Base class for AST visitors that need the current type/method context info. /// </summary> public abstract class ContextTrackingVisitor<TResult> : DepthFirstAstVisitor<TResult> { protected ITypeDefinition currentTypeDefinition; protected IMethod currentMethod; protected void Initialize(TransformContext context) { currentTypeDefinition = context.CurrentTypeDefinition; currentMethod = context.CurrentMember as IMethod; } protected void Uninitialize() { currentTypeDefinition = null; currentMethod = null; } public override TResult VisitTypeDeclaration(TypeDeclaration typeDeclaration) { ITypeDefinition oldType = currentTypeDefinition; try { currentTypeDefinition = typeDeclaration.GetSymbol() as ITypeDefinition; return base.VisitTypeDeclaration(typeDeclaration); } finally { currentTypeDefinition = oldType; } } public override TResult VisitMethodDeclaration(MethodDeclaration methodDeclaration) { var oldMethod = currentMethod; try { currentMethod = methodDeclaration.GetSymbol() as IMethod; return base.VisitMethodDeclaration(methodDeclaration); } finally { currentMethod = oldMethod; } } public override TResult VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration) { var oldMethod = currentMethod; try { currentMethod = constructorDeclaration.GetSymbol() as IMethod; return base.VisitConstructorDeclaration(constructorDeclaration); } finally { currentMethod = oldMethod; } } public override TResult VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration) { var oldMethod = currentMethod; try { currentMethod = destructorDeclaration.GetSymbol() as IMethod; return base.VisitDestructorDeclaration(destructorDeclaration); } finally { currentMethod = oldMethod; } } public override TResult VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration) { var oldMethod = currentMethod; try { currentMethod = operatorDeclaration.GetSymbol() as IMethod; return base.VisitOperatorDeclaration(operatorDeclaration); } finally { currentMethod = oldMethod; } } public override TResult VisitAccessor(Accessor accessor) { var oldMethod = currentMethod; try { currentMethod = accessor.GetSymbol() as IMethod; return base.VisitAccessor(accessor); } finally { currentMethod = oldMethod; } } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/ContextTrackingVisitor.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/ContextTrackingVisitor.cs", "repo_id": "ILSpy", "token_count": 1241 }
227
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.Reflection; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching; using ICSharpCode.Decompiler.Semantics; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.CSharp.Transforms { /// <summary> /// Replaces method calls with the appropriate operator expressions. /// </summary> public class ReplaceMethodCallsWithOperators : DepthFirstAstVisitor, IAstTransform { static readonly MemberReferenceExpression typeHandleOnTypeOfPattern = new MemberReferenceExpression { Target = new Choice { new TypeOfExpression(new AnyNode()), new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.RefType, Arguments = { new AnyNode() } } }, MemberName = "TypeHandle" }; TransformContext context; public override void VisitInvocationExpression(InvocationExpression invocationExpression) { base.VisitInvocationExpression(invocationExpression); ProcessInvocationExpression(invocationExpression); } void ProcessInvocationExpression(InvocationExpression invocationExpression) { var method = invocationExpression.GetSymbol() as IMethod; if (method == null) return; var arguments = invocationExpression.Arguments.ToArray(); // Reduce "String.Concat(a, b)" to "a + b" if (IsStringConcat(method) && context.Settings.StringConcat && CheckArgumentsForStringConcat(arguments)) { bool isInExpressionTree = invocationExpression.Ancestors.OfType<LambdaExpression>().Any( lambda => lambda.Annotation<IL.ILFunction>()?.Kind == IL.ILFunctionKind.ExpressionTree); Expression arg0 = arguments[0].Detach(); Expression arg1 = arguments[1].Detach(); if (!isInExpressionTree) { arg1 = RemoveRedundantToStringInConcat(arg1, method, isLastArgument: arguments.Length == 2).Detach(); if (arg1.GetResolveResult().Type.IsKnownType(KnownTypeCode.String)) { arg0 = RemoveRedundantToStringInConcat(arg0, method, isLastArgument: false).Detach(); } } var expr = new BinaryOperatorExpression(arg0, BinaryOperatorType.Add, arg1); for (int i = 2; i < arguments.Length; i++) { var arg = arguments[i].Detach(); if (!isInExpressionTree) { arg = RemoveRedundantToStringInConcat(arg, method, isLastArgument: i == arguments.Length - 1).Detach(); } expr = new BinaryOperatorExpression(expr, BinaryOperatorType.Add, arg); } expr.CopyAnnotationsFrom(invocationExpression); invocationExpression.ReplaceWith(expr); return; } switch (method.FullName) { case "System.Type.GetTypeFromHandle": if (arguments.Length == 1) { if (typeHandleOnTypeOfPattern.IsMatch(arguments[0])) { Expression target = ((MemberReferenceExpression)arguments[0]).Target; target.CopyInstructionsFrom(invocationExpression); invocationExpression.ReplaceWith(target); return; } } break; /* case "System.Reflection.FieldInfo.GetFieldFromHandle": // TODO : This is dead code because LdTokenAnnotation is not added anywhere: if (arguments.Length == 1) { MemberReferenceExpression mre = arguments[0] as MemberReferenceExpression; if (mre != null && mre.MemberName == "FieldHandle" && mre.Target.Annotation<LdTokenAnnotation>() != null) { invocationExpression.ReplaceWith(mre.Target); return; } } else if (arguments.Length == 2) { MemberReferenceExpression mre1 = arguments[0] as MemberReferenceExpression; MemberReferenceExpression mre2 = arguments[1] as MemberReferenceExpression; if (mre1 != null && mre1.MemberName == "FieldHandle" && mre1.Target.Annotation<LdTokenAnnotation>() != null) { if (mre2 != null && mre2.MemberName == "TypeHandle" && mre2.Target is TypeOfExpression) { Expression oldArg = ((InvocationExpression)mre1.Target).Arguments.Single(); FieldReference field = oldArg.Annotation<FieldReference>(); if (field != null) { AstType declaringType = ((TypeOfExpression)mre2.Target).Type.Detach(); oldArg.ReplaceWith(new MemberReferenceExpression(new TypeReferenceExpression(declaringType), field.Name).CopyAnnotationsFrom(oldArg)); invocationExpression.ReplaceWith(mre1.Target); return; } } } } break; */ case "System.Activator.CreateInstance": if (arguments.Length == 0 && method.TypeArguments.Count == 1 && IsInstantiableTypeParameter(method.TypeArguments[0])) { invocationExpression.ReplaceWith(new ObjectCreateExpression(context.TypeSystemAstBuilder.ConvertType(method.TypeArguments.First()))); } break; case "System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray": if (arguments.Length == 2 && context.Settings.Ranges) { var slicing = new IndexerExpression(arguments[0].Detach(), arguments[1].Detach()); slicing.CopyAnnotationsFrom(invocationExpression); invocationExpression.ReplaceWith(slicing); } break; } bool isChecked; BinaryOperatorType? bop = GetBinaryOperatorTypeFromMetadataName(method.Name, out isChecked, context.Settings); if (bop != null && arguments.Length == 2) { invocationExpression.Arguments.Clear(); // detach arguments from invocationExpression if (isChecked) { invocationExpression.AddAnnotation(AddCheckedBlocks.CheckedAnnotation); } else if (HasCheckedEquivalent(method)) { invocationExpression.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation); } invocationExpression.ReplaceWith( new BinaryOperatorExpression( arguments[0].UnwrapInDirectionExpression(), bop.Value, arguments[1].UnwrapInDirectionExpression() ).CopyAnnotationsFrom(invocationExpression) ); return; } UnaryOperatorType? uop = GetUnaryOperatorTypeFromMetadataName(method.Name, out isChecked, context.Settings); if (uop != null && arguments.Length == 1) { if (isChecked) { invocationExpression.AddAnnotation(AddCheckedBlocks.CheckedAnnotation); } else if (HasCheckedEquivalent(method)) { invocationExpression.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation); } if (uop == UnaryOperatorType.Increment || uop == UnaryOperatorType.Decrement) { // `op_Increment(a)` is not equivalent to `++a`, // because it doesn't assign the incremented value to a. if (method.DeclaringType.IsKnownType(KnownTypeCode.Decimal)) { // Legacy csc optimizes "d + 1m" to "op_Increment(d)", // so reverse that optimization here: invocationExpression.ReplaceWith( new BinaryOperatorExpression( arguments[0].UnwrapInDirectionExpression().Detach(), (uop == UnaryOperatorType.Increment ? BinaryOperatorType.Add : BinaryOperatorType.Subtract), new PrimitiveExpression(1m) ).CopyAnnotationsFrom(invocationExpression) ); } } else { arguments[0].Remove(); // detach argument invocationExpression.ReplaceWith( new UnaryOperatorExpression(uop.Value, arguments[0].UnwrapInDirectionExpression()).CopyAnnotationsFrom(invocationExpression) ); } return; } if (method.Name is "op_Explicit" or "op_CheckedExplicit" && arguments.Length == 1) { arguments[0].Remove(); // detach argument if (method.Name == "op_CheckedExplicit") { invocationExpression.AddAnnotation(AddCheckedBlocks.CheckedAnnotation); } else if (HasCheckedEquivalent(method)) { invocationExpression.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation); } invocationExpression.ReplaceWith( new CastExpression(context.TypeSystemAstBuilder.ConvertType(method.ReturnType), arguments[0].UnwrapInDirectionExpression()) .CopyAnnotationsFrom(invocationExpression) ); return; } if (method.Name == "op_True" && arguments.Length == 1 && invocationExpression.Role == Roles.Condition) { invocationExpression.ReplaceWith(arguments[0].UnwrapInDirectionExpression()); return; } return; } internal static bool HasCheckedEquivalent(IMethod method) { string name = method.Name; if (name.StartsWith("op_", StringComparison.Ordinal)) name = "op_Checked" + name.Substring(3); return method.DeclaringType.GetMethods(m => m.IsOperator && m.Name == name).Any(); } bool IsInstantiableTypeParameter(IType type) { return type is ITypeParameter tp && tp.HasDefaultConstructorConstraint; } bool CheckArgumentsForStringConcat(Expression[] arguments) { if (arguments.Length < 2) return false; if (arguments.Any(arg => arg is NamedArgumentExpression)) return false; // The evaluation order when the object.ToString() calls happen is a mess: // The C# spec says the evaluation for order for each individual string + should be: // * evaluate left argument // * evaluate right argument // * call ToString() on object argument // What actually happens pre-VS2019.3: // * evaluate all arguments in chain of + operators from left to right // * call ToString() on all object arguments from left to right // What happens in VS2019.3: // * for each argument in chain of + operators fom left to right: // * evaluate argument // * call ToString() on object argument // See https://github.com/dotnet/roslyn/issues/38641 for details. // To ensure the decompiled code's behavior matches the original IL behavior, // no matter which compiler is used to recompile it, we require that all // implicit ToString() calls except for the last are free of side effects. foreach (var arg in arguments.SkipLast(1)) { if (!ToStringIsKnownEffectFree(arg.GetResolveResult().Type)) { return false; } } foreach (var arg in arguments) { if (arg.GetResolveResult() is InvocationResolveResult rr && IsStringConcat(rr.Member)) { // Roslyn + mcs also flatten nested string.Concat() invocations within a operator+ use, // which causes it to use the incorrect evaluation order despite the code using an // explicit string.Concat() call. // This problem is avoided if the outer call remains string.Concat() as well. return false; } } // One of the first two arguments must be string, otherwise the + operator // won't resolve to a string concatenation. return arguments[0].GetResolveResult().Type.IsKnownType(KnownTypeCode.String) || arguments[1].GetResolveResult().Type.IsKnownType(KnownTypeCode.String); } private bool IsStringConcat(IParameterizedMember member) { return member is IMethod method && method.Name == "Concat" && method.DeclaringType.IsKnownType(KnownTypeCode.String); } static readonly Pattern ToStringCallPattern = new Choice { // target.ToString() new InvocationExpression(new MemberReferenceExpression(new AnyNode("target"), "ToString")).WithName("call"), // target?.ToString() new UnaryOperatorExpression( UnaryOperatorType.NullConditionalRewrap, new InvocationExpression( new MemberReferenceExpression( new UnaryOperatorExpression(UnaryOperatorType.NullConditional, new AnyNode("target")), "ToString") ).WithName("call") ).WithName("nullConditional") }; internal static Expression RemoveRedundantToStringInConcat(Expression expr, IMethod concatMethod, bool isLastArgument) { var m = ToStringCallPattern.Match(expr); if (!m.Success) return expr; if (!concatMethod.Parameters.All(IsStringParameter)) { // If we're using a string.Concat() overload involving object parameters, // string.Concat() itself already calls ToString() so the C# compiler shouldn't // generate additional ToString() calls in this case. return expr; } var toStringMethod = m.Get<Expression>("call").Single().GetSymbol() as IMethod; var target = m.Get<Expression>("target").Single(); var type = target.GetResolveResult().Type; if (!(isLastArgument || ToStringIsKnownEffectFree(type))) { // ToString() order of evaluation matters, see CheckArgumentsForStringConcat(). return expr; } if (type.IsReferenceType != false && !m.Has("nullConditional")) { // ToString() might throw NullReferenceException, but the builtin operator+ doesn't. return expr; } if (!ToStringIsKnownEffectFree(type) && toStringMethod != null && IL.Transforms.ILInlining.MethodRequiresCopyForReadonlyLValue(toStringMethod)) { // ToString() on a struct may mutate the struct. // For operator+ the C# compiler creates a temporary copy before implicitly calling ToString(), // whereas an explicit ToString() call would mutate the original lvalue. // So we can't remove the compiler-generated ToString() call in cases where this might make a difference. return expr; } // All checks succeeded, we can eliminate the ToString() call. // The C# compiler will generate an equivalent call if the code is recompiled. return target; bool IsStringParameter(IParameter p) { IType ty = p.Type; if (p.IsParams && ty.Kind == TypeKind.Array) ty = ((ArrayType)ty).ElementType; return ty.IsKnownType(KnownTypeCode.String); } } static bool ToStringIsKnownEffectFree(IType type) { type = NullableType.GetUnderlyingType(type); switch (type.GetDefinition()?.KnownTypeCode) { case KnownTypeCode.Boolean: case KnownTypeCode.Char: case KnownTypeCode.SByte: case KnownTypeCode.Byte: case KnownTypeCode.Int16: case KnownTypeCode.UInt16: case KnownTypeCode.Int32: case KnownTypeCode.UInt32: case KnownTypeCode.Int64: case KnownTypeCode.UInt64: case KnownTypeCode.Single: case KnownTypeCode.Double: case KnownTypeCode.Decimal: case KnownTypeCode.IntPtr: case KnownTypeCode.UIntPtr: case KnownTypeCode.String: return true; default: return false; } } static BinaryOperatorType? GetBinaryOperatorTypeFromMetadataName(string name, out bool isChecked, DecompilerSettings settings) { isChecked = false; switch (name) { case "op_Addition": return BinaryOperatorType.Add; case "op_Subtraction": return BinaryOperatorType.Subtract; case "op_Multiply": return BinaryOperatorType.Multiply; case "op_Division": return BinaryOperatorType.Divide; case "op_CheckedAddition" when settings.CheckedOperators: isChecked = true; return BinaryOperatorType.Add; case "op_CheckedSubtraction" when settings.CheckedOperators: isChecked = true; return BinaryOperatorType.Subtract; case "op_CheckedMultiply" when settings.CheckedOperators: isChecked = true; return BinaryOperatorType.Multiply; case "op_CheckedDivision" when settings.CheckedOperators: isChecked = true; return BinaryOperatorType.Divide; case "op_Modulus": return BinaryOperatorType.Modulus; case "op_BitwiseAnd": return BinaryOperatorType.BitwiseAnd; case "op_BitwiseOr": return BinaryOperatorType.BitwiseOr; case "op_ExclusiveOr": return BinaryOperatorType.ExclusiveOr; case "op_LeftShift": return BinaryOperatorType.ShiftLeft; case "op_RightShift": return BinaryOperatorType.ShiftRight; case "op_UnsignedRightShift" when settings.UnsignedRightShift: return BinaryOperatorType.UnsignedShiftRight; case "op_Equality": return BinaryOperatorType.Equality; case "op_Inequality": return BinaryOperatorType.InEquality; case "op_LessThan": return BinaryOperatorType.LessThan; case "op_LessThanOrEqual": return BinaryOperatorType.LessThanOrEqual; case "op_GreaterThan": return BinaryOperatorType.GreaterThan; case "op_GreaterThanOrEqual": return BinaryOperatorType.GreaterThanOrEqual; default: return null; } } static UnaryOperatorType? GetUnaryOperatorTypeFromMetadataName(string name, out bool isChecked, DecompilerSettings settings) { isChecked = false; switch (name) { case "op_LogicalNot": return UnaryOperatorType.Not; case "op_OnesComplement": return UnaryOperatorType.BitNot; case "op_UnaryNegation": return UnaryOperatorType.Minus; case "op_CheckedUnaryNegation" when settings.CheckedOperators: isChecked = true; return UnaryOperatorType.Minus; case "op_UnaryPlus": return UnaryOperatorType.Plus; case "op_Increment": return UnaryOperatorType.Increment; case "op_Decrement": return UnaryOperatorType.Decrement; case "op_CheckedIncrement" when settings.CheckedOperators: isChecked = true; return UnaryOperatorType.Increment; case "op_CheckedDecrement" when settings.CheckedOperators: isChecked = true; return UnaryOperatorType.Decrement; default: return null; } } static readonly Expression getMethodOrConstructorFromHandlePattern = new CastExpression(new Choice { new TypePattern(typeof(MethodInfo)), new TypePattern(typeof(ConstructorInfo)) }, new InvocationExpression(new MemberReferenceExpression(new TypeReferenceExpression(new TypePattern(typeof(MethodBase)).ToType()), "GetMethodFromHandle"), new NamedNode("ldtokenNode", new MemberReferenceExpression(new LdTokenPattern("method").ToExpression(), "MethodHandle")), new OptionalNode(new MemberReferenceExpression(new TypeOfExpression(new AnyNode("declaringType")), "TypeHandle")) )); public override void VisitCastExpression(CastExpression castExpression) { base.VisitCastExpression(castExpression); // Handle methodof Match m = getMethodOrConstructorFromHandlePattern.Match(castExpression); if (m.Success) { IMethod method = m.Get<AstNode>("method").Single().GetSymbol() as IMethod; if (m.Has("declaringType") && method != null) { Expression newNode = new MemberReferenceExpression(new TypeReferenceExpression(m.Get<AstType>("declaringType").Single().Detach()), method.Name); newNode = new InvocationExpression(newNode, method.Parameters.Select(p => new TypeReferenceExpression(context.TypeSystemAstBuilder.ConvertType(p.Type)))); m.Get<AstNode>("method").Single().ReplaceWith(newNode); } castExpression.ReplaceWith(m.Get<AstNode>("ldtokenNode").Single().CopyAnnotationsFrom(castExpression)); } } void IAstTransform.Run(AstNode rootNode, TransformContext context) { try { this.context = context; rootNode.AcceptVisitor(this); } finally { this.context = null; } } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs", "repo_id": "ILSpy", "token_count": 7266 }
228
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using ICSharpCode.Decompiler.DebugInfo; using ICSharpCode.Decompiler.IL; using ICSharpCode.Decompiler.Metadata; namespace ICSharpCode.Decompiler.Disassembler { /// <summary> /// Disassembles type and member definitions. /// </summary> public sealed class ReflectionDisassembler { readonly ITextOutput output; CancellationToken cancellationToken; bool isInType; // whether we are currently disassembling a whole type (-> defaultCollapsed for foldings) MethodBodyDisassembler methodBodyDisassembler; public bool DetectControlStructure { get => methodBodyDisassembler.DetectControlStructure; set => methodBodyDisassembler.DetectControlStructure = value; } public bool ShowSequencePoints { get => methodBodyDisassembler.ShowSequencePoints; set => methodBodyDisassembler.ShowSequencePoints = value; } public bool ShowMetadataTokens { get => methodBodyDisassembler.ShowMetadataTokens; set => methodBodyDisassembler.ShowMetadataTokens = value; } public bool ShowMetadataTokensInBase10 { get => methodBodyDisassembler.ShowMetadataTokensInBase10; set => methodBodyDisassembler.ShowMetadataTokensInBase10 = value; } public bool ShowRawRVAOffsetAndBytes { get => methodBodyDisassembler.ShowRawRVAOffsetAndBytes; set => methodBodyDisassembler.ShowRawRVAOffsetAndBytes = value; } public IDebugInfoProvider DebugInfo { get => methodBodyDisassembler.DebugInfo; set => methodBodyDisassembler.DebugInfo = value; } public bool ExpandMemberDefinitions { get; set; } public IAssemblyResolver AssemblyResolver { get; set; } public IEntityProcessor EntityProcessor { get; set; } public ReflectionDisassembler(ITextOutput output, CancellationToken cancellationToken) : this(output, new MethodBodyDisassembler(output, cancellationToken), cancellationToken) { } public ReflectionDisassembler(ITextOutput output, MethodBodyDisassembler methodBodyDisassembler, CancellationToken cancellationToken) { if (output == null) throw new ArgumentNullException(nameof(output)); this.output = output; this.cancellationToken = cancellationToken; this.methodBodyDisassembler = methodBodyDisassembler; } #region Disassemble Method EnumNameCollection<MethodAttributes> methodAttributeFlags = new EnumNameCollection<MethodAttributes>() { { MethodAttributes.Final, "final" }, { MethodAttributes.HideBySig, "hidebysig" }, { MethodAttributes.SpecialName, "specialname" }, { MethodAttributes.PinvokeImpl, null }, // handled separately { MethodAttributes.UnmanagedExport, "export" }, { MethodAttributes.RTSpecialName, "rtspecialname" }, { MethodAttributes.RequireSecObject, "reqsecobj" }, { MethodAttributes.NewSlot, "newslot" }, { MethodAttributes.CheckAccessOnOverride, "strict" }, { MethodAttributes.Abstract, "abstract" }, { MethodAttributes.Virtual, "virtual" }, { MethodAttributes.Static, "static" }, { MethodAttributes.HasSecurity, null }, // ?? also invisible in ILDasm }; EnumNameCollection<MethodAttributes> methodVisibility = new EnumNameCollection<MethodAttributes>() { { MethodAttributes.Private, "private" }, { MethodAttributes.FamANDAssem, "famandassem" }, { MethodAttributes.Assembly, "assembly" }, { MethodAttributes.Family, "family" }, { MethodAttributes.FamORAssem, "famorassem" }, { MethodAttributes.Public, "public" }, }; EnumNameCollection<SignatureCallingConvention> callingConvention = new EnumNameCollection<SignatureCallingConvention>() { { SignatureCallingConvention.CDecl, "unmanaged cdecl" }, { SignatureCallingConvention.StdCall, "unmanaged stdcall" }, { SignatureCallingConvention.ThisCall, "unmanaged thiscall" }, { SignatureCallingConvention.FastCall, "unmanaged fastcall" }, { SignatureCallingConvention.VarArgs, "vararg" }, { SignatureCallingConvention.Default, null }, }; EnumNameCollection<MethodImplAttributes> methodCodeType = new EnumNameCollection<MethodImplAttributes>() { { MethodImplAttributes.IL, "cil" }, { MethodImplAttributes.Native, "native" }, { MethodImplAttributes.OPTIL, "optil" }, { MethodImplAttributes.Runtime, "runtime" }, }; EnumNameCollection<MethodImplAttributes> methodImpl = new EnumNameCollection<MethodImplAttributes>() { { MethodImplAttributes.Synchronized, "synchronized" }, { MethodImplAttributes.NoInlining, "noinlining" }, { MethodImplAttributes.NoOptimization, "nooptimization" }, { MethodImplAttributes.PreserveSig, "preservesig" }, { MethodImplAttributes.InternalCall, "internalcall" }, { MethodImplAttributes.ForwardRef, "forwardref" }, { MethodImplAttributes.AggressiveInlining, "aggressiveinlining" }, }; public void DisassembleMethod(PEFile module, MethodDefinitionHandle handle) { var genericContext = new MetadataGenericContext(handle, module); // write method header output.WriteReference(module, handle, ".method", isDefinition: true); output.Write(" "); DisassembleMethodHeaderInternal(module, handle, genericContext); DisassembleMethodBlock(module, handle, genericContext); } public void DisassembleMethodHeader(PEFile module, MethodDefinitionHandle handle) { var genericContext = new MetadataGenericContext(handle, module); // write method header output.WriteReference(module, handle, ".method", isDefinition: true); output.Write(" "); DisassembleMethodHeaderInternal(module, handle, genericContext); } void DisassembleMethodHeaderInternal(PEFile module, MethodDefinitionHandle handle, MetadataGenericContext genericContext) { var metadata = module.Metadata; WriteMetadataToken(output, module, handle, MetadataTokens.GetToken(handle), spaceAfter: true, spaceBefore: false, ShowMetadataTokens, ShowMetadataTokensInBase10); var methodDefinition = metadata.GetMethodDefinition(handle); // .method public hidebysig specialname // instance default class [mscorlib]System.IO.TextWriter get_BaseWriter () cil managed // //emit flags WriteEnum(methodDefinition.Attributes & MethodAttributes.MemberAccessMask, methodVisibility); WriteFlags(methodDefinition.Attributes & ~MethodAttributes.MemberAccessMask, methodAttributeFlags); bool isCompilerControlled = (methodDefinition.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.PrivateScope; if (isCompilerControlled) output.Write("privatescope "); if ((methodDefinition.Attributes & MethodAttributes.PinvokeImpl) == MethodAttributes.PinvokeImpl) { output.Write("pinvokeimpl"); var info = methodDefinition.GetImport(); if (!info.Module.IsNil) { var moduleRef = metadata.GetModuleReference(info.Module); output.Write("(\"" + DisassemblerHelpers.EscapeString(metadata.GetString(moduleRef.Name)) + "\""); if (!info.Name.IsNil && metadata.GetString(info.Name) != metadata.GetString(methodDefinition.Name)) output.Write(" as \"" + DisassemblerHelpers.EscapeString(metadata.GetString(info.Name)) + "\""); if ((info.Attributes & MethodImportAttributes.ExactSpelling) == MethodImportAttributes.ExactSpelling) output.Write(" nomangle"); switch (info.Attributes & MethodImportAttributes.CharSetMask) { case MethodImportAttributes.CharSetAnsi: output.Write(" ansi"); break; case MethodImportAttributes.CharSetAuto: output.Write(" autochar"); break; case MethodImportAttributes.CharSetUnicode: output.Write(" unicode"); break; } if ((info.Attributes & MethodImportAttributes.SetLastError) == MethodImportAttributes.SetLastError) output.Write(" lasterr"); switch (info.Attributes & MethodImportAttributes.CallingConventionMask) { case MethodImportAttributes.CallingConventionCDecl: output.Write(" cdecl"); break; case MethodImportAttributes.CallingConventionFastCall: output.Write(" fastcall"); break; case MethodImportAttributes.CallingConventionStdCall: output.Write(" stdcall"); break; case MethodImportAttributes.CallingConventionThisCall: output.Write(" thiscall"); break; case MethodImportAttributes.CallingConventionWinApi: output.Write(" winapi"); break; } output.Write(')'); } output.Write(' '); } output.WriteLine(); output.Indent(); var declaringType = methodDefinition.GetDeclaringType(); MethodSignature<Action<ILNameSyntax>>? signature; try { var signatureProvider = new DisassemblerSignatureTypeProvider(module, output); signature = methodDefinition.DecodeSignature(signatureProvider, genericContext); if (signature.Value.Header.HasExplicitThis) { output.Write("instance explicit "); } else if (signature.Value.Header.IsInstance) { output.Write("instance "); } //call convention WriteEnum(signature.Value.Header.CallingConvention, callingConvention); //return type signature.Value.ReturnType(ILNameSyntax.Signature); } catch (BadImageFormatException) { signature = null; output.Write("<bad signature>"); } output.Write(' '); var parameters = methodDefinition.GetParameters(); if (parameters.Count > 0) { var firstParam = metadata.GetParameter(parameters.First()); if (firstParam.SequenceNumber == 0) { var marshallingDesc = firstParam.GetMarshallingDescriptor(); if (!marshallingDesc.IsNil) { WriteMarshalInfo(metadata.GetBlobReader(marshallingDesc)); } } } if (isCompilerControlled) { output.Write(DisassemblerHelpers.Escape(metadata.GetString(methodDefinition.Name) + "$PST" + MetadataTokens.GetToken(handle).ToString("X8"))); } else { output.Write(DisassemblerHelpers.Escape(metadata.GetString(methodDefinition.Name))); } WriteTypeParameters(output, module, genericContext, methodDefinition.GetGenericParameters()); //( params ) output.Write(" ("); if (signature?.ParameterTypes.Length > 0) { output.WriteLine(); output.Indent(); WriteParameters(metadata, parameters, signature.Value); output.Unindent(); } output.Write(") "); //cil managed WriteEnum(methodDefinition.ImplAttributes & MethodImplAttributes.CodeTypeMask, methodCodeType); if ((methodDefinition.ImplAttributes & MethodImplAttributes.ManagedMask) == MethodImplAttributes.Managed) output.Write("managed "); else output.Write("unmanaged "); WriteFlags(methodDefinition.ImplAttributes & ~(MethodImplAttributes.CodeTypeMask | MethodImplAttributes.ManagedMask), methodImpl); output.Unindent(); } internal static void WriteMetadataToken(ITextOutput output, PEFile module, Handle? handle, int metadataToken, bool spaceAfter, bool spaceBefore, bool showMetadataTokens, bool base10) { // handle can be null in case of errors, if that's the case, we always want to print a comment, // with the metadataToken. if (showMetadataTokens || handle == null) { if (spaceBefore) { output.Write(' '); } output.Write("/* "); string format = base10 ? null : "X8"; if (handle == null || !handle.Value.IsEntityHandle()) { output.Write(metadataToken.ToString(format)); } else { output.WriteReference(module, handle.GetValueOrDefault(), metadataToken.ToString(format), "metadata"); } output.Write(" */"); if (spaceAfter) { output.Write(' '); } } else if (spaceBefore && spaceAfter) { output.Write(' '); } } void DisassembleMethodBlock(PEFile module, MethodDefinitionHandle handle, MetadataGenericContext genericContext) { var metadata = module.Metadata; var methodDefinition = metadata.GetMethodDefinition(handle); OpenBlock(defaultCollapsed: isInType); WriteAttributes(module, methodDefinition.GetCustomAttributes()); foreach (var h in handle.GetMethodImplementations(metadata)) { var impl = metadata.GetMethodImplementation(h); output.Write(".override method "); impl.MethodDeclaration.WriteTo(module, output, genericContext); output.WriteLine(); } foreach (var p in methodDefinition.GetGenericParameters()) { WriteGenericParametersAndAttributes(module, genericContext, p); } foreach (var p in methodDefinition.GetParameters()) { WriteParameterAttributes(module, p); } WriteSecurityDeclarations(module, methodDefinition.GetDeclarativeSecurityAttributes()); if (methodDefinition.HasBody()) { methodBodyDisassembler.Disassemble(module, handle); } var declaringType = metadata.GetTypeDefinition(methodDefinition.GetDeclaringType()); CloseBlock("end of method " + DisassemblerHelpers.Escape(metadata.GetString(declaringType.Name)) + "::" + DisassemblerHelpers.Escape(metadata.GetString(methodDefinition.Name))); } #region Write Security Declarations void WriteSecurityDeclarations(PEFile module, DeclarativeSecurityAttributeHandleCollection secDeclProvider) { if (secDeclProvider.Count == 0) return; foreach (var h in secDeclProvider) { output.Write(".permissionset "); var secdecl = module.Metadata.GetDeclarativeSecurityAttribute(h); switch ((ushort)secdecl.Action) { case 1: // DeclarativeSecurityAction.Request output.Write("request"); break; case 2: // DeclarativeSecurityAction.Demand output.Write("demand"); break; case 3: // DeclarativeSecurityAction.Assert output.Write("assert"); break; case 4: // DeclarativeSecurityAction.Deny output.Write("deny"); break; case 5: // DeclarativeSecurityAction.PermitOnly output.Write("permitonly"); break; case 6: // DeclarativeSecurityAction.LinkDemand output.Write("linkcheck"); break; case 7: // DeclarativeSecurityAction.InheritDemand output.Write("inheritcheck"); break; case 8: // DeclarativeSecurityAction.RequestMinimum output.Write("reqmin"); break; case 9: // DeclarativeSecurityAction.RequestOptional output.Write("reqopt"); break; case 10: // DeclarativeSecurityAction.RequestRefuse output.Write("reqrefuse"); break; case 11: // DeclarativeSecurityAction.PreJitGrant output.Write("prejitgrant"); break; case 12: // DeclarativeSecurityAction.PreJitDeny output.Write("prejitdeny"); break; case 13: // DeclarativeSecurityAction.NonCasDemand output.Write("noncasdemand"); break; case 14: // DeclarativeSecurityAction.NonCasLinkDemand output.Write("noncaslinkdemand"); break; case 15: // DeclarativeSecurityAction.NonCasInheritance output.Write("noncasinheritance"); break; default: output.Write(secdecl.Action.ToString()); break; } var blob = module.Metadata.GetBlobReader(secdecl.PermissionSet); if (AssemblyResolver == null) { output.Write(" = "); WriteBlob(blob); output.WriteLine(); } else if ((char)blob.ReadByte() != '.') { blob.Reset(); output.WriteLine(); output.Indent(); output.Write("bytearray"); WriteBlob(blob); output.WriteLine(); output.Unindent(); } else { var outputWithRollback = new TextOutputWithRollback(output); try { TryDecodeSecurityDeclaration(outputWithRollback, blob, module); outputWithRollback.Commit(); } catch (Exception ex) when (ex is BadImageFormatException || ex is EnumUnderlyingTypeResolveException) { blob.Reset(); output.Write(" = "); WriteBlob(blob); output.WriteLine(); } } } } class SecurityDeclarationDecoder : ICustomAttributeTypeProvider<(PrimitiveTypeCode, string)> { readonly ITextOutput output; readonly IAssemblyResolver resolver; readonly PEFile module; public SecurityDeclarationDecoder(ITextOutput output, IAssemblyResolver resolver, PEFile module) { this.output = output; this.resolver = resolver; this.module = module; } public (PrimitiveTypeCode, string) GetPrimitiveType(PrimitiveTypeCode typeCode) { return (typeCode, null); } public (PrimitiveTypeCode, string) GetSystemType() { return (0, "type"); } public (PrimitiveTypeCode, string) GetSZArrayType((PrimitiveTypeCode, string) elementType) { return (elementType.Item1, (elementType.Item2 ?? PrimitiveTypeCodeToString(elementType.Item1)) + "[]"); } public (PrimitiveTypeCode, string) GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { throw new NotImplementedException(); } public (PrimitiveTypeCode, string) GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { throw new NotImplementedException(); } public (PrimitiveTypeCode, string) GetTypeFromSerializedName(string name) { if (resolver == null) throw new EnumUnderlyingTypeResolveException(); var (containingModule, typeDefHandle) = ResolveType(name, module); if (typeDefHandle.IsNil) throw new EnumUnderlyingTypeResolveException(); if (typeDefHandle.IsEnum(containingModule.Metadata, out var typeCode)) return (typeCode, "enum " + name); return (0, name); } public PrimitiveTypeCode GetUnderlyingEnumType((PrimitiveTypeCode, string) type) { return type.Item1; } public bool IsSystemType((PrimitiveTypeCode, string) type) { return "type" == type.Item2; } (PEFile, TypeDefinitionHandle) ResolveType(string typeName, PEFile module) { string[] nameParts = typeName.Split(new[] { ", " }, 2, StringSplitOptions.None); string[] typeNameParts = nameParts[0].Split('.'); PEFile containingModule = null; TypeDefinitionHandle typeDefHandle = default; // if we deal with an assembly-qualified name, resolve the assembly if (nameParts.Length == 2) containingModule = resolver.Resolve(AssemblyNameReference.Parse(nameParts[1])); if (containingModule != null) { // try to find the type in the assembly typeDefHandle = FindType(containingModule, typeNameParts); } else { // just fully-qualified name, try current assembly typeDefHandle = FindType(module, typeNameParts); containingModule = module; if (typeDefHandle.IsNil && TryResolveMscorlib(out var mscorlib)) { // otherwise try mscorlib typeDefHandle = FindType(mscorlib, typeNameParts); containingModule = mscorlib; } } return (containingModule, typeDefHandle); TypeDefinitionHandle FindType(PEFile currentModule, string[] name) { var metadata = currentModule.Metadata; var currentNamespace = metadata.GetNamespaceDefinitionRoot(); ImmutableArray<TypeDefinitionHandle> typeDefinitions = default; for (int i = 0; i < name.Length; i++) { string identifier = name[i]; if (!typeDefinitions.IsDefault) { restart: foreach (var type in typeDefinitions) { var typeDef = metadata.GetTypeDefinition(type); var currentTypeName = metadata.GetString(typeDef.Name); if (identifier == currentTypeName) { if (i + 1 == name.Length) return type; typeDefinitions = typeDef.GetNestedTypes(); goto restart; } } } else { var next = currentNamespace.NamespaceDefinitions.FirstOrDefault(ns => metadata.StringComparer.Equals(metadata.GetNamespaceDefinition(ns).Name, identifier)); if (!next.IsNil) { currentNamespace = metadata.GetNamespaceDefinition(next); } else { typeDefinitions = currentNamespace.TypeDefinitions; i--; } } } return default; } } PrimitiveTypeCode ResolveEnumUnderlyingType(string typeName, PEFile module) { if (typeName.StartsWith("enum ", StringComparison.Ordinal)) typeName = typeName.Substring(5); var (containingModule, typeDefHandle) = ResolveType(typeName, module); if (typeDefHandle.IsNil || !typeDefHandle.IsEnum(containingModule.Metadata, out var typeCode)) throw new EnumUnderlyingTypeResolveException(); return typeCode; } PEFile mscorlib; bool TryResolveMscorlib(out PEFile mscorlib) { mscorlib = null; if (this.mscorlib != null) { mscorlib = this.mscorlib; return true; } if (resolver == null) { return false; } this.mscorlib = mscorlib = resolver.Resolve(AssemblyNameReference.Parse("mscorlib")); return this.mscorlib != null; } } void TryDecodeSecurityDeclaration(TextOutputWithRollback output, BlobReader blob, PEFile module) { output.WriteLine(" = {"); output.Indent(); string currentAssemblyName = null; string currentFullAssemblyName = null; if (module.Metadata.IsAssembly) { try { currentAssemblyName = module.Metadata.GetString(module.Metadata.GetAssemblyDefinition().Name); } catch (BadImageFormatException) { currentAssemblyName = "<ERR: invalid assembly name>"; } if (!module.Metadata.TryGetFullAssemblyName(out currentFullAssemblyName)) { currentFullAssemblyName = "<ERR: invalid assembly name>"; } } int count = blob.ReadCompressedInteger(); for (int i = 0; i < count; i++) { var fullTypeName = blob.ReadSerializedString(); string[] nameParts = fullTypeName.Split(new[] { ", " }, StringSplitOptions.None); if (nameParts.Length < 2 || nameParts[1] == currentAssemblyName) { output.Write("class "); output.Write(DisassemblerHelpers.Escape(fullTypeName)); } else { output.Write('['); output.Write(nameParts[1]); output.Write(']'); output.Write(nameParts[0]); } output.Write(" = {"); blob.ReadCompressedInteger(); // ? // The specification seems to be incorrect here, so I'm using the logic from Cecil instead. int argCount = blob.ReadCompressedInteger(); var decoder = new CustomAttributeDecoder<(PrimitiveTypeCode Code, string Name)>(new SecurityDeclarationDecoder(output, AssemblyResolver, module), module.Metadata, provideBoxingTypeInfo: true); var arguments = decoder.DecodeNamedArguments(ref blob, argCount); if (argCount > 0) { output.WriteLine(); output.Indent(); } foreach (var argument in arguments) { switch (argument.Kind) { case CustomAttributeNamedArgumentKind.Field: output.Write("field "); break; case CustomAttributeNamedArgumentKind.Property: output.Write("property "); break; } output.Write(argument.Type.Name ?? PrimitiveTypeCodeToString(argument.Type.Code)); output.Write(" " + argument.Name + " = "); WriteValue(output, argument.Type, argument.Value); output.WriteLine(); } if (argCount > 0) { output.Unindent(); } output.Write('}'); if (i + 1 < count) output.Write(','); output.WriteLine(); } output.Unindent(); output.WriteLine("}"); } void WriteValue(ITextOutput output, (PrimitiveTypeCode Code, string Name) type, object value) { if (value is CustomAttributeTypedArgument<(PrimitiveTypeCode, string)> boxedValue) { output.Write("object("); WriteValue(output, boxedValue.Type, boxedValue.Value); output.Write(")"); } else if (value is ImmutableArray<CustomAttributeTypedArgument<(PrimitiveTypeCode, string)>> arrayValue) { string elementType = type.Name != null && !type.Name.StartsWith("enum ", StringComparison.Ordinal) ? type.Name.Remove(type.Name.Length - 2) : PrimitiveTypeCodeToString(type.Code); output.Write(elementType); output.Write("["); output.Write(arrayValue.Length.ToString()); output.Write("]("); bool first = true; foreach (var item in arrayValue) { if (!first) output.Write(" "); if (item.Value is CustomAttributeTypedArgument<(PrimitiveTypeCode, string)> boxedItem) { WriteValue(output, boxedItem.Type, boxedItem.Value); } else { WriteSimpleValue(output, item.Value, elementType); } first = false; } output.Write(")"); } else { string typeName = type.Name != null && !type.Name.StartsWith("enum ", StringComparison.Ordinal) ? type.Name : PrimitiveTypeCodeToString(type.Code); output.Write(typeName); output.Write("("); WriteSimpleValue(output, value, typeName); output.Write(")"); } } private static void WriteSimpleValue(ITextOutput output, object value, string typeName) { switch (typeName) { case "string": output.Write("'" + DisassemblerHelpers.EscapeString(value.ToString()).Replace("'", "\\'") + "'"); break; case "type": var info = ((PrimitiveTypeCode Code, string Name))value; if (info.Name.StartsWith("enum ", StringComparison.Ordinal)) { output.Write(info.Name.Substring(5)); } else { output.Write(info.Name); } break; default: DisassemblerHelpers.WriteOperand(output, value); break; } } static string PrimitiveTypeCodeToString(PrimitiveTypeCode typeCode) { switch (typeCode) { case PrimitiveTypeCode.Boolean: return "bool"; case PrimitiveTypeCode.Byte: return "uint8"; case PrimitiveTypeCode.SByte: return "int8"; case PrimitiveTypeCode.Char: return "char"; case PrimitiveTypeCode.Int16: return "int16"; case PrimitiveTypeCode.UInt16: return "uint16"; case PrimitiveTypeCode.Int32: return "int32"; case PrimitiveTypeCode.UInt32: return "uint32"; case PrimitiveTypeCode.Int64: return "int64"; case PrimitiveTypeCode.UInt64: return "uint64"; case PrimitiveTypeCode.Single: return "float32"; case PrimitiveTypeCode.Double: return "float64"; case PrimitiveTypeCode.String: return "string"; case PrimitiveTypeCode.Object: return "object"; default: return "unknown"; } } #endregion #region WriteMarshalInfo void WriteMarshalInfo(BlobReader marshalInfo) { output.Write("marshal("); WriteNativeType(ref marshalInfo); output.Write(") "); } void WriteNativeType(ref BlobReader blob) { byte type; switch (type = blob.ReadByte()) { case 0x66: // None case 0x50: // Max break; case 0x02: // NATIVE_TYPE_BOOLEAN output.Write("bool"); break; case 0x03: // NATIVE_TYPE_I1 output.Write("int8"); break; case 0x04: // NATIVE_TYPE_U1 output.Write("unsigned int8"); break; case 0x05: // NATIVE_TYPE_I2 output.Write("int16"); break; case 0x06: // NATIVE_TYPE_U2 output.Write("unsigned int16"); break; case 0x07: // NATIVE_TYPE_I4 output.Write("int32"); break; case 0x08: // NATIVE_TYPE_U4 output.Write("unsigned int32"); break; case 0x09: // NATIVE_TYPE_I8 output.Write("int64"); break; case 0x0a: // NATIVE_TYPE_U8 output.Write("unsigned int64"); break; case 0x0b: // NATIVE_TYPE_R4 output.Write("float32"); break; case 0x0c: // NATIVE_TYPE_R8 output.Write("float64"); break; case 0x14: // NATIVE_TYPE_LPSTR output.Write("lpstr"); break; case 0x1f: // NATIVE_TYPE_INT output.Write("int"); break; case 0x20: // NATIVE_TYPE_UINT output.Write("unsigned int"); break; case 0x26: // NATIVE_TYPE_FUNC output.Write("Func"); break; case 0x2a: // NATIVE_TYPE_ARRAY if (blob.RemainingBytes > 0) WriteNativeType(ref blob); output.Write('['); int sizeParameterIndex = blob.TryReadCompressedInteger(out int value) ? value : -1; int size = blob.TryReadCompressedInteger(out value) ? value : -1; int sizeParameterMultiplier = blob.TryReadCompressedInteger(out value) ? value : -1; if (size >= 0) { output.Write(size.ToString()); } if (sizeParameterIndex >= 0 && sizeParameterMultiplier != 0) { output.Write(" + "); output.Write(sizeParameterIndex.ToString()); } output.Write(']'); break; case 0x0f: // Currency output.Write("currency"); break; case 0x13: // BStr output.Write("bstr"); break; case 0x15: // LPWStr output.Write("lpwstr"); break; case 0x16: // LPTStr output.Write("lptstr"); break; case 0x17: // FixedSysString output.Write("fixed sysstring[{0}]", blob.ReadCompressedInteger()); break; case 0x19: // IUnknown output.Write("iunknown"); break; case 0x1a: // IDispatch output.Write("idispatch"); break; case 0x1b: // Struct output.Write("struct"); break; case 0x1c: // IntF output.Write("interface"); break; case 0x1d: // SafeArray output.Write("safearray "); if (blob.RemainingBytes > 0) { byte elementType = blob.ReadByte(); switch (elementType) { case 0: // None break; case 2: // I2 output.Write("int16"); break; case 3: // I4 output.Write("int32"); break; case 4: // R4 output.Write("float32"); break; case 5: // R8 output.Write("float64"); break; case 6: // Currency output.Write("currency"); break; case 7: // Date output.Write("date"); break; case 8: // BStr output.Write("bstr"); break; case 9: // Dispatch output.Write("idispatch"); break; case 10: // Error output.Write("error"); break; case 11: // Bool output.Write("bool"); break; case 12: // Variant output.Write("variant"); break; case 13: // Unknown output.Write("iunknown"); break; case 14: // Decimal output.Write("decimal"); break; case 16: // I1 output.Write("int8"); break; case 17: // UI1 output.Write("unsigned int8"); break; case 18: // UI2 output.Write("unsigned int16"); break; case 19: // UI4 output.Write("unsigned int32"); break; case 22: // Int output.Write("int"); break; case 23: // UInt output.Write("unsigned int"); break; default: output.Write(elementType.ToString()); break; } } break; case 0x1e: // FixedArray output.Write("fixed array"); output.Write("[{0}]", blob.TryReadCompressedInteger(out value) ? value : 0); if (blob.RemainingBytes > 0) { output.Write(' '); WriteNativeType(ref blob); } break; case 0x22: // ByValStr output.Write("byvalstr"); break; case 0x23: // ANSIBStr output.Write("ansi bstr"); break; case 0x24: // TBStr output.Write("tbstr"); break; case 0x25: // VariantBool output.Write("variant bool"); break; case 0x28: // ASAny output.Write("as any"); break; case 0x2b: // LPStruct output.Write("lpstruct"); break; case 0x2c: // CustomMarshaler string guidValue = blob.ReadSerializedString(); string unmanagedType = blob.ReadSerializedString(); string managedType = blob.ReadSerializedString(); string cookie = blob.ReadSerializedString(); var guid = !string.IsNullOrEmpty(guidValue) ? new Guid(guidValue) : Guid.Empty; output.Write("custom(\"{0}\", \"{1}\"", DisassemblerHelpers.EscapeString(managedType), DisassemblerHelpers.EscapeString(cookie)); if (guid != Guid.Empty || !string.IsNullOrEmpty(unmanagedType)) { output.Write(", \"{0}\", \"{1}\"", guid.ToString(), DisassemblerHelpers.EscapeString(unmanagedType)); } output.Write(')'); break; case 0x2d: // Error output.Write("error"); break; default: output.Write(type.ToString()); break; } } #endregion void WriteParameters(MetadataReader metadata, IEnumerable<ParameterHandle> parameters, MethodSignature<Action<ILNameSyntax>> signature) { int i = 0; int offset = signature.Header.IsInstance ? 1 : 0; foreach (var h in parameters) { var p = metadata.GetParameter(h); // skip return type parameter handle if (p.SequenceNumber == 0) continue; // fill gaps in parameter list while (i < p.SequenceNumber - 1) { if (i > 0) { output.Write(','); output.WriteLine(); } signature.ParameterTypes[i](ILNameSyntax.Signature); output.Write(' '); output.WriteLocalReference("''", "param_" + (i + offset), isDefinition: true); i++; } // separator if (i > 0) { output.Write(','); output.WriteLine(); } // print parameter if ((p.Attributes & ParameterAttributes.In) == ParameterAttributes.In) output.Write("[in] "); if ((p.Attributes & ParameterAttributes.Out) == ParameterAttributes.Out) output.Write("[out] "); if ((p.Attributes & ParameterAttributes.Optional) == ParameterAttributes.Optional) output.Write("[opt] "); signature.ParameterTypes[i](ILNameSyntax.Signature); output.Write(' '); var md = p.GetMarshallingDescriptor(); if (!md.IsNil) { WriteMarshalInfo(metadata.GetBlobReader(md)); } output.WriteLocalReference(DisassemblerHelpers.Escape(metadata.GetString(p.Name)), "param_" + (i + offset), isDefinition: true); i++; } // add remaining parameter types as unnamed parameters while (i < signature.RequiredParameterCount) { if (i > 0) { output.Write(','); output.WriteLine(); } signature.ParameterTypes[i](ILNameSyntax.Signature); output.Write(' '); output.WriteLocalReference("''", "param_" + (i + offset), isDefinition: true); i++; } output.WriteLine(); } void WriteGenericParametersAndAttributes(PEFile module, MetadataGenericContext context, GenericParameterHandle handle) { var metadata = module.Metadata; var p = metadata.GetGenericParameter(handle); if (p.GetCustomAttributes().Count > 0) { output.Write(".param type {0}", metadata.GetString(p.Name)); output.WriteLine(); output.Indent(); WriteAttributes(module, p.GetCustomAttributes()); output.Unindent(); } foreach (var constraintHandle in p.GetConstraints()) { var constraint = metadata.GetGenericParameterConstraint(constraintHandle); if (constraint.GetCustomAttributes().Count > 0) { output.Write(".param constraint {0}, ", metadata.GetString(p.Name)); constraint.Type.WriteTo(module, output, context, ILNameSyntax.TypeName); output.WriteLine(); output.Indent(); WriteAttributes(module, constraint.GetCustomAttributes()); output.Unindent(); } } } void WriteParameterAttributes(PEFile module, ParameterHandle handle) { var metadata = module.Metadata; var p = metadata.GetParameter(handle); if (p.GetDefaultValue().IsNil && p.GetCustomAttributes().Count == 0) return; output.Write(".param [{0}]", p.SequenceNumber); if (!p.GetDefaultValue().IsNil) { output.Write(" = "); WriteConstant(metadata, metadata.GetConstant(p.GetDefaultValue())); } output.WriteLine(); output.Indent(); WriteAttributes(module, p.GetCustomAttributes()); output.Unindent(); } void WriteConstant(MetadataReader metadata, Constant constant) { switch (constant.TypeCode) { case ConstantTypeCode.NullReference: output.Write("nullref"); break; default: var blob = metadata.GetBlobReader(constant.Value); object value; try { value = blob.ReadConstant(constant.TypeCode); } catch (ArgumentOutOfRangeException) { output.Write($"/* Constant with invalid typecode: {constant.TypeCode} */"); return; } if (value is string) { DisassemblerHelpers.WriteOperand(output, value); } else { string typeName = DisassemblerHelpers.PrimitiveTypeName(value.GetType().FullName); output.Write(typeName); output.Write('('); float? cf = value as float?; double? cd = value as double?; if (cf.HasValue && (float.IsNaN(cf.Value) || float.IsInfinity(cf.Value))) { output.Write("0x{0:x8}", BitConverter.ToInt32(BitConverter.GetBytes(cf.Value), 0)); } else if (cd.HasValue && (double.IsNaN(cd.Value) || double.IsInfinity(cd.Value))) { output.Write("0x{0:x16}", BitConverter.DoubleToInt64Bits(cd.Value)); } else { DisassemblerHelpers.WriteOperand(output, value); } output.Write(')'); } break; } } #endregion #region Disassemble Field EnumNameCollection<FieldAttributes> fieldVisibility = new EnumNameCollection<FieldAttributes>() { { FieldAttributes.Private, "private" }, { FieldAttributes.FamANDAssem, "famandassem" }, { FieldAttributes.Assembly, "assembly" }, { FieldAttributes.Family, "family" }, { FieldAttributes.FamORAssem, "famorassem" }, { FieldAttributes.Public, "public" }, }; EnumNameCollection<FieldAttributes> fieldAttributes = new EnumNameCollection<FieldAttributes>() { { FieldAttributes.Static, "static" }, { FieldAttributes.Literal, "literal" }, { FieldAttributes.InitOnly, "initonly" }, { FieldAttributes.SpecialName, "specialname" }, { FieldAttributes.RTSpecialName, "rtspecialname" }, { FieldAttributes.NotSerialized, "notserialized" }, }; public void DisassembleField(PEFile module, FieldDefinitionHandle handle) { var metadata = module.Metadata; var fieldDefinition = metadata.GetFieldDefinition(handle); char sectionPrefix = DisassembleFieldHeaderInternal(module, handle, metadata, fieldDefinition); output.WriteLine(); var attributes = fieldDefinition.GetCustomAttributes(); if (attributes.Count > 0) { output.MarkFoldStart(); WriteAttributes(module, fieldDefinition.GetCustomAttributes()); output.MarkFoldEnd(); } if (fieldDefinition.HasFlag(FieldAttributes.HasFieldRVA)) { // Field data as specified in II.16.3.1 of ECMA-335 6th edition int rva = fieldDefinition.GetRelativeVirtualAddress(); int sectionIndex = module.Reader.PEHeaders.GetContainingSectionIndex(rva); if (sectionIndex < 0) { output.WriteLine($"// RVA {rva:X8} invalid (not in any section)"); } else { BlobReader initVal; try { initVal = fieldDefinition.GetInitialValue(module.Reader, null); } catch (BadImageFormatException ex) { initVal = default; output.WriteLine("// .data {2}_{0:X8} = {1}", fieldDefinition.GetRelativeVirtualAddress(), ex.Message, sectionPrefix); } if (initVal.Length > 0) { var sectionHeader = module.Reader.PEHeaders.SectionHeaders[sectionIndex]; output.Write(".data "); if (sectionHeader.Name == ".text") { output.Write("cil "); } else if (sectionHeader.Name == ".tls") { output.Write("tls "); } else if (sectionHeader.Name != ".data") { output.Write($"/* {sectionHeader.Name} */ "); } output.Write($"{sectionPrefix}_{rva:X8} = bytearray "); WriteBlob(initVal); output.WriteLine(); } } } } public void DisassembleFieldHeader(PEFile module, FieldDefinitionHandle handle) { var metadata = module.Metadata; var fieldDefinition = metadata.GetFieldDefinition(handle); DisassembleFieldHeaderInternal(module, handle, metadata, fieldDefinition); } private char DisassembleFieldHeaderInternal(PEFile module, FieldDefinitionHandle handle, MetadataReader metadata, FieldDefinition fieldDefinition) { output.WriteReference(module, handle, ".field", isDefinition: true); WriteMetadataToken(output, module, handle, MetadataTokens.GetToken(handle), spaceAfter: true, spaceBefore: true, ShowMetadataTokens, ShowMetadataTokensInBase10); int offset = fieldDefinition.GetOffset(); if (offset > -1) { output.Write("[" + offset + "] "); } WriteEnum(fieldDefinition.Attributes & FieldAttributes.FieldAccessMask, fieldVisibility); const FieldAttributes hasXAttributes = FieldAttributes.HasDefault | FieldAttributes.HasFieldMarshal | FieldAttributes.HasFieldRVA; WriteFlags(fieldDefinition.Attributes & ~(FieldAttributes.FieldAccessMask | hasXAttributes), fieldAttributes); var signature = fieldDefinition.DecodeSignature(new DisassemblerSignatureTypeProvider(module, output), new MetadataGenericContext(fieldDefinition.GetDeclaringType(), module)); var marshallingDescriptor = fieldDefinition.GetMarshallingDescriptor(); if (!marshallingDescriptor.IsNil) { WriteMarshalInfo(metadata.GetBlobReader(marshallingDescriptor)); } signature(ILNameSyntax.Signature); output.Write(' '); var fieldName = metadata.GetString(fieldDefinition.Name); output.Write(DisassemblerHelpers.Escape(fieldName)); char sectionPrefix = 'D'; if (fieldDefinition.HasFlag(FieldAttributes.HasFieldRVA)) { int rva = fieldDefinition.GetRelativeVirtualAddress(); sectionPrefix = GetRVASectionPrefix(module.Reader.PEHeaders, rva); output.Write(" at {1}_{0:X8}", rva, sectionPrefix); } var defaultValue = fieldDefinition.GetDefaultValue(); if (!defaultValue.IsNil) { output.Write(" = "); WriteConstant(metadata, metadata.GetConstant(defaultValue)); } return sectionPrefix; } char GetRVASectionPrefix(System.Reflection.PortableExecutable.PEHeaders headers, int rva) { int sectionIndex = headers.GetContainingSectionIndex(rva); if (sectionIndex < 0) return 'D'; var sectionHeader = headers.SectionHeaders[sectionIndex]; switch (sectionHeader.Name) { case ".tls": return 'T'; case ".text": return 'I'; default: return 'D'; } } #endregion #region Disassemble Property EnumNameCollection<PropertyAttributes> propertyAttributes = new EnumNameCollection<PropertyAttributes>() { { PropertyAttributes.SpecialName, "specialname" }, { PropertyAttributes.RTSpecialName, "rtspecialname" }, { PropertyAttributes.HasDefault, "hasdefault" }, }; public void DisassembleProperty(PEFile module, PropertyDefinitionHandle property) { var metadata = module.Metadata; var propertyDefinition = metadata.GetPropertyDefinition(property); PropertyAccessors accessors = DisassemblePropertyHeaderInternal(module, property, metadata, propertyDefinition); OpenBlock(false); WriteAttributes(module, propertyDefinition.GetCustomAttributes()); WriteNestedMethod(".get", module, accessors.Getter); WriteNestedMethod(".set", module, accessors.Setter); foreach (var method in accessors.Others) { WriteNestedMethod(".other", module, method); } CloseBlock(); } public void DisassemblePropertyHeader(PEFile module, PropertyDefinitionHandle property) { var metadata = module.Metadata; var propertyDefinition = metadata.GetPropertyDefinition(property); DisassemblePropertyHeaderInternal(module, property, metadata, propertyDefinition); } private PropertyAccessors DisassemblePropertyHeaderInternal(PEFile module, PropertyDefinitionHandle handle, MetadataReader metadata, PropertyDefinition propertyDefinition) { output.WriteReference(module, handle, ".property", isDefinition: true); WriteMetadataToken(output, module, handle, MetadataTokens.GetToken(handle), spaceAfter: true, spaceBefore: true, ShowMetadataTokens, ShowMetadataTokensInBase10); WriteFlags(propertyDefinition.Attributes, propertyAttributes); var accessors = propertyDefinition.GetAccessors(); var declaringType = metadata.GetMethodDefinition(accessors.GetAny()).GetDeclaringType(); var signature = propertyDefinition.DecodeSignature(new DisassemblerSignatureTypeProvider(module, output), new MetadataGenericContext(declaringType, module)); if (signature.Header.IsInstance) output.Write("instance "); signature.ReturnType(ILNameSyntax.Signature); output.Write(' '); output.Write(DisassemblerHelpers.Escape(metadata.GetString(propertyDefinition.Name))); output.Write('('); if (signature.ParameterTypes.Length > 0) { var parameters = metadata.GetMethodDefinition(accessors.GetAny()).GetParameters(); int parametersCount = accessors.Getter.IsNil ? parameters.Count - 1 : parameters.Count; output.WriteLine(); output.Indent(); WriteParameters(metadata, parameters.Take(parametersCount), signature); output.Unindent(); } output.Write(')'); return accessors; } void WriteNestedMethod(string keyword, PEFile module, MethodDefinitionHandle method) { if (method.IsNil) return; output.Write(keyword); output.Write(' '); ((EntityHandle)method).WriteTo(module, output, default); output.WriteLine(); } #endregion #region Disassemble Event EnumNameCollection<EventAttributes> eventAttributes = new EnumNameCollection<EventAttributes>() { { EventAttributes.SpecialName, "specialname" }, { EventAttributes.RTSpecialName, "rtspecialname" }, }; public void DisassembleEvent(PEFile module, EventDefinitionHandle handle) { var eventDefinition = module.Metadata.GetEventDefinition(handle); var accessors = eventDefinition.GetAccessors(); DisassembleEventHeaderInternal(module, handle, eventDefinition, accessors); OpenBlock(false); WriteAttributes(module, eventDefinition.GetCustomAttributes()); WriteNestedMethod(".addon", module, accessors.Adder); WriteNestedMethod(".removeon", module, accessors.Remover); WriteNestedMethod(".fire", module, accessors.Raiser); foreach (var method in accessors.Others) { WriteNestedMethod(".other", module, method); } CloseBlock(); } public void DisassembleEventHeader(PEFile module, EventDefinitionHandle handle) { var eventDefinition = module.Metadata.GetEventDefinition(handle); var accessors = eventDefinition.GetAccessors(); DisassembleEventHeaderInternal(module, handle, eventDefinition, accessors); } private void DisassembleEventHeaderInternal(PEFile module, EventDefinitionHandle handle, EventDefinition eventDefinition, EventAccessors accessors) { TypeDefinitionHandle declaringType; if (!accessors.Adder.IsNil) { declaringType = module.Metadata.GetMethodDefinition(accessors.Adder).GetDeclaringType(); } else if (!accessors.Remover.IsNil) { declaringType = module.Metadata.GetMethodDefinition(accessors.Remover).GetDeclaringType(); } else { declaringType = module.Metadata.GetMethodDefinition(accessors.Raiser).GetDeclaringType(); } output.WriteReference(module, handle, ".event", isDefinition: true); WriteMetadataToken(output, module, handle, MetadataTokens.GetToken(handle), spaceAfter: true, spaceBefore: true, ShowMetadataTokens, ShowMetadataTokensInBase10); WriteFlags(eventDefinition.Attributes, eventAttributes); var provider = new DisassemblerSignatureTypeProvider(module, output); Action<ILNameSyntax> signature; switch (eventDefinition.Type.Kind) { case HandleKind.TypeDefinition: signature = provider.GetTypeFromDefinition(module.Metadata, (TypeDefinitionHandle)eventDefinition.Type, 0); break; case HandleKind.TypeReference: signature = provider.GetTypeFromReference(module.Metadata, (TypeReferenceHandle)eventDefinition.Type, 0); break; case HandleKind.TypeSpecification: signature = provider.GetTypeFromSpecification(module.Metadata, new MetadataGenericContext(declaringType, module), (TypeSpecificationHandle)eventDefinition.Type, 0); break; default: throw new BadImageFormatException("Expected a TypeDef, TypeRef or TypeSpec handle!"); } signature(ILNameSyntax.TypeName); output.Write(' '); output.Write(DisassemblerHelpers.Escape(module.Metadata.GetString(eventDefinition.Name))); } #endregion #region Disassemble Type EnumNameCollection<TypeAttributes> typeVisibility = new EnumNameCollection<TypeAttributes>() { { TypeAttributes.Public, "public" }, { TypeAttributes.NotPublic, "private" }, { TypeAttributes.NestedPublic, "nested public" }, { TypeAttributes.NestedPrivate, "nested private" }, { TypeAttributes.NestedAssembly, "nested assembly" }, { TypeAttributes.NestedFamily, "nested family" }, { TypeAttributes.NestedFamANDAssem, "nested famandassem" }, { TypeAttributes.NestedFamORAssem, "nested famorassem" }, }; EnumNameCollection<TypeAttributes> typeLayout = new EnumNameCollection<TypeAttributes>() { { TypeAttributes.AutoLayout, "auto" }, { TypeAttributes.SequentialLayout, "sequential" }, { TypeAttributes.ExplicitLayout, "explicit" }, }; EnumNameCollection<TypeAttributes> typeStringFormat = new EnumNameCollection<TypeAttributes>() { { TypeAttributes.AutoClass, "auto" }, { TypeAttributes.AnsiClass, "ansi" }, { TypeAttributes.UnicodeClass, "unicode" }, }; EnumNameCollection<TypeAttributes> typeAttributes = new EnumNameCollection<TypeAttributes>() { { TypeAttributes.Abstract, "abstract" }, { TypeAttributes.Sealed, "sealed" }, { TypeAttributes.SpecialName, "specialname" }, { TypeAttributes.Import, "import" }, { TypeAttributes.Serializable, "serializable" }, { TypeAttributes.WindowsRuntime, "windowsruntime" }, { TypeAttributes.BeforeFieldInit, "beforefieldinit" }, { TypeAttributes.HasSecurity, null }, }; public void DisassembleType(PEFile module, TypeDefinitionHandle type) { var typeDefinition = module.Metadata.GetTypeDefinition(type); MetadataGenericContext genericContext = new MetadataGenericContext(type, module); DisassembleTypeHeaderInternal(module, type, typeDefinition, genericContext); var interfaces = Process(module, typeDefinition.GetInterfaceImplementations()); if (interfaces.Count > 0) { output.Indent(); bool first = true; foreach (var i in interfaces) { if (!first) output.WriteLine(","); if (first) output.Write("implements "); else output.Write(" "); first = false; var iface = module.Metadata.GetInterfaceImplementation(i); iface.Interface.WriteTo(module, output, genericContext, ILNameSyntax.TypeName); } output.WriteLine(); output.Unindent(); } output.WriteLine("{"); output.Indent(); bool oldIsInType = isInType; isInType = true; WriteAttributes(module, typeDefinition.GetCustomAttributes()); WriteSecurityDeclarations(module, typeDefinition.GetDeclarativeSecurityAttributes()); foreach (var tp in typeDefinition.GetGenericParameters()) { WriteGenericParametersAndAttributes(module, genericContext, tp); } var layout = typeDefinition.GetLayout(); if (!layout.IsDefault) { output.WriteLine(".pack {0}", layout.PackingSize); output.WriteLine(".size {0}", layout.Size); output.WriteLine(); } foreach (var ifaceHandle in interfaces) { var iface = module.Metadata.GetInterfaceImplementation(ifaceHandle); var customAttributes = iface.GetCustomAttributes(); if (customAttributes.Count != 0) { output.Write(".interfaceimpl type "); iface.Interface.WriteTo(module, output, genericContext, ILNameSyntax.TypeName); output.WriteLine(); output.Indent(); WriteAttributes(module, customAttributes); output.Unindent(); output.WriteLine(); } } var nestedTypes = Process(module, typeDefinition.GetNestedTypes()); if (nestedTypes.Any()) { output.WriteLine("// Nested Types"); foreach (var nestedType in nestedTypes) { cancellationToken.ThrowIfCancellationRequested(); DisassembleType(module, nestedType); output.WriteLine(); } output.WriteLine(); } var fields = Process(module, typeDefinition.GetFields()); if (fields.Any()) { output.WriteLine("// Fields"); foreach (var field in fields) { cancellationToken.ThrowIfCancellationRequested(); DisassembleField(module, field); } output.WriteLine(); } var methods = Process(module, typeDefinition.GetMethods()); if (methods.Any()) { output.WriteLine("// Methods"); foreach (var m in methods) { cancellationToken.ThrowIfCancellationRequested(); DisassembleMethod(module, m); output.WriteLine(); } } var events = Process(module, typeDefinition.GetEvents()); if (events.Any()) { output.WriteLine("// Events"); foreach (var ev in events) { cancellationToken.ThrowIfCancellationRequested(); DisassembleEvent(module, ev); output.WriteLine(); } output.WriteLine(); } var properties = Process(module, typeDefinition.GetProperties()); if (properties.Any()) { output.WriteLine("// Properties"); foreach (var prop in properties) { cancellationToken.ThrowIfCancellationRequested(); DisassembleProperty(module, prop); } output.WriteLine(); } CloseBlock("end of class " + (!typeDefinition.GetDeclaringType().IsNil ? module.Metadata.GetString(typeDefinition.Name) : typeDefinition.GetFullTypeName(module.Metadata).ToString())); isInType = oldIsInType; } public void DisassembleTypeHeader(PEFile module, TypeDefinitionHandle type) { var typeDefinition = module.Metadata.GetTypeDefinition(type); MetadataGenericContext genericContext = new MetadataGenericContext(type, module); DisassembleTypeHeaderInternal(module, type, typeDefinition, genericContext); } private void DisassembleTypeHeaderInternal(PEFile module, TypeDefinitionHandle handle, TypeDefinition typeDefinition, MetadataGenericContext genericContext) { output.WriteReference(module, handle, ".class", isDefinition: true); WriteMetadataToken(output, module, handle, MetadataTokens.GetToken(handle), spaceAfter: true, spaceBefore: true, ShowMetadataTokens, ShowMetadataTokensInBase10); if ((typeDefinition.Attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) output.Write("interface "); WriteEnum(typeDefinition.Attributes & TypeAttributes.VisibilityMask, typeVisibility); WriteEnum(typeDefinition.Attributes & TypeAttributes.LayoutMask, typeLayout); WriteEnum(typeDefinition.Attributes & TypeAttributes.StringFormatMask, typeStringFormat); const TypeAttributes masks = TypeAttributes.ClassSemanticsMask | TypeAttributes.VisibilityMask | TypeAttributes.LayoutMask | TypeAttributes.StringFormatMask; WriteFlags(typeDefinition.Attributes & ~masks, typeAttributes); output.Write(typeDefinition.GetDeclaringType().IsNil ? typeDefinition.GetFullTypeName(module.Metadata).ToILNameString() : DisassemblerHelpers.Escape(module.Metadata.GetString(typeDefinition.Name))); WriteTypeParameters(output, module, genericContext, typeDefinition.GetGenericParameters()); output.MarkFoldStart(defaultCollapsed: !ExpandMemberDefinitions && isInType, isDefinition: isInType); output.WriteLine(); EntityHandle baseType = typeDefinition.GetBaseTypeOrNil(); if (!baseType.IsNil) { output.Indent(); output.Write("extends "); baseType.WriteTo(module, output, genericContext, ILNameSyntax.TypeName); output.WriteLine(); output.Unindent(); } } void WriteTypeParameters(ITextOutput output, PEFile module, MetadataGenericContext context, GenericParameterHandleCollection p) { if (p.Count > 0) { output.Write('<'); var metadata = module.Metadata; for (int i = 0; i < p.Count; i++) { if (i > 0) output.Write(", "); var gp = metadata.GetGenericParameter(p[i]); if ((gp.Attributes & GenericParameterAttributes.ReferenceTypeConstraint) == GenericParameterAttributes.ReferenceTypeConstraint) { output.Write("class "); } else if ((gp.Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) == GenericParameterAttributes.NotNullableValueTypeConstraint) { output.Write("valuetype "); } if ((gp.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) == GenericParameterAttributes.DefaultConstructorConstraint) { output.Write(".ctor "); } var constraints = gp.GetConstraints(); if (constraints.Count > 0) { output.Write('('); for (int j = 0; j < constraints.Count; j++) { if (j > 0) output.Write(", "); var constraint = metadata.GetGenericParameterConstraint(constraints[j]); constraint.Type.WriteTo(module, output, context, ILNameSyntax.TypeName); } output.Write(") "); } if ((gp.Attributes & GenericParameterAttributes.Contravariant) == GenericParameterAttributes.Contravariant) { output.Write('-'); } else if ((gp.Attributes & GenericParameterAttributes.Covariant) == GenericParameterAttributes.Covariant) { output.Write('+'); } output.Write(DisassemblerHelpers.Escape(metadata.GetString(gp.Name))); } output.Write('>'); } } #endregion #region Processing private IReadOnlyCollection<InterfaceImplementationHandle> Process(PEFile module, IReadOnlyCollection<InterfaceImplementationHandle> items) { return EntityProcessor?.Process(module, items) ?? items; } private IReadOnlyCollection<TypeDefinitionHandle> Process(PEFile module, IReadOnlyCollection<TypeDefinitionHandle> items) { return EntityProcessor?.Process(module, items) ?? items; } private IReadOnlyCollection<MethodDefinitionHandle> Process(PEFile module, IReadOnlyCollection<MethodDefinitionHandle> items) { return EntityProcessor?.Process(module, items) ?? items; } private IReadOnlyCollection<PropertyDefinitionHandle> Process(PEFile module, IReadOnlyCollection<PropertyDefinitionHandle> items) { return EntityProcessor?.Process(module, items) ?? items; } private IReadOnlyCollection<EventDefinitionHandle> Process(PEFile module, IReadOnlyCollection<EventDefinitionHandle> items) { return EntityProcessor?.Process(module, items) ?? items; } private IReadOnlyCollection<FieldDefinitionHandle> Process(PEFile module, IReadOnlyCollection<FieldDefinitionHandle> items) { return EntityProcessor?.Process(module, items) ?? items; } private IReadOnlyCollection<CustomAttributeHandle> Process(PEFile module, IReadOnlyCollection<CustomAttributeHandle> items) { return EntityProcessor?.Process(module, items) ?? items; } #endregion #region Helper methods void WriteAttributes(PEFile module, CustomAttributeHandleCollection attributes) { var metadata = module.Metadata; foreach (CustomAttributeHandle a in Process(module, attributes)) { output.Write(".custom "); WriteMetadataToken(output, module, a, MetadataTokens.GetToken(a), spaceAfter: true, spaceBefore: false, ShowMetadataTokens, ShowMetadataTokensInBase10); var attr = metadata.GetCustomAttribute(a); attr.Constructor.WriteTo(module, output, default); if (!attr.Value.IsNil) { output.Write(" = "); WriteBlob(attr.Value, metadata); } output.WriteLine(); } } void WriteBlob(BlobHandle blob, MetadataReader metadata) { var reader = metadata.GetBlobReader(blob); WriteBlob(reader); } void WriteBlob(BlobReader reader) { output.Write("("); output.Indent(); for (int i = 0; i < reader.Length; i++) { if (i % 16 == 0 && i < reader.Length - 1) { output.WriteLine(); } else { output.Write(' '); } output.Write(reader.ReadByte().ToString("x2")); } output.WriteLine(); output.Unindent(); output.Write(")"); } void OpenBlock(bool defaultCollapsed) { output.MarkFoldStart(defaultCollapsed: !ExpandMemberDefinitions && defaultCollapsed, isDefinition: true); output.WriteLine(); output.WriteLine("{"); output.Indent(); } void CloseBlock(string comment = null) { output.Unindent(); output.Write("}"); if (comment != null) output.Write(" // " + comment); output.MarkFoldEnd(); output.WriteLine(); } void WriteFlags<T>(T flags, EnumNameCollection<T> flagNames) where T : struct { long val = Convert.ToInt64(flags); long tested = 0; foreach (var pair in flagNames) { tested |= pair.Key; if ((val & pair.Key) != 0 && pair.Value != null) { output.Write(pair.Value); output.Write(' '); } } if ((val & ~tested) != 0) output.Write("flag({0:x4}) ", val & ~tested); } void WriteEnum<T>(T enumValue, EnumNameCollection<T> enumNames) where T : struct { long val = Convert.ToInt64(enumValue); foreach (var pair in enumNames) { if (pair.Key == val) { if (pair.Value != null) { output.Write(pair.Value); output.Write(' '); } return; } } if (val != 0) { output.Write("flag({0:x4})", val); output.Write(' '); } } sealed class EnumNameCollection<T> : IEnumerable<KeyValuePair<long, string>> where T : struct { List<KeyValuePair<long, string>> names = new List<KeyValuePair<long, string>>(); public void Add(T flag, string name) { this.names.Add(new KeyValuePair<long, string>(Convert.ToInt64(flag), name)); } public IEnumerator<KeyValuePair<long, string>> GetEnumerator() { return names.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return names.GetEnumerator(); } } #endregion public void DisassembleNamespace(string nameSpace, PEFile module, IEnumerable<TypeDefinitionHandle> types) { if (!string.IsNullOrEmpty(nameSpace)) { output.Write(".namespace " + DisassemblerHelpers.Escape(nameSpace)); OpenBlock(false); } bool oldIsInType = isInType; isInType = true; foreach (var td in types) { cancellationToken.ThrowIfCancellationRequested(); DisassembleType(module, td); output.WriteLine(); } if (!string.IsNullOrEmpty(nameSpace)) { CloseBlock(); isInType = oldIsInType; } } public void WriteAssemblyHeader(PEFile module) { var metadata = module.Metadata; if (!metadata.IsAssembly) return; output.Write(".assembly "); var asm = metadata.GetAssemblyDefinition(); if ((asm.Flags & AssemblyFlags.WindowsRuntime) == AssemblyFlags.WindowsRuntime) output.Write("windowsruntime "); output.Write(DisassemblerHelpers.Escape(metadata.GetString(asm.Name))); OpenBlock(false); WriteAttributes(module, asm.GetCustomAttributes()); WriteSecurityDeclarations(module, asm.GetDeclarativeSecurityAttributes()); if (!asm.PublicKey.IsNil) { output.Write(".publickey = "); WriteBlob(asm.PublicKey, metadata); output.WriteLine(); } if (asm.HashAlgorithm != AssemblyHashAlgorithm.None) { output.Write(".hash algorithm 0x{0:x8}", (int)asm.HashAlgorithm); if (asm.HashAlgorithm == AssemblyHashAlgorithm.Sha1) output.Write(" // SHA1"); output.WriteLine(); } Version v = asm.Version; if (v != null) { output.WriteLine(".ver {0}:{1}:{2}:{3}", v.Major, v.Minor, v.Build, v.Revision); } CloseBlock(); } public void WriteAssemblyReferences(MetadataReader metadata) { foreach (var m in metadata.GetModuleReferences()) { var mref = metadata.GetModuleReference(m); output.WriteLine(".module extern {0}", DisassemblerHelpers.Escape(metadata.GetString(mref.Name))); } foreach (var a in metadata.AssemblyReferences) { var aref = metadata.GetAssemblyReference(a); output.Write(".assembly extern "); if ((aref.Flags & AssemblyFlags.WindowsRuntime) == AssemblyFlags.WindowsRuntime) output.Write("windowsruntime "); output.Write(DisassemblerHelpers.Escape(metadata.GetString(aref.Name))); OpenBlock(false); if (!aref.PublicKeyOrToken.IsNil) { output.Write(".publickeytoken = "); WriteBlob(aref.PublicKeyOrToken, metadata); output.WriteLine(); } if (aref.Version != null) { output.WriteLine(".ver {0}:{1}:{2}:{3}", aref.Version.Major, aref.Version.Minor, aref.Version.Build, aref.Version.Revision); } CloseBlock(); } } public void WriteModuleHeader(PEFile module, bool skipMVID = false) { var metadata = module.Metadata; void WriteExportedType(ExportedType exportedType) { if (!exportedType.Namespace.IsNil) { output.Write(DisassemblerHelpers.Escape(metadata.GetString(exportedType.Namespace))); output.Write('.'); } output.Write(DisassemblerHelpers.Escape(metadata.GetString(exportedType.Name))); } foreach (var et in metadata.ExportedTypes) { var exportedType = metadata.GetExportedType(et); output.Write(".class extern "); if (exportedType.IsForwarder) output.Write("forwarder "); WriteExportedType(exportedType); OpenBlock(false); switch (exportedType.Implementation.Kind) { case HandleKind.AssemblyFile: var file = metadata.GetAssemblyFile((AssemblyFileHandle)exportedType.Implementation); output.WriteLine(".file {0}", metadata.GetString(file.Name)); int typeDefId = exportedType.GetTypeDefinitionId(); if (typeDefId != 0) output.WriteLine(".class 0x{0:x8}", typeDefId); break; case HandleKind.ExportedType: output.Write(".class extern "); var declaringType = metadata.GetExportedType((ExportedTypeHandle)exportedType.Implementation); while (true) { WriteExportedType(declaringType); if (declaringType.Implementation.Kind == HandleKind.ExportedType) { declaringType = metadata.GetExportedType((ExportedTypeHandle)declaringType.Implementation); } else { break; } } output.WriteLine(); break; case HandleKind.AssemblyReference: output.Write(".assembly extern "); var reference = metadata.GetAssemblyReference((AssemblyReferenceHandle)exportedType.Implementation); output.Write(DisassemblerHelpers.Escape(metadata.GetString(reference.Name))); output.WriteLine(); break; default: throw new BadImageFormatException("Implementation must either be an index into the File, ExportedType or AssemblyRef table."); } CloseBlock(); } var moduleDefinition = metadata.GetModuleDefinition(); output.WriteLine(".module {0}", metadata.GetString(moduleDefinition.Name)); if (!skipMVID) { output.WriteLine("// MVID: {0}", metadata.GetGuid(moduleDefinition.Mvid).ToString("B").ToUpperInvariant()); } var headers = module.Reader.PEHeaders; output.WriteLine(".imagebase 0x{0:x8}", headers.PEHeader.ImageBase); output.WriteLine(".file alignment 0x{0:x8}", headers.PEHeader.FileAlignment); output.WriteLine(".stackreserve 0x{0:x8}", headers.PEHeader.SizeOfStackReserve); output.WriteLine(".subsystem 0x{0:x} // {1}", headers.PEHeader.Subsystem, headers.PEHeader.Subsystem.ToString()); output.WriteLine(".corflags 0x{0:x} // {1}", headers.CorHeader.Flags, headers.CorHeader.Flags.ToString()); WriteAttributes(module, metadata.GetCustomAttributes(EntityHandle.ModuleDefinition)); } public void WriteModuleContents(PEFile module) { foreach (var handle in Process(module, module.Metadata.GetTopLevelTypeDefinitions().ToArray())) { DisassembleType(module, handle); output.WriteLine(); } } } }
ILSpy/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs", "repo_id": "ILSpy", "token_count": 26329 }
229
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <PackageId>ICSharpCode.Decompiler</PackageId> <PackageVersion>8.0.0.0-noversion</PackageVersion> <Title>ILSpy Decompiler Engine</Title> <Authors>ILSpy Contributors</Authors> <PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageProjectUrl>https://github.com/icsharpcode/ILSpy/</PackageProjectUrl> <Description>ICSharpCode.Decompiler is the decompiler engine used in ILSpy.</Description> <PackageReadmeFile>PackageReadme.md</PackageReadmeFile> <Company>ic#code</Company> <Product>ILSpy</Product> <RepositoryType>git</RepositoryType> <RepositoryUrl>https://github.com/icsharpcode/ILSpy.git</RepositoryUrl> <PackageIcon>DecompilerNuGetPackageIcon.png</PackageIcon> <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> <Copyright>Copyright 2011-$([System.DateTime]::Now.Year) AlphaSierraPapa</Copyright> <PackageTags>C# Decompiler ILSpy</PackageTags> <NeutralLanguage>en-US</NeutralLanguage> <GenerateAssemblyVersionAttribute>False</GenerateAssemblyVersionAttribute> <GenerateAssemblyFileVersionAttribute>False</GenerateAssemblyFileVersionAttribute> <GenerateAssemblyInformationalVersionAttribute>False</GenerateAssemblyInformationalVersionAttribute> <EnableDefaultItems>false</EnableDefaultItems> <LangVersion>11</LangVersion> <GenerateDocumentationFile>true</GenerateDocumentationFile> <SignAssembly>True</SignAssembly> <AssemblyOriginatorKeyFile>ICSharpCode.Decompiler.snk</AssemblyOriginatorKeyFile> <NoWarn>1701;1702;1591;1573</NoWarn> <WarningsAsErrors>nullable</WarningsAsErrors> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <DebugType>embedded</DebugType> <DebugSymbols>true</DebugSymbols> <EmbedUntrackedSources>true</EmbedUntrackedSources> <PublishRepositoryUrl>true</PublishRepositoryUrl> <CodeAnalysisRuleSet>ICSharpCode.Decompiler.ruleset</CodeAnalysisRuleSet> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <None Include="PackageReadme.md" Pack="true" PackagePath="\" /> <None Include="DecompilerNuGetPackageIcon.png" Pack="true" PackagePath="\" /> </ItemGroup> <PropertyGroup Condition="'$(Configuration)' == 'Debug'"> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> <DefineConstants>$(DefineConstants);STEP</DefineConstants> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' == 'Release'"> </PropertyGroup> <PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'"> <ContinuousIntegrationBuild>true</ContinuousIntegrationBuild> </PropertyGroup> <!-- Inject ILSpyUpdateAssemblyInfo as dependency of the GetPackageVersion target so Pack uses the generated version when evaluating project references. --> <PropertyGroup> <GetPackageVersionDependsOn> ILSpyUpdateAssemblyInfo; $(GetPackageVersionDependsOn) </GetPackageVersionDependsOn> </PropertyGroup> <PropertyGroup> <ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="6.0.0" /> <PackageReference Include="System.Reflection.Metadata" Version="6.0.0" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> </ItemGroup> <ItemGroup> <PackageReference Include="TunnelVisionLabs.ReferenceAssemblyAnnotator" Version="1.0.0-alpha.160" PrivateAssets="all" /> <!-- Specifies the version of Microsoft.NETCore.App.Ref to obtain nullability information from. --> <PackageDownload Include="Microsoft.NETCore.App.Ref" Version="[8.0.0]" /> </ItemGroup> <ItemGroup> <Compile Include="CSharp\Annotations.cs" /> <Compile Include="CSharp\CallBuilder.cs" /> <Compile Include="CSharp\CSharpLanguageVersion.cs" /> <Compile Include="CSharp\Syntax\Expressions\RecursivePatternExpression.cs" /> <Compile Include="DecompilationProgress.cs" /> <Compile Include="Disassembler\IEntityProcessor.cs" /> <Compile Include="Disassembler\SortByNameProcessor.cs" /> <Compile Include="IL\ApplyPdbLocalTypeInfoTypeVisitor.cs" /> <Compile Include="Metadata\ModuleReferenceMetadata.cs" /> <Compile Include="NRTAttributes.cs" /> <Compile Include="PartialTypeInfo.cs" /> <Compile Include="CSharp\ProjectDecompiler\IProjectFileWriter.cs" /> <Compile Include="CSharp\OutputVisitor\GenericGrammarAmbiguityVisitor.cs" /> <Compile Include="CSharp\ProjectDecompiler\IProjectInfoProvider.cs" /> <Compile Include="CSharp\ProjectDecompiler\ProjectFileWriterSdkStyle.cs" /> <Compile Include="CSharp\ProjectDecompiler\ProjectFileWriterDefault.cs" /> <Compile Include="CSharp\RecordDecompiler.cs" /> <Compile Include="CSharp\RequiredNamespaceCollector.cs" /> <Compile Include="CSharp\SequencePointBuilder.cs" /> <Compile Include="CSharp\ProjectDecompiler\TargetFramework.cs" /> <Compile Include="CSharp\ProjectDecompiler\TargetServices.cs" /> <Compile Include="CSharp\Syntax\Expressions\DeclarationExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\SwitchExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\WithInitializerExpression.cs" /> <Compile Include="CSharp\Syntax\FunctionPointerAstType.cs" /> <Compile Include="CSharp\Syntax\InvocationAstType.cs" /> <Compile Include="CSharp\Syntax\VariableDesignation.cs" /> <Compile Include="Humanizer\Vocabularies.cs" /> <Compile Include="Humanizer\Vocabulary.cs" /> <Compile Include="IL\ControlFlow\RemoveRedundantReturn.cs" /> <Compile Include="IL\Transforms\DeconstructionTransform.cs" /> <Compile Include="IL\Transforms\FixLoneIsInst.cs" /> <Compile Include="IL\Instructions\DeconstructInstruction.cs" /> <Compile Include="IL\Instructions\DeconstructResultInstruction.cs" /> <Compile Include="IL\Instructions\MatchInstruction.cs" /> <Compile Include="IL\Transforms\IndexRangeTransform.cs" /> <Compile Include="CSharp\TranslatedStatement.cs" /> <Compile Include="DebugInfo\KnownGuids.cs" /> <Compile Include="Disassembler\DisassemblerSignatureTypeProvider.cs" /> <Compile Include="Documentation\XmlDocumentationElement.cs" /> <Compile Include="IL\ControlFlow\AwaitInFinallyTransform.cs" /> <Compile Include="IL\Transforms\InterpolatedStringTransform.cs" /> <Compile Include="IL\Transforms\IntroduceNativeIntTypeOnLocals.cs" /> <Compile Include="IL\Transforms\LdLocaDupInitObjTransform.cs" /> <Compile Include="IL\Transforms\ParameterNullCheckTransform.cs" /> <Compile Include="IL\Transforms\PatternMatchingTransform.cs" /> <Compile Include="IL\Transforms\RemoveInfeasiblePathTransform.cs" /> <Compile Include="Instrumentation\DecompilerEventSource.cs" /> <Compile Include="Metadata\FindTypeDecoder.cs" /> <Compile Include="Metadata\FullTypeNameSignatureDecoder.cs" /> <Compile Include="Metadata\MetadataGenericContext.cs" /> <Compile Include="Metadata\ReferenceLoadInfo.cs" /> <Compile Include="Properties\DecompilerVersionInfo.cs" /> <Compile Include="TypeSystem\ITypeDefinitionOrUnknown.cs" /> <Compile Include="Util\BitOperations.cs" /> <Compile Include="Util\Index.cs" /> <None Include="Properties\DecompilerVersionInfo.template.cs" /> <Compile Include="Semantics\OutVarResolveResult.cs" /> <Compile Include="SingleFileBundle.cs" /> <Compile Include="Solution\ProjectId.cs" /> <Compile Include="Solution\ProjectItem.cs" /> <Compile Include="Solution\SolutionCreator.cs" /> <Compile Include="CSharp\Syntax\AstNode.cs" /> <Compile Include="CSharp\Syntax\AstNodeCollection.cs" /> <Compile Include="CSharp\Syntax\AstType.cs" /> <Compile Include="CSharp\Syntax\ComposedType.cs" /> <Compile Include="CSharp\Syntax\CSharpModifierToken.cs" /> <Compile Include="CSharp\Syntax\CSharpTokenNode.cs" /> <Compile Include="CSharp\Syntax\DepthFirstAstVisitor.cs" /> <Compile Include="CSharp\Syntax\DocumentationReference.cs" /> <Compile Include="CSharp\Syntax\Expressions\AnonymousMethodExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\AnonymousTypeCreateExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\ArrayCreateExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\ArrayInitializerExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\AsExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\AssignmentExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\BaseReferenceExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\BinaryOperatorExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\CastExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\CheckedExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\ConditionalExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\DefaultValueExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\DirectionExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\ErrorExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\Expression.cs" /> <Compile Include="CSharp\Syntax\Expressions\IdentifierExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\IndexerExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\InterpolatedStringExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\InvocationExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\IsExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\LambdaExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\MemberReferenceExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\NamedArgumentExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\NamedExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\NullReferenceExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\ObjectCreateExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\OutVarDeclarationExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\ParenthesizedExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\PointerReferenceExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\PrimitiveExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\QueryExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\SizeOfExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\StackAllocExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\ThisReferenceExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\ThrowExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\TupleExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\TypeOfExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\TypeReferenceExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\UnaryOperatorExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\UncheckedExpression.cs" /> <Compile Include="CSharp\Syntax\Expressions\UndocumentedExpression.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\Attribute.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\AttributeSection.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\Comment.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\Constraint.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\DelegateDeclaration.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\ExternAliasDeclaration.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\NamespaceDeclaration.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\PreProcessorDirective.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\TypeDeclaration.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\TypeParameterDeclaration.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\UsingAliasDeclaration.cs" /> <Compile Include="CSharp\Syntax\GeneralScope\UsingDeclaration.cs" /> <Compile Include="CSharp\Syntax\IAstVisitor.cs" /> <Compile Include="CSharp\Syntax\Identifier.cs" /> <Compile Include="CSharp\Syntax\IdentifierExpressionBackreference.cs" /> <Compile Include="CSharp\Syntax\MemberType.cs" /> <Compile Include="CSharp\Syntax\Modifiers.cs" /> <Compile Include="CSharp\Syntax\NodeType.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\AnyNode.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\AnyNodeOrNull.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\Backreference.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\BacktrackingInfo.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\Choice.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\INode.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\Match.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\NamedNode.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\OptionalNode.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\Pattern.cs" /> <Compile Include="CSharp\Syntax\PatternMatching\Repeat.cs" /> <Compile Include="CSharp\Syntax\PrimitiveType.cs" /> <Compile Include="CSharp\Syntax\Role.cs" /> <Compile Include="CSharp\Syntax\Roles.cs" /> <Compile Include="CSharp\Syntax\SimpleType.cs" /> <Compile Include="CSharp\Syntax\Statements\BlockStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\BreakStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\CheckedStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\ContinueStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\DoWhileStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\EmptyStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\ExpressionStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\FixedStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\ForeachStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\ForStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\GotoStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\IfElseStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\LabelStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\LocalFunctionDeclarationStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\LockStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\ReturnStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\Statement.cs" /> <Compile Include="CSharp\Syntax\Statements\SwitchStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\ThrowStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\TryCatchStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\UncheckedStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\UnsafeStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\UsingStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\VariableDeclarationStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\WhileStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\YieldBreakStatement.cs" /> <Compile Include="CSharp\Syntax\Statements\YieldReturnStatement.cs" /> <Compile Include="CSharp\Syntax\SyntaxExtensions.cs" /> <Compile Include="CSharp\Syntax\SyntaxTree.cs" /> <Compile Include="CSharp\Syntax\TextLocation.cs" /> <Compile Include="CSharp\Syntax\TokenRole.cs" /> <Compile Include="CSharp\Syntax\TupleAstType.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\Accessor.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\ConstructorDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\DestructorDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\EntityDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\EnumMemberDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\EventDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\FieldDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\FixedFieldDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\FixedVariableInitializer.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\IndexerDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\MethodDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\OperatorDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\ParameterDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\PropertyDeclaration.cs" /> <Compile Include="CSharp\Syntax\TypeMembers\VariableInitializer.cs" /> <Compile Include="CSharp\Syntax\TypeSystemAstBuilder.cs" /> <Compile Include="CSharp\OutputVisitor\CSharpAmbience.cs" /> <Compile Include="CSharp\OutputVisitor\CSharpFormattingOptions.cs" /> <Compile Include="CSharp\OutputVisitor\CSharpOutputVisitor.cs" /> <Compile Include="CSharp\OutputVisitor\FormattingOptionsFactory.cs" /> <Compile Include="CSharp\OutputVisitor\InsertMissingTokensDecorator.cs" /> <Compile Include="CSharp\OutputVisitor\InsertParenthesesVisitor.cs" /> <Compile Include="CSharp\OutputVisitor\InsertRequiredSpacesDecorator.cs" /> <Compile Include="CSharp\OutputVisitor\InsertSpecialsDecorator.cs" /> <Compile Include="CSharp\OutputVisitor\ITokenWriter.cs" /> <Compile Include="CSharp\OutputVisitor\TextWriterTokenWriter.cs" /> <Compile Include="CSharp\Resolver\AliasNamespaceResolveResult.cs" /> <Compile Include="CSharp\Resolver\AliasTypeResolveResult.cs" /> <Compile Include="CSharp\Resolver\AwaitResolveResult.cs" /> <Compile Include="CSharp\Resolver\CSharpConversions.cs" /> <Compile Include="CSharp\Resolver\CSharpInvocationResolveResult.cs" /> <Compile Include="CSharp\Resolver\CSharpOperators.cs" /> <Compile Include="CSharp\Resolver\CSharpResolver.cs" /> <Compile Include="CSharp\Resolver\DynamicInvocationResolveResult.cs" /> <Compile Include="CSharp\Resolver\DynamicMemberResolveResult.cs" /> <Compile Include="CSharp\Resolver\LambdaResolveResult.cs" /> <Compile Include="CSharp\Resolver\Log.cs" /> <Compile Include="CSharp\Resolver\MemberLookup.cs" /> <Compile Include="CSharp\Resolver\MethodGroupResolveResult.cs" /> <Compile Include="CSharp\Resolver\NameLookupMode.cs" /> <Compile Include="CSharp\Resolver\OverloadResolution.cs" /> <Compile Include="CSharp\Resolver\OverloadResolutionErrors.cs" /> <Compile Include="IL\Transforms\FixRemainingIncrements.cs" /> <Compile Include="IL\Transforms\ILExtraction.cs" /> <Compile Include="TypeSystem\FunctionPointerType.cs" /> <Compile Include="TypeSystem\Implementation\LocalFunctionMethod.cs" /> <Compile Include="CSharp\Resolver\TypeInference.cs" /> <Compile Include="CSharp\Transforms\CombineQueryExpressions.cs" /> <Compile Include="CSharp\Transforms\FlattenSwitchBlocks.cs" /> <Compile Include="CSharp\Transforms\IntroduceExtensionMethods.cs" /> <Compile Include="CSharp\Transforms\IntroduceQueryExpressions.cs" /> <Compile Include="CSharp\Transforms\NormalizeBlockStatements.cs" /> <Compile Include="CSharp\Transforms\PrettifyAssignments.cs" /> <Compile Include="CSharp\Transforms\RemoveCLSCompliantAttribute.cs" /> <Compile Include="CSharp\TranslationContext.cs" /> <Compile Include="CSharp\TypeSystem\AliasNamespaceReference.cs" /> <Compile Include="CSharp\TypeSystem\CSharpTypeResolveContext.cs" /> <Compile Include="CSharp\TypeSystem\MemberTypeOrNamespaceReference.cs" /> <Compile Include="CSharp\TypeSystem\ResolvedUsingScope.cs" /> <Compile Include="CSharp\TypeSystem\SimpleTypeOrNamespaceReference.cs" /> <Compile Include="CSharp\TypeSystem\TypeOrNamespaceReference.cs" /> <Compile Include="CSharp\TypeSystem\UsingScope.cs" /> <Compile Include="DebugInfo\AsyncDebugInfo.cs" /> <Compile Include="DebugInfo\ImportScopeInfo.cs" /> <Compile Include="DebugInfo\DebugInfoGenerator.cs" /> <Compile Include="DecompilerException.cs" /> <Compile Include="DecompilerSettings.cs" /> <Compile Include="CSharp\Transforms\ContextTrackingVisitor.cs" /> <Compile Include="CSharp\Transforms\DecimalConstantTransform.cs" /> <Compile Include="CSharp\Transforms\DeclareVariables.cs" /> <Compile Include="CSharp\Transforms\EscapeInvalidIdentifiers.cs" /> <Compile Include="CSharp\Transforms\FixNameCollisions.cs" /> <Compile Include="CSharp\Transforms\IntroduceUsingDeclarations.cs" /> <Compile Include="CSharp\Transforms\PatternStatementTransform.cs" /> <Compile Include="CSharp\Transforms\TransformContext.cs" /> <Compile Include="CSharp\TranslatedExpression.cs" /> <Compile Include="CSharp\CSharpDecompiler.cs" /> <Compile Include="CSharp\ExpressionBuilder.cs" /> <Compile Include="CSharp\StatementBuilder.cs" /> <Compile Include="CSharp\Transforms\AddCheckedBlocks.cs" /> <Compile Include="CSharp\Transforms\TransformFieldAndConstructorInitializers.cs" /> <Compile Include="CSharp\Transforms\CustomPatterns.cs" /> <Compile Include="CSharp\Transforms\IAstTransform.cs" /> <Compile Include="CSharp\Transforms\IntroduceUnsafeModifier.cs" /> <Compile Include="CSharp\Transforms\ReplaceMethodCallsWithOperators.cs" /> <Compile Include="CSharp\ProjectDecompiler\WholeProjectDecompiler.cs" /> <Compile Include="CSharp\Transforms\AddXmlDocumentationTransform.cs" /> <Compile Include="DecompileRun.cs" /> <Compile Include="Disassembler\ILParser.cs" /> <Compile Include="IL\ILInstructionExtensions.cs" /> <Compile Include="IL\Transforms\CombineExitsTransform.cs" /> <Compile Include="IL\Transforms\DynamicIsEventAssignmentTransform.cs" /> <Compile Include="IL\Transforms\ReduceNestingTransform.cs" /> <Compile Include="IL\Transforms\LocalFunctionDecompiler.cs" /> <Compile Include="IL\Transforms\TransformDisplayClassUsage.cs" /> <Compile Include="IL\Transforms\UserDefinedLogicTransform.cs" /> <Compile Include="Metadata\AssemblyReferences.cs" /> <Compile Include="Metadata\ExportedTypeMetadata.cs" /> <Compile Include="Metadata\MemberReferenceMetadata.cs" /> <Compile Include="Metadata\TypeReferenceMetadata.cs" /> <Compile Include="Metadata\CodeMappingInfo.cs" /> <Compile Include="Metadata\EnumUnderlyingTypeResolveException.cs" /> <Compile Include="Metadata\MetadataTokenHelpers.cs" /> <Compile Include="Disassembler\OpCodeInfo.cs" /> <Compile Include="Documentation\GetPotentiallyNestedClassTypeReference.cs" /> <Compile Include="Documentation\IdStringMemberReference.cs" /> <Compile Include="Documentation\IdStringProvider.cs" /> <Compile Include="Documentation\XmlDocLoader.cs" /> <Compile Include="Documentation\XmlDocumentationProvider.cs" /> <Compile Include="IL\ControlFlow\AsyncAwaitDecompiler.cs" /> <Compile Include="IL\ControlFlow\AwaitInCatchTransform.cs" /> <Compile Include="IL\ControlFlow\YieldReturnDecompiler.cs" /> <Compile Include="Metadata\CustomAttributeDecoder.cs" /> <Compile Include="Metadata\Resource.cs" /> <Compile Include="Metadata\DotNetCorePathFinder.cs" /> <Compile Include="Metadata\DotNetCorePathFinderExtensions.cs" /> <Compile Include="Metadata\LightJson\JsonArray.cs" /> <Compile Include="Metadata\LightJson\JsonObject.cs" /> <Compile Include="Metadata\LightJson\JsonValue.cs" /> <Compile Include="Metadata\LightJson\JsonValueType.cs" /> <Compile Include="Metadata\LightJson\Serialization\JsonParseException.cs" /> <Compile Include="Metadata\LightJson\Serialization\JsonReader.cs" /> <Compile Include="Metadata\LightJson\Serialization\TextPosition.cs" /> <Compile Include="Metadata\LightJson\Serialization\TextScanner.cs" /> <Compile Include="Metadata\MethodSemanticsLookup.cs" /> <Compile Include="Metadata\OperandType.cs" /> <Compile Include="Metadata\PEFile.cs" /> <Compile Include="Metadata\SignatureBlobComparer.cs" /> <Compile Include="Metadata\UniversalAssemblyResolver.cs" /> <Compile Include="Metadata\UnresolvedAssemblyNameReference.cs" /> <Compile Include="IL\Instructions\DynamicInstructions.cs" /> <Compile Include="IL\PointerArithmeticOffset.cs" /> <Compile Include="IL\ILAstWritingOptions.cs" /> <Compile Include="IL\Instructions\LdFlda.cs" /> <Compile Include="IL\Instructions\NullableInstructions.cs" /> <Compile Include="IL\Instructions\StLoc.cs" /> <Compile Include="DebugInfo\SequencePoint.cs" /> <Compile Include="IL\Instructions\CallIndirect.cs" /> <Compile Include="IL\Instructions\DefaultValue.cs" /> <Compile Include="IL\Transforms\DynamicCallSiteTransform.cs" /> <Compile Include="IL\Transforms\EarlyExpressionTransforms.cs" /> <Compile Include="IL\Instructions\ExpressionTreeCast.cs" /> <Compile Include="IL\Transforms\HighLevelLoopTransform.cs" /> <Compile Include="IL\Transforms\NamedArgumentTransform.cs" /> <Compile Include="IL\Transforms\IntroduceDynamicTypeOnLocals.cs" /> <Compile Include="IL\Transforms\IntroduceRefReadOnlyModifierOnLocals.cs" /> <Compile Include="IL\Transforms\NullPropagationTransform.cs" /> <Compile Include="IL\Transforms\ProxyCallReplacer.cs" /> <Compile Include="IL\Instructions\StringToInt.cs" /> <Compile Include="IL\Instructions\UsingInstruction.cs" /> <Compile Include="IL\Transforms\InlineReturnTransform.cs" /> <Compile Include="IL\Transforms\SwitchOnNullableTransform.cs" /> <Compile Include="IL\Transforms\SwitchOnStringTransform.cs" /> <Compile Include="IL\Transforms\TransformExpressionTrees.cs" /> <Compile Include="IL\Transforms\TupleTransform.cs" /> <Compile Include="IL\Transforms\UsingTransform.cs" /> <Compile Include="IL\ControlFlow\ControlFlowGraph.cs" /> <Compile Include="IL\ControlFlow\StateRangeAnalysis.cs" /> <Compile Include="IL\ControlFlow\SymbolicExecution.cs" /> <Compile Include="IL\Instructions\Await.cs" /> <Compile Include="IL\Instructions\ILVariableCollection.cs" /> <Compile Include="IL\Instructions\LockInstruction.cs" /> <Compile Include="IL\Instructions\NullCoalescingInstruction.cs" /> <Compile Include="IL\Instructions\LogicInstructions.cs" /> <Compile Include="IL\Patterns\AnyNode.cs" /> <Compile Include="IL\Transforms\AssignVariableNames.cs" /> <Compile Include="IL\Transforms\DetectCatchWhenConditionBlocks.cs" /> <Compile Include="IL\Transforms\LockTransform.cs" /> <Compile Include="IL\Transforms\NullableLiftingTransform.cs" /> <Compile Include="IL\Transforms\NullCoalescingTransform.cs" /> <Compile Include="IL\Transforms\StatementTransform.cs" /> <Compile Include="IL\Transforms\TransformCollectionAndObjectInitializers.cs" /> <Compile Include="Output\TextTokenWriter.cs" /> <Compile Include="DebugInfo\IDebugInfoProvider.cs" /> <Compile Include="DebugInfo\PortablePdbWriter.cs" /> <Compile Include="Semantics\InterpolatedStringResolveResult.cs" /> <Compile Include="SRMExtensions.cs" /> <Compile Include="SRMHacks.cs" /> <Compile Include="TypeSystem\ApplyAttributeTypeVisitor.cs" /> <Compile Include="TypeSystem\GenericContext.cs" /> <Compile Include="TypeSystem\Implementation\AttributeListBuilder.cs" /> <Compile Include="TypeSystem\Implementation\CustomAttribute.cs" /> <Compile Include="TypeSystem\Implementation\DecimalConstantHelper.cs" /> <Compile Include="TypeSystem\Implementation\DecoratedType.cs" /> <Compile Include="TypeSystem\Implementation\DefaultTypeParameter.cs" /> <Compile Include="TypeSystem\Implementation\FakeMember.cs" /> <Compile Include="TypeSystem\Implementation\KnownAttributes.cs" /> <Compile Include="TypeSystem\Implementation\MetadataField.cs" /> <Compile Include="TypeSystem\Implementation\MetadataMethod.cs" /> <Compile Include="TypeSystem\Implementation\MetadataNamespace.cs" /> <Compile Include="TypeSystem\Implementation\MetadataParameter.cs" /> <Compile Include="TypeSystem\Implementation\MetadataEvent.cs" /> <Compile Include="TypeSystem\Implementation\MetadataProperty.cs" /> <Compile Include="TypeSystem\Implementation\MetadataTypeDefinition.cs" /> <Compile Include="TypeSystem\Implementation\MetadataTypeParameter.cs" /> <Compile Include="TypeSystem\Implementation\SpecializedParameter.cs" /> <Compile Include="TypeSystem\Implementation\SyntheticRangeIndexer.cs" /> <Compile Include="TypeSystem\Implementation\ThreeState.cs" /> <Compile Include="TypeSystem\MetadataModule.cs" /> <Compile Include="TypeSystem\ModifiedType.cs" /> <Compile Include="TypeSystem\Implementation\PinnedType.cs" /> <Compile Include="Metadata\MetadataExtensions.cs" /> <Compile Include="Semantics\ThrowResolveResult.cs" /> <Compile Include="Semantics\TupleResolveResult.cs" /> <Compile Include="TypeSystem\NormalizeTypeVisitor.cs" /> <Compile Include="TypeSystem\Nullability.cs" /> <Compile Include="TypeSystem\Implementation\NullabilityAnnotatedType.cs" /> <Compile Include="TypeSystem\TupleType.cs" /> <Compile Include="TypeSystem\TypeProvider.cs" /> <Compile Include="Util\FileUtility.cs" /> <Compile Include="Util\GraphVizGraph.cs" /> <Compile Include="Util\KeyComparer.cs" /> <Compile Include="Util\LongDict.cs" /> <Compile Include="Util\ResourcesFile.cs" /> <Compile Include="Util\ResXResourceWriter.cs" /> <Compile Include="Util\UnicodeNewline.cs" /> <Compile Include="FlowAnalysis\ControlFlowNode.cs" /> <Compile Include="FlowAnalysis\DataFlowVisitor.cs" /> <Compile Include="FlowAnalysis\DefiniteAssignmentVisitor.cs" /> <Compile Include="FlowAnalysis\Dominance.cs" /> <Compile Include="FlowAnalysis\ReachingDefinitionsVisitor.cs" /> <Compile Include="CSharp\Syntax\IAnnotatable.cs" /> <Compile Include="IL\ControlFlow\ConditionDetection.cs" /> <Compile Include="IL\ControlFlow\ControlFlowSimplification.cs" /> <Compile Include="IL\ControlFlow\DetectPinnedRegions.cs" /> <Compile Include="IL\ControlFlow\ExitPoints.cs" /> <Compile Include="IL\ControlFlow\LoopDetection.cs" /> <Compile Include="IL\ControlFlow\SwitchAnalysis.cs" /> <Compile Include="IL\ControlFlow\SwitchDetection.cs" /> <Compile Include="IL\Instructions.cs"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Instructions.tt</DependentUpon> </Compile> <Compile Include="IL\Instructions\Comp.cs" /> <Compile Include="IL\Instructions\BinaryNumericInstruction.cs" /> <Compile Include="IL\Instructions\Block.cs" /> <Compile Include="IL\Instructions\BlockContainer.cs" /> <Compile Include="IL\Instructions\Branch.cs" /> <Compile Include="IL\Instructions\CallInstruction.cs" /> <Compile Include="IL\Instructions\CompoundAssignmentInstruction.cs" /> <Compile Include="IL\Instructions\Conv.cs" /> <Compile Include="IL\Instructions\IfInstruction.cs" /> <Compile Include="IL\Instructions\ILFunction.cs" /> <Compile Include="IL\Instructions\ILInstruction.cs" /> <Compile Include="IL\Instructions\InstructionCollection.cs" /> <Compile Include="IL\Instructions\LdLen.cs" /> <Compile Include="IL\Instructions\Leave.cs" /> <Compile Include="IL\Instructions\MemoryInstructions.cs" /> <Compile Include="IL\Instructions\PatternMatching.cs" /> <Compile Include="IL\Instructions\SimpleInstruction.cs" /> <Compile Include="IL\Instructions\SwitchInstruction.cs" /> <Compile Include="IL\Instructions\TryInstruction.cs" /> <Compile Include="IL\Instructions\UnaryInstruction.cs" /> <Compile Include="IL\Patterns\ListMatch.cs" /> <Compile Include="IL\Patterns\Match.cs" /> <Compile Include="IL\SlotInfo.cs" /> <Compile Include="IL\Transforms\BlockTransform.cs" /> <Compile Include="IL\Transforms\CachedDelegateInitialization.cs" /> <Compile Include="IL\Transforms\CopyPropagation.cs" /> <Compile Include="IL\Transforms\IILTransform.cs" /> <Compile Include="IL\Transforms\ILInlining.cs" /> <Compile Include="IL\Transforms\ExpressionTransforms.cs" /> <Compile Include="IL\Transforms\DelegateConstruction.cs" /> <Compile Include="IL\Transforms\RemoveDeadVariableInit.cs" /> <Compile Include="IL\Transforms\SplitVariables.cs" /> <Compile Include="IL\Transforms\Stepper.cs" /> <Compile Include="IL\Transforms\TransformArrayInitializers.cs" /> <Compile Include="Disassembler\DisassemblerHelpers.cs" /> <Compile Include="Disassembler\ILStructure.cs" /> <Compile Include="Disassembler\MethodBodyDisassembler.cs" /> <Compile Include="Disassembler\ReflectionDisassembler.cs" /> <Compile Include="IL\SemanticHelper.cs" /> <Compile Include="IL\BlockBuilder.cs" /> <Compile Include="Metadata\ILOpCodes.cs"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>ILOpCodes.tt</DependentUpon> </Compile> <Compile Include="IL\ILReader.cs" /> <Compile Include="IL\ILTypeExtensions.cs" /> <Compile Include="IL\ILVariable.cs" /> <Compile Include="IL\InstructionFlags.cs" /> <Compile Include="IL\InstructionOutputExtensions.cs" /> <Compile Include="IL\PrimitiveType.cs" /> <Compile Include="IL\StackType.cs" /> <Compile Include="IL\Transforms\TransformAssignment.cs" /> <Compile Include="NRExtensions.cs" /> <Compile Include="Output\ITextOutput.cs" /> <Compile Include="Output\PlainTextOutput.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Output\TextOutputWriter.cs" /> <Compile Include="Semantics\AmbiguousResolveResult.cs" /> <Compile Include="Semantics\ArrayAccessResolveResult.cs" /> <Compile Include="Semantics\ArrayCreateResolveResult.cs" /> <Compile Include="Semantics\ByReferenceResolveResult.cs" /> <Compile Include="Semantics\ConstantResolveResult.cs" /> <Compile Include="Semantics\Conversion.cs" /> <Compile Include="Semantics\ConversionResolveResult.cs" /> <Compile Include="Semantics\ErrorResolveResult.cs" /> <Compile Include="Semantics\ForEachResolveResult.cs" /> <Compile Include="Semantics\InitializedObjectResolveResult.cs" /> <Compile Include="Semantics\InvocationResolveResult.cs" /> <Compile Include="Semantics\LocalResolveResult.cs" /> <Compile Include="Semantics\MemberResolveResult.cs" /> <Compile Include="Semantics\NamedArgumentResolveResult.cs" /> <Compile Include="Semantics\NamespaceResolveResult.cs" /> <Compile Include="Semantics\OperatorResolveResult.cs" /> <Compile Include="Semantics\ResolveResult.cs" /> <Compile Include="Semantics\SizeOfResolveResult.cs" /> <Compile Include="Semantics\ThisResolveResult.cs" /> <Compile Include="Semantics\TypeIsResolveResult.cs" /> <Compile Include="Semantics\TypeOfResolveResult.cs" /> <Compile Include="Semantics\TypeResolveResult.cs" /> <Compile Include="Semantics\UnknownMemberResolveResult.cs" /> <Compile Include="TypeSystem\Accessibility.cs" /> <Compile Include="TypeSystem\ArrayType.cs" /> <Compile Include="TypeSystem\AssemblyQualifiedTypeName.cs" /> <Compile Include="TypeSystem\ByReferenceType.cs" /> <Compile Include="TypeSystem\ComHelper.cs" /> <Compile Include="TypeSystem\DecompilerTypeSystem.cs" /> <Compile Include="TypeSystem\FullTypeName.cs" /> <Compile Include="Output\IAmbience.cs" /> <Compile Include="TypeSystem\IAssembly.cs" /> <Compile Include="TypeSystem\IAttribute.cs" /> <Compile Include="TypeSystem\ICodeContext.cs" /> <Compile Include="TypeSystem\ICompilation.cs" /> <Compile Include="TypeSystem\IEntity.cs" /> <Compile Include="TypeSystem\IEvent.cs" /> <Compile Include="TypeSystem\IField.cs" /> <Compile Include="TypeSystem\IFreezable.cs" /> <Compile Include="TypeSystem\IInterningProvider.cs" /> <Compile Include="TypeSystem\IMember.cs" /> <Compile Include="TypeSystem\IMethod.cs" /> <Compile Include="TypeSystem\Implementation\AbstractFreezable.cs" /> <Compile Include="TypeSystem\Implementation\AbstractTypeParameter.cs" /> <Compile Include="TypeSystem\Implementation\AbstractType.cs" /> <Compile Include="TypeSystem\Implementation\BaseTypeCollector.cs" /> <Compile Include="TypeSystem\Implementation\DefaultAssemblyReference.cs" /> <Compile Include="TypeSystem\Implementation\DefaultAttribute.cs" /> <Compile Include="TypeSystem\Implementation\DefaultParameter.cs" /> <Compile Include="TypeSystem\Implementation\DefaultVariable.cs" /> <Compile Include="TypeSystem\Implementation\DummyTypeParameter.cs" /> <Compile Include="TypeSystem\Implementation\GetClassTypeReference.cs" /> <Compile Include="TypeSystem\Implementation\GetMembersHelper.cs" /> <Compile Include="TypeSystem\Implementation\KnownTypeCache.cs" /> <Compile Include="TypeSystem\Implementation\MergedNamespace.cs" /> <Compile Include="TypeSystem\Implementation\MinimalCorlib.cs" /> <Compile Include="TypeSystem\Implementation\NestedTypeReference.cs" /> <Compile Include="TypeSystem\Implementation\SimpleCompilation.cs" /> <Compile Include="TypeSystem\Implementation\SpecializedEvent.cs" /> <Compile Include="TypeSystem\Implementation\SpecializedField.cs" /> <Compile Include="TypeSystem\Implementation\SpecializedMember.cs" /> <Compile Include="TypeSystem\Implementation\SpecializedMethod.cs" /> <Compile Include="TypeSystem\Implementation\SpecializedProperty.cs" /> <Compile Include="TypeSystem\Implementation\TypeParameterReference.cs" /> <Compile Include="TypeSystem\Implementation\TypeWithElementType.cs" /> <Compile Include="TypeSystem\Implementation\UnknownType.cs" /> <Compile Include="TypeSystem\INamedElement.cs" /> <Compile Include="TypeSystem\INamespace.cs" /> <Compile Include="TypeSystem\InheritanceHelper.cs" /> <Compile Include="TypeSystem\IntersectionType.cs" /> <Compile Include="TypeSystem\IParameter.cs" /> <Compile Include="TypeSystem\IParameterizedMember.cs" /> <Compile Include="TypeSystem\IProperty.cs" /> <Compile Include="TypeSystem\ISupportsInterning.cs" /> <Compile Include="TypeSystem\ISymbol.cs" /> <Compile Include="TypeSystem\IType.cs" /> <Compile Include="TypeSystem\ITypeDefinition.cs" /> <Compile Include="TypeSystem\ITypeParameter.cs" /> <Compile Include="TypeSystem\ITypeReference.cs" /> <Compile Include="TypeSystem\IVariable.cs" /> <Compile Include="TypeSystem\KnownTypeReference.cs" /> <Compile Include="TypeSystem\NullableType.cs" /> <Compile Include="TypeSystem\ParameterizedType.cs" /> <Compile Include="TypeSystem\ParameterListComparer.cs" /> <Compile Include="TypeSystem\PointerType.cs" /> <Compile Include="TypeSystem\ReflectionHelper.cs" /> <Compile Include="TypeSystem\ReflectionNameParseException.cs" /> <Compile Include="TypeSystem\SimpleTypeResolveContext.cs" /> <Compile Include="TypeSystem\SpecialType.cs" /> <Compile Include="TypeSystem\TaskType.cs" /> <Compile Include="TypeSystem\TopLevelTypeName.cs" /> <Compile Include="TypeSystem\TypeKind.cs" /> <Compile Include="TypeSystem\TypeParameterSubstitution.cs" /> <Compile Include="TypeSystem\TypeSystemExtensions.cs" /> <Compile Include="TypeSystem\TypeUtils.cs" /> <Compile Include="TypeSystem\IDecompilerTypeSystem.cs" /> <Compile Include="TypeSystem\ReferenceResolvingException.cs" /> <Compile Include="TypeSystem\TypeVisitor.cs" /> <Compile Include="TypeSystem\VarArgInstanceMethod.cs" /> <Compile Include="Util\BusyManager.cs" /> <Compile Include="Util\CacheManager.cs" /> <Compile Include="Util\CallbackOnDispose.cs" /> <Compile Include="Util\CollectionExtensions.cs" /> <Compile Include="Util\BitSet.cs" /> <Compile Include="Util\CSharpPrimitiveCast.cs" /> <Compile Include="Util\EmptyList.cs" /> <Compile Include="Util\ExtensionMethods.cs" /> <Compile Include="Util\GraphTraversal.cs" /> <Compile Include="Util\Interval.cs" /> <Compile Include="Util\LazyInit.cs" /> <Compile Include="Util\LongSet.cs" /> <Compile Include="Util\MultiDictionary.cs" /> <Compile Include="Util\Platform.cs" /> <Compile Include="Util\ProjectedList.cs" /> <Compile Include="Util\ReferenceComparer.cs" /> <Compile Include="Util\TreeTraversal.cs" /> <Compile Include="Util\UnionFind.cs" /> <Compile Include="Util\Win32Resources.cs" /> <None Include="ICSharpCode.Decompiler.ruleset" /> <None Include="ICSharpCode.Decompiler.snk" /> <None Include="Metadata\ILOpCodes.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>ILOpCodes.cs</LastGenOutput> </None> <None Include="IL\Instructions.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>Instructions.cs</LastGenOutput> </None> </ItemGroup> <ItemGroup> <None Include="..\doc\Pattern Matching.html"> <Link>CSharp\Syntax\PatternMatching\Pattern Matching.html</Link> </None> <None Include="Humanizer\LICENSE" /> </ItemGroup> <ItemGroup> <Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" /> </ItemGroup> <ItemGroup> <UpdateAssemblyInfoStamp Include="obj\update-assemblyinfo-last-commit-hash.txt" /> </ItemGroup> <Target Name="ILSpyUpdateAssemblyInfo" BeforeTargets="BeforeBuild"> <PropertyGroup Condition=" '$(OS)' == 'Windows_NT' "> <UpdateAssemblyInfo>powershell -NoProfile -ExecutionPolicy Bypass -File BuildTools/update-assemblyinfo.ps1 $(Configuration)</UpdateAssemblyInfo> <GitRevParse>git rev-parse HEAD^^{commit}</GitRevParse> </PropertyGroup> <PropertyGroup Condition=" '$(OS)' != 'Windows_NT' "> <UpdateAssemblyInfo>pwsh -NoProfile -ExecutionPolicy Bypass -File BuildTools/update-assemblyinfo.ps1 $(Configuration)</UpdateAssemblyInfo> <GitRevParse>git rev-parse HEAD^{commit}</GitRevParse> </PropertyGroup> <ReadLinesFromFile ContinueOnError="true" File="@(UpdateAssemblyInfoStamp)"> <Output TaskParameter="Lines" PropertyName="LastCommitHash" /> </ReadLinesFromFile> <Exec ContinueOnError="true" WorkingDirectory=".." Command="$(GitRevParse)" ConsoleToMSBuild="true"> <Output TaskParameter="ConsoleOutput" PropertyName="CommitHash" /> </Exec> <Exec WorkingDirectory=".." Command="$(UpdateAssemblyInfo)" Timeout="60000" Condition="'$(CommitHash)'!='$(LastCommitHash)'" LogStandardErrorAsError="true" ContinueOnError="false" /> <WriteLinesToFile Lines="$(CommitHash)" File="@(UpdateAssemblyInfoStamp)" Overwrite="true" Condition="'$(CommitHash)'!='$(LastCommitHash)'" /> <ReadLinesFromFile ContinueOnError="true" File="..\VERSION"> <Output TaskParameter="Lines" PropertyName="PackageVersion" /> </ReadLinesFromFile> </Target> <Target Name="CleanUpdateAssemblyInfo" BeforeTargets="BeforeClean"> <Delete Files="@(UpdateAssemblyInfoStamp);..\VERSION" /> </Target> </Project>
ILSpy/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj", "repo_id": "ILSpy", "token_count": 15098 }
230
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.IL.ControlFlow { /// <summary> /// C# switch statements are not necessarily compiled into IL switch instructions. /// For example, when the label values are not contiguous, the C# compiler /// will generate if statements similar to a binary search. /// /// This class analyses such sequences of if statements to reconstruct the original switch. /// </summary> /// <remarks> /// This analysis expects to be run on basic blocks (not extended basic blocks). /// </remarks> class SwitchAnalysis { /// <summary> /// The variable that is used to represent the switch expression. /// <c>null</c> while analyzing the first block. /// </summary> ILVariable switchVar; /// <summary> /// The variable to be used as the argument of the switch instruction. /// </summary> public ILVariable SwitchVariable => switchVar; /// <summary> /// Whether at least one of the analyzed blocks contained an IL switch constructors. /// </summary> public bool ContainsILSwitch { get; private set; } /// <summary> /// Gets the sections that were detected by the previous AnalyzeBlock() call. /// </summary> public readonly List<KeyValuePair<LongSet, ILInstruction>> Sections = new List<KeyValuePair<LongSet, ILInstruction>>(); /// <summary> /// Used to de-duplicate sections with a branch instruction. /// Invariant: (Sections[targetBlockToSectionIndex[branch.TargetBlock]].Instruction as Branch).TargetBlock == branch.TargetBlock /// </summary> readonly Dictionary<Block, int> targetBlockToSectionIndex = new Dictionary<Block, int>(); /// <summary> /// Used to de-duplicate sections with a value-less leave instruction. /// Invariant: (Sections[targetBlockToSectionIndex[leave.TargetContainer]].Instruction as Leave).TargetContainer == leave.TargetContainer /// </summary> readonly Dictionary<BlockContainer, int> targetContainerToSectionIndex = new Dictionary<BlockContainer, int>(); /// <summary> /// Blocks that can be deleted if the tail of the initial block is replaced with a switch instruction. /// </summary> public readonly List<Block> InnerBlocks = new List<Block>(); public Block RootBlock { get; private set; } /// <summary> /// Gets/sets whether to allow unreachable cases in switch instructions. /// </summary> public bool AllowUnreachableCases { get; set; } /// <summary> /// Analyze the last two statements in the block and see if they can be turned into a /// switch instruction. /// </summary> /// <returns>true if the block could be analyzed successfully; false otherwise</returns> public bool AnalyzeBlock(Block block) { switchVar = null; RootBlock = block; targetBlockToSectionIndex.Clear(); targetContainerToSectionIndex.Clear(); Sections.Clear(); InnerBlocks.Clear(); ContainsILSwitch = false; return AnalyzeBlock(block, LongSet.Universe, tailOnly: true); } /// <summary> /// Analyzes the tail end (last two instructions) of a block. /// </summary> /// <remarks> /// Sets <c>switchVar</c> and <c>defaultInstruction</c> if they are null, /// and adds found sections to <c>sectionLabels</c> and <c>sectionInstructions</c>. /// /// If the function returns false, <c>sectionLabels</c> and <c>sectionInstructions</c> are unmodified. /// </remarks> /// <param name="block">The block to analyze.</param> /// <param name="inputValues">The possible values of the "interesting" variable /// when control flow reaches this block.</param> /// <param name="tailOnly">If true, analyze only the tail (last two instructions). /// If false, analyze the whole block.</param> bool AnalyzeBlock(Block block, LongSet inputValues, bool tailOnly = false) { if (block.Instructions.Count == 0) { // might happen if the block was already marked for deletion in SwitchDetection return false; } if (tailOnly) { Debug.Assert(block == RootBlock); } else { Debug.Assert(switchVar != null); // switchVar should always be determined by the top-level call if (block.IncomingEdgeCount != 1 || block == RootBlock) return false; // for now, let's only consider if-structures that form a tree if (block.Parent != RootBlock.Parent) return false; // all blocks should belong to the same container } LongSet trueValues; if (block.Instructions.Count >= 2 && block.Instructions[block.Instructions.Count - 2].MatchIfInstruction(out var condition, out var trueInst) && AnalyzeCondition(condition, out trueValues) ) { if (!(tailOnly || block.Instructions.Count == 2)) return false; trueValues = trueValues.IntersectWith(inputValues); if (trueValues.SetEquals(inputValues) || trueValues.IsEmpty) return false; Block trueBlock; if (trueInst.MatchBranch(out trueBlock) && AnalyzeBlock(trueBlock, trueValues)) { // OK, true block was further analyzed. InnerBlocks.Add(trueBlock); } else { // Create switch section for trueInst. AddSection(trueValues, trueInst); } } else if (block.Instructions.Last() is SwitchInstruction switchInst) { if (!(tailOnly || block.Instructions.Count == 1)) return false; if (AnalyzeSwitch(switchInst, inputValues)) { ContainsILSwitch = true; // OK return true; } else { // switch analysis failed (e.g. switchVar mismatch) return false; } } else { // unknown inst return false; } var remainingValues = inputValues.ExceptWith(trueValues); ILInstruction falseInst = block.Instructions.Last(); Block falseBlock; if (falseInst.MatchBranch(out falseBlock) && AnalyzeBlock(falseBlock, remainingValues)) { // OK, false block was further analyzed. InnerBlocks.Add(falseBlock); } else { // Create switch section for falseInst. AddSection(remainingValues, falseInst); } return true; } private bool AnalyzeSwitch(SwitchInstruction inst, LongSet inputValues) { Debug.Assert(!inst.IsLifted); long offset; if (MatchSwitchVar(inst.Value)) { offset = 0; } else if (inst.Value is BinaryNumericInstruction bop) { if (bop.CheckForOverflow) return false; if (MatchSwitchVar(bop.Left) && bop.Right.MatchLdcI(out long val)) { switch (bop.Operator) { case BinaryNumericOperator.Add: offset = unchecked(-val); break; case BinaryNumericOperator.Sub: offset = val; break; default: // unknown bop.Operator return false; } } else { // unknown bop.Left return false; } } else { // unknown inst.Value return false; } foreach (var section in inst.Sections) { var matchValues = section.Labels.AddOffset(offset).IntersectWith(inputValues); if (!AllowUnreachableCases && matchValues.IsEmpty) return false; if (matchValues.Count() > 1 && section.Body.MatchBranch(out var targetBlock) && AnalyzeBlock(targetBlock, matchValues)) { InnerBlocks.Add(targetBlock); } else { AddSection(matchValues, section.Body); } } return true; } /// <summary> /// Adds a new section to the Sections list. /// /// If the instruction is a branch instruction, unify the new section with an existing section /// that also branches to the same target. /// </summary> void AddSection(LongSet values, ILInstruction inst) { if (values.IsEmpty) { return; } if (inst.MatchBranch(out Block targetBlock)) { if (targetBlockToSectionIndex.TryGetValue(targetBlock, out int index)) { Sections[index] = new KeyValuePair<LongSet, ILInstruction>( Sections[index].Key.UnionWith(values), inst ); } else { targetBlockToSectionIndex.Add(targetBlock, Sections.Count); Sections.Add(new KeyValuePair<LongSet, ILInstruction>(values, inst)); } } else if (inst.MatchLeave(out BlockContainer targetContainer)) { if (targetContainerToSectionIndex.TryGetValue(targetContainer, out int index)) { Sections[index] = new KeyValuePair<LongSet, ILInstruction>( Sections[index].Key.UnionWith(values), inst ); } else { targetContainerToSectionIndex.Add(targetContainer, Sections.Count); Sections.Add(new KeyValuePair<LongSet, ILInstruction>(values, inst)); } } else { Sections.Add(new KeyValuePair<LongSet, ILInstruction>(values, inst)); } } bool MatchSwitchVar(ILInstruction inst) { if (switchVar != null) return inst.MatchLdLoc(switchVar); else return inst.MatchLdLoc(out switchVar); } bool MatchSwitchVar(ILInstruction inst, out long sub) { if (inst is BinaryNumericInstruction bn && bn.Operator == BinaryNumericOperator.Sub && !bn.CheckForOverflow && !bn.IsLifted && bn.Right.MatchLdcI(out sub)) { return MatchSwitchVar(bn.Left); } sub = 0; return MatchSwitchVar(inst); } /// <summary> /// Analyzes the boolean condition, returning the set of values of the interesting /// variable for which the condition evaluates to true. /// </summary> private bool AnalyzeCondition(ILInstruction condition, out LongSet trueValues) { if (condition is Comp comp && MatchSwitchVar(comp.Left, out var sub) && comp.Right.MatchLdcI(out long val)) { // if (comp((V - sub) OP val)) trueValues = MakeSetWhereComparisonIsTrue(comp.Kind, val, comp.Sign); trueValues = trueValues.AddOffset(sub); return true; } else if (MatchSwitchVar(condition)) { // if (ldloc V) --> branch for all values except 0 trueValues = new LongSet(0).Invert(); return true; } else if (condition.MatchLogicNot(out ILInstruction arg)) { // if (logic.not(X)) --> branch for all values where if (X) does not branch bool res = AnalyzeCondition(arg, out LongSet falseValues); trueValues = falseValues.Invert(); return res; } else { trueValues = LongSet.Empty; return false; } } /// <summary> /// Create the LongSet that contains a value x iff x compared with value is true. /// </summary> internal static LongSet MakeSetWhereComparisonIsTrue(ComparisonKind kind, long val, Sign sign) { switch (kind) { case ComparisonKind.Equality: return new LongSet(val); case ComparisonKind.Inequality: return new LongSet(val).Invert(); case ComparisonKind.LessThan: return MakeGreaterThanOrEqualSet(val, sign).Invert(); case ComparisonKind.LessThanOrEqual: return MakeLessThanOrEqualSet(val, sign); case ComparisonKind.GreaterThan: return MakeLessThanOrEqualSet(val, sign).Invert(); case ComparisonKind.GreaterThanOrEqual: return MakeGreaterThanOrEqualSet(val, sign); default: throw new ArgumentException("Invalid ComparisonKind"); } } private static LongSet MakeGreaterThanOrEqualSet(long val, Sign sign) { if (sign == Sign.Signed) { return new LongSet(LongInterval.Inclusive(val, long.MaxValue)); } else { Debug.Assert(sign == Sign.Unsigned); if (val >= 0) { // The range val to ulong.MaxValue expressed with signed longs // is not a single contiguous range, but two ranges: return new LongSet(LongInterval.Inclusive(val, long.MaxValue)) .UnionWith(new LongSet(new LongInterval(long.MinValue, 0))); } else { return new LongSet(new LongInterval(val, 0)); } } } private static LongSet MakeLessThanOrEqualSet(long val, Sign sign) { if (sign == Sign.Signed) { return new LongSet(LongInterval.Inclusive(long.MinValue, val)); } else { Debug.Assert(sign == Sign.Unsigned); if (val >= 0) { return new LongSet(LongInterval.Inclusive(0, val)); } else { // The range 0 to (ulong)val expressed with signed longs // is not a single contiguous range, but two ranges: return new LongSet(LongInterval.Inclusive(0, long.MaxValue)) .UnionWith(new LongSet(LongInterval.Inclusive(long.MinValue, val))); } } } } }
ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs", "repo_id": "ILSpy", "token_count": 4557 }
231
#nullable enable // Copyright (c) 2014 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.IL.Transforms; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.IL { /// <summary> /// A container of IL blocks. /// Each block is an extended basic block (branches may only jump to the beginning of blocks, not into the middle), /// and only branches within this container may reference the blocks in this container. /// That means that viewed from the outside, the block container has a single entry point (but possibly multiple exit points), /// and the same holds for every block within the container. /// /// All blocks in the container must perform unconditional control flow (falling through to the block end is not allowed). /// To exit the block container, use the 'leave' instruction. /// </summary> partial class BlockContainer : ILInstruction { public static readonly SlotInfo BlockSlot = new SlotInfo("Block", isCollection: true); public readonly InstructionCollection<Block> Blocks; public ContainerKind Kind { get; set; } public StackType ExpectedResultType { get; set; } int leaveCount; /// <summary> /// Gets the number of 'leave' instructions that target this BlockContainer. /// </summary> public int LeaveCount { get => leaveCount; internal set { leaveCount = value; InvalidateFlags(); } } Block? entryPoint; /// <summary> /// Gets the container's entry point. This is the first block in the Blocks collection. /// </summary> public Block EntryPoint { get { // HACK: While it's possible to have BlockContainers without entry point, // normally every container must have an entry point according to its invariant. // Thus it's easier on the transforms if this property returns a non-nullable EntryPoint. return entryPoint!; } private set { if (entryPoint != null && IsConnected) entryPoint.IncomingEdgeCount--; entryPoint = value; if (entryPoint != null && IsConnected) entryPoint.IncomingEdgeCount++; } } public BlockContainer(ContainerKind kind = ContainerKind.Normal, StackType expectedResultType = StackType.Void) : base(OpCode.BlockContainer) { this.Kind = kind; this.Blocks = new InstructionCollection<Block>(this, 0); this.ExpectedResultType = expectedResultType; } public override ILInstruction Clone() { BlockContainer clone = new BlockContainer(this.Kind, this.ExpectedResultType); clone.AddILRange(this); clone.Blocks.AddRange(this.Blocks.Select(block => (Block)block.Clone())); // Adjust branch instructions to point to the new container foreach (var branch in clone.Descendants.OfType<Branch>()) { if (branch.TargetBlock != null && branch.TargetBlock.Parent == this) branch.TargetBlock = clone.Blocks[branch.TargetBlock.ChildIndex]; } foreach (var leave in clone.Descendants.OfType<Leave>()) { if (leave.TargetContainer == this) leave.TargetContainer = clone; } return clone; } protected internal override void InstructionCollectionUpdateComplete() { base.InstructionCollectionUpdateComplete(); this.EntryPoint = this.Blocks.FirstOrDefault()!; } protected override void Connected() { base.Connected(); if (entryPoint != null) entryPoint.IncomingEdgeCount++; } protected override void Disconnected() { base.Disconnected(); if (entryPoint != null) entryPoint.IncomingEdgeCount--; } public override void WriteTo(ITextOutput output, ILAstWritingOptions options) { WriteILRange(output, options); output.WriteLocalReference("BlockContainer", this, isDefinition: true); output.Write(' '); switch (Kind) { case ContainerKind.Loop: output.Write("(while-true) "); break; case ContainerKind.Switch: output.Write("(switch) "); break; case ContainerKind.While: output.Write("(while) "); break; case ContainerKind.DoWhile: output.Write("(do-while) "); break; case ContainerKind.For: output.Write("(for) "); break; } output.MarkFoldStart("{...}"); output.WriteLine("{"); output.Indent(); foreach (var inst in Blocks) { if (inst.Parent == this) { inst.WriteTo(output, options); } else { output.Write("stale reference to "); output.WriteLocalReference(inst.Label, inst); } output.WriteLine(); output.WriteLine(); } output.Unindent(); output.Write("}"); output.MarkFoldEnd(); } protected override int GetChildCount() { return Blocks.Count; } protected override ILInstruction GetChild(int index) { return Blocks[index]; } protected override void SetChild(int index, ILInstruction? value) { if (Blocks[index] != value) throw new InvalidOperationException("Cannot replace blocks in BlockContainer"); } protected override SlotInfo GetChildSlot(int index) { return BlockSlot; } internal override void CheckInvariant(ILPhase phase) { base.CheckInvariant(phase); Debug.Assert(Blocks.Count > 0 && EntryPoint == Blocks[0]); Debug.Assert(!IsConnected || EntryPoint.IncomingEdgeCount >= 1); Debug.Assert(Parent is ILFunction || !ILRangeIsEmpty); Debug.Assert(Blocks.All(b => b.HasFlag(InstructionFlags.EndPointUnreachable))); Debug.Assert(Blocks.All(b => b.Kind == BlockKind.ControlFlow)); // this also implies that the blocks don't use FinalInstruction Debug.Assert(TopologicalSort(deleteUnreachableBlocks: true).Count == Blocks.Count, "Container should not have any unreachable blocks"); Block? bodyStartBlock; switch (Kind) { case ContainerKind.Normal: break; case ContainerKind.Loop: Debug.Assert(EntryPoint.IncomingEdgeCount > 1); break; case ContainerKind.Switch: Debug.Assert(EntryPoint.Instructions.Count == 1); Debug.Assert(EntryPoint.Instructions[0] is SwitchInstruction); Debug.Assert(EntryPoint.IncomingEdgeCount == 1); break; case ContainerKind.While: Debug.Assert(EntryPoint.IncomingEdgeCount > 1); Debug.Assert(Blocks.Count >= 2); Debug.Assert(MatchConditionBlock(EntryPoint, out _, out bodyStartBlock)); Debug.Assert(bodyStartBlock == Blocks[1]); break; case ContainerKind.DoWhile: Debug.Assert(EntryPoint.IncomingEdgeCount > 1); Debug.Assert(Blocks.Count >= 2); Debug.Assert(MatchConditionBlock(Blocks.Last(), out _, out bodyStartBlock)); Debug.Assert(bodyStartBlock == EntryPoint); break; case ContainerKind.For: Debug.Assert(EntryPoint.IncomingEdgeCount == 2); Debug.Assert(Blocks.Count >= 3); Debug.Assert(MatchConditionBlock(EntryPoint, out _, out bodyStartBlock)); Debug.Assert(MatchIncrementBlock(Blocks.Last())); Debug.Assert(bodyStartBlock == Blocks[1]); break; } } protected override InstructionFlags ComputeFlags() { InstructionFlags flags = InstructionFlags.ControlFlow; foreach (var block in Blocks) { flags |= block.Flags; } // The end point of the BlockContainer is only reachable if there's a leave instruction if (LeaveCount == 0) flags |= InstructionFlags.EndPointUnreachable; else flags &= ~InstructionFlags.EndPointUnreachable; return flags; } public override InstructionFlags DirectFlags { get { return InstructionFlags.ControlFlow; } } internal override bool CanInlineIntoSlot(int childIndex, ILInstruction expressionBeingMoved) { // Inlining into the entry-point is allowed as long as we're not moving code into a loop. // This is used to inline into the switch expression. return childIndex == 0 && this.EntryPoint.IncomingEdgeCount == 1; } internal override bool PrepareExtract(int childIndex, ExtractionContext ctx) { // Un-inlining from the entry-point is allowed as long as we're not moving code out of a loop return childIndex == 0 && this.EntryPoint.IncomingEdgeCount == 1; } /// <summary> /// Topologically sort the blocks. /// The new order is returned without modifying the BlockContainer. /// </summary> /// <param name="deleteUnreachableBlocks">If true, unreachable blocks are not included in the new order.</param> public List<Block> TopologicalSort(bool deleteUnreachableBlocks = false) { // Visit blocks in post-order BitSet visited = new BitSet(Blocks.Count); List<Block> postOrder = new List<Block>(); GraphTraversal.DepthFirstSearch(new[] { EntryPoint }, MarkAsVisited, Successors, postOrder.Add, reverseSuccessors: true); postOrder.Reverse(); if (!deleteUnreachableBlocks) { for (int i = 0; i < Blocks.Count; i++) { if (!visited[i]) postOrder.Add(Blocks[i]); } } return postOrder; bool MarkAsVisited(Block block) { Debug.Assert(block.Parent == this); if (!visited[block.ChildIndex]) { visited[block.ChildIndex] = true; return true; } else { return false; } } IEnumerable<Block> Successors(Block block) { foreach (var branch in block.Descendants.OfType<Branch>()) { if (branch.TargetBlock.Parent == this) { yield return branch.TargetBlock; } } } } /// <summary> /// Topologically sort the blocks. /// </summary> /// <param name="deleteUnreachableBlocks">If true, delete unreachable blocks.</param> public void SortBlocks(bool deleteUnreachableBlocks = false) { if (Blocks.Count < 2) return; var newOrder = TopologicalSort(deleteUnreachableBlocks); Debug.Assert(newOrder[0] == Blocks[0]); Blocks.ReplaceList(newOrder); } public static BlockContainer? FindClosestContainer(ILInstruction? inst) { while (inst != null) { if (inst is BlockContainer bc) return bc; inst = inst.Parent; } return null; } public static BlockContainer? FindClosestSwitchContainer(ILInstruction? inst) { while (inst != null) { if (inst is BlockContainer { Kind: ContainerKind.Switch } bc) return bc; inst = inst.Parent; } return null; } public bool MatchConditionBlock(Block block, [NotNullWhen(true)] out ILInstruction? condition, [NotNullWhen(true)] out Block? bodyStartBlock) { condition = null; bodyStartBlock = null; if (block.Instructions.Count != 1) return false; if (!block.Instructions[0].MatchIfInstruction(out condition, out var trueInst, out var falseInst)) return false; return falseInst.MatchLeave(this) && trueInst.MatchBranch(out bodyStartBlock); } public bool MatchIncrementBlock(Block block) { if (block.Instructions.Count == 0) return false; if (!block.Instructions.Last().MatchBranch(EntryPoint)) return false; return true; } /// <summary> /// If the container consists of a single block with a single instruction, /// returns that instruction. /// Otherwise returns the block, or the container itself if it has multiple blocks. /// </summary> public ILInstruction SingleInstruction() { if (Blocks.Count != 1) return this; if (Blocks[0].Instructions.Count != 1) return Blocks[0]; return Blocks[0].Instructions[0]; } } public enum ContainerKind { /// <summary> /// Normal container that contains control-flow blocks. /// </summary> Normal, /// <summary> /// A while-true loop. /// Continue is represented as branch to entry-point. /// Return/break is represented as leave. /// </summary> Loop, /// <summary> /// Container that has a switch instruction as entry-point. /// Goto case is represented as branch. /// Break is represented as leave. /// </summary> Switch, /// <summary> /// while-loop. /// The entry-point is a block consisting of a single if instruction /// that if true: jumps to the head of the loop body, /// if false: leaves the block. /// Continue is a branch to the entry-point. /// Break is a leave. /// </summary> While, /// <summary> /// do-while-loop. /// The entry-point is a block that is the head of the loop body. /// The last block consists of a single if instruction /// that if true: jumps to the head of the loop body, /// if false: leaves the block. /// Only the last block is allowed to jump to the entry-point. /// Continue is a branch to the last block. /// Break is a leave. /// </summary> DoWhile, /// <summary> /// for-loop. /// The entry-point is a block consisting of a single if instruction /// that if true: jumps to the head of the loop body, /// if false: leaves the block. /// The last block is the increment block. /// Only the last block is allowed to jump to the entry-point. /// Continue is a branch to the last block. /// Break is a leave. /// </summary> For } }
ILSpy/ICSharpCode.Decompiler/IL/Instructions/BlockContainer.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/BlockContainer.cs", "repo_id": "ILSpy", "token_count": 4793 }
232
// Copyright (c) 2014 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; namespace ICSharpCode.Decompiler.IL { public sealed class InstructionCollection<T> : IList<T>, IReadOnlyList<T> where T : ILInstruction { readonly ILInstruction parentInstruction; readonly int firstChildIndex; readonly List<T> list = new List<T>(); public InstructionCollection(ILInstruction parentInstruction, int firstChildIndex) { if (parentInstruction == null) throw new ArgumentNullException(nameof(parentInstruction)); this.parentInstruction = parentInstruction; this.firstChildIndex = firstChildIndex; } public int Count { get { return list.Count; } } public T this[int index] { get { return list[index]; } set { T oldValue = list[index]; if (!(oldValue == value && value.Parent == parentInstruction && value.ChildIndex == index)) { list[index] = value; value.ChildIndex = index + firstChildIndex; parentInstruction.InstructionCollectionAdded(value); parentInstruction.InstructionCollectionRemoved(oldValue); parentInstruction.InstructionCollectionUpdateComplete(); } } } #region GetEnumerator public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Custom enumerator for InstructionCollection. /// Unlike List{T}.Enumerator, this enumerator allows replacing an item during the enumeration. /// Adding/removing items from the collection still is invalid (however, such /// invalid actions are only detected in debug builds). /// /// Warning: even though this is a struct, it is invalid to copy: /// the number of constructor calls must match the number of dispose calls. /// </summary> public struct Enumerator : IEnumerator<T> { #if DEBUG ILInstruction? parentInstruction; #endif readonly List<T> list; int pos; public Enumerator(InstructionCollection<T> col) { this.list = col.list; this.pos = -1; #if DEBUG this.parentInstruction = col.parentInstruction; col.parentInstruction.StartEnumerator(); #endif } [DebuggerStepThrough] public bool MoveNext() { return ++pos < list.Count; } public T Current { [DebuggerStepThrough] get { return list[pos]; } } [DebuggerStepThrough] public void Dispose() { #if DEBUG if (parentInstruction != null) { parentInstruction.StopEnumerator(); parentInstruction = null; } #endif } void System.Collections.IEnumerator.Reset() { pos = -1; } object System.Collections.IEnumerator.Current { get { return this.Current; } } } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// Gets the index of the instruction in this collection. /// Returns -1 if the instruction does not exist in the collection. /// </summary> /// <remarks> /// Runs in O(1) if the item can be found using the Parent/ChildIndex properties. /// Otherwise, runs in O(N). /// </remarks> public int IndexOf(T? item) { if (item == null) { // InstructionCollection can't contain nulls return -1; } // If this collection is the item's primary position, we can use ChildIndex: int index = item.ChildIndex - firstChildIndex; if (index >= 0 && index < list.Count && list[index] == item) return index; // But we still need to fall back on a full search, because the ILAst might be // in a state where item is in multiple locations. return list.IndexOf(item); } /// <summary> /// Gets whether the item is in this collection. /// </summary> /// <remarks> /// This method searches the list. /// Usually it's more efficient to test item.Parent instead! /// </remarks> public bool Contains(T? item) { return IndexOf(item) >= 0; } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } bool ICollection<T>.IsReadOnly { get { return false; } } public void Add(T value) { parentInstruction.AssertNoEnumerators(); value.ChildIndex = list.Count + firstChildIndex; list.Add(value); parentInstruction.InstructionCollectionAdded(value); parentInstruction.InstructionCollectionUpdateComplete(); } public void AddRange(IEnumerable<T> values) { parentInstruction.AssertNoEnumerators(); foreach (T value in values) { value.ChildIndex = list.Count + firstChildIndex; list.Add(value); parentInstruction.InstructionCollectionAdded(value); } parentInstruction.InstructionCollectionUpdateComplete(); } /// <summary> /// Replaces all entries in the InstructionCollection with the newList. /// </summary> /// <remarks> /// Equivalent to Clear() followed by AddRange(newList), but slightly more efficient. /// </remarks> public void ReplaceList(IEnumerable<T> newList) { parentInstruction.AssertNoEnumerators(); int index = 0; foreach (T value in newList) { value.ChildIndex = index + firstChildIndex; if (index < list.Count) { T oldValue = list[index]; list[index] = value; parentInstruction.InstructionCollectionAdded(value); parentInstruction.InstructionCollectionRemoved(oldValue); } else { list.Add(value); parentInstruction.InstructionCollectionAdded(value); } index++; } for (int i = index; i < list.Count; i++) { parentInstruction.InstructionCollectionRemoved(list[i]); } list.RemoveRange(index, list.Count - index); parentInstruction.InstructionCollectionUpdateComplete(); } public void Insert(int index, T item) { parentInstruction.AssertNoEnumerators(); list.Insert(index, item); item.ChildIndex = index; parentInstruction.InstructionCollectionAdded(item); for (int i = index + 1; i < list.Count; i++) { T other_item = list[i]; // Update ChildIndex of items after the inserted one, but only if // that's their 'primary position' (in case of multiple parents) if (other_item.Parent == parentInstruction && other_item.ChildIndex == i + firstChildIndex - 1) other_item.ChildIndex = i + firstChildIndex; } parentInstruction.InstructionCollectionUpdateComplete(); } public void RemoveAt(int index) { parentInstruction.AssertNoEnumerators(); parentInstruction.InstructionCollectionRemoved(list[index]); list.RemoveAt(index); for (int i = index; i < list.Count; i++) { var other_item = list[i]; if (other_item.Parent == parentInstruction && other_item.ChildIndex == i + firstChildIndex + 1) other_item.ChildIndex = i + firstChildIndex; } parentInstruction.InstructionCollectionUpdateComplete(); } /// <summary> /// Remove item at index <c>index</c> in O(1) by swapping it with the last element in the collection. /// </summary> public void SwapRemoveAt(int index) { parentInstruction.AssertNoEnumerators(); parentInstruction.InstructionCollectionRemoved(list[index]); int removeIndex = list.Count - 1; T movedItem = list[index] = list[removeIndex]; list.RemoveAt(removeIndex); if (movedItem.Parent == parentInstruction && movedItem.ChildIndex == removeIndex + firstChildIndex) movedItem.ChildIndex = index + firstChildIndex; parentInstruction.InstructionCollectionUpdateComplete(); } public void Clear() { parentInstruction.AssertNoEnumerators(); foreach (var entry in list) { parentInstruction.InstructionCollectionRemoved(entry); } list.Clear(); parentInstruction.InstructionCollectionUpdateComplete(); } public bool Remove(T item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } return false; } public void RemoveRange(int index, int count) { parentInstruction.AssertNoEnumerators(); for (int i = 0; i < count; i++) { parentInstruction.InstructionCollectionRemoved(list[index + i]); } list.RemoveRange(index, count); for (int i = index; i < list.Count; i++) { var other_item = list[i]; if (other_item.Parent == parentInstruction && other_item.ChildIndex == i + firstChildIndex + count) other_item.ChildIndex = i + firstChildIndex; } parentInstruction.InstructionCollectionUpdateComplete(); } /// <summary> /// Removes all elements for which the predicate returns true. /// </summary> /// <remarks> /// This method runs in O(N), which is more efficient than calling RemoveAt() in a loop. /// The collection may be in an invalid state during the invocation of the predicate. /// </remarks> public int RemoveAll(Predicate<T> predicate) { parentInstruction.AssertNoEnumerators(); int j = 0; for (int i = 0; i < list.Count; i++) { T item = list[i]; if (predicate(item)) { parentInstruction.InstructionCollectionRemoved(item); } else { // keep the item if (item.Parent == parentInstruction && item.ChildIndex == i + firstChildIndex) item.ChildIndex = j + firstChildIndex; list[j] = item; j++; } } int removed = list.Count - j; if (removed > 0) { list.RemoveRange(j, removed); parentInstruction.InstructionCollectionUpdateComplete(); } return removed; } public void MoveElementToIndex(int oldIndex, int newIndex) { parentInstruction.AssertNoEnumerators(); var item = list[oldIndex]; Insert(newIndex, item); if (oldIndex < newIndex) RemoveAt(oldIndex); else RemoveAt(oldIndex + 1); } public void MoveElementToIndex(T item, int newIndex) { parentInstruction.AssertNoEnumerators(); int oldIndex = IndexOf(item); if (oldIndex >= 0) { Insert(newIndex, item); if (oldIndex < newIndex) RemoveAt(oldIndex); else RemoveAt(oldIndex + 1); } } public void MoveElementToEnd(int index) { MoveElementToIndex(index, list.Count); } public void MoveElementToEnd(T item) { MoveElementToIndex(item, list.Count); } // more efficient versions of some LINQ methods: public T First() { return list[0]; } public T? FirstOrDefault() { return list.Count > 0 ? list[0] : null; } public T Last() { return list[list.Count - 1]; } public T? LastOrDefault() { return list.Count > 0 ? list[list.Count - 1] : null; } public T? SecondToLastOrDefault() { return list.Count > 1 ? list[list.Count - 2] : null; } public T? ElementAtOrDefault(int index) { if (index >= 0 && index < list.Count) return list[index]; return null; } } }
ILSpy/ICSharpCode.Decompiler/IL/Instructions/InstructionCollection.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/InstructionCollection.cs", "repo_id": "ILSpy", "token_count": 4258 }
233
// Copyright (c) 2011-2016 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.IL.Transforms { /// <summary> /// Transforms anonymous methods and lambdas by creating nested ILFunctions. /// </summary> public class DelegateConstruction : IILTransform { ILTransformContext context; ITypeResolveContext decompilationContext; readonly Stack<MethodDefinitionHandle> activeMethods = new Stack<MethodDefinitionHandle>(); void IILTransform.Run(ILFunction function, ILTransformContext context) { if (!context.Settings.AnonymousMethods) return; var prevContext = this.context; var prevDecompilationContext = this.decompilationContext; try { activeMethods.Push((MethodDefinitionHandle)function.Method.MetadataToken); this.context = context; this.decompilationContext = new SimpleTypeResolveContext(function.Method); var cancellationToken = context.CancellationToken; foreach (var inst in function.Descendants) { cancellationToken.ThrowIfCancellationRequested(); if (!MatchDelegateConstruction(inst, out var targetMethod, out var target, out var delegateType, allowTransformed: false)) continue; context.StepStartGroup($"TransformDelegateConstruction {inst.StartILOffset}", inst); ILFunction f = TransformDelegateConstruction(inst, targetMethod, target, delegateType); if (f != null && target is IInstructionWithVariableOperand instWithVar) { var v = instWithVar.Variable; if (v.Kind == VariableKind.Local) { v.Kind = VariableKind.DisplayClassLocal; } if (v.IsSingleDefinition && v.StoreInstructions.SingleOrDefault() is StLoc store && store.Value is NewObj) { v.CaptureScope = BlockContainer.FindClosestContainer(store); } } context.StepEndGroup(); } } finally { this.context = prevContext; this.decompilationContext = prevDecompilationContext; activeMethods.Pop(); } } internal static bool MatchDelegateConstruction(ILInstruction inst, out IMethod targetMethod, out ILInstruction target, out IType delegateType, bool allowTransformed = false) { targetMethod = null; target = null; delegateType = null; switch (inst) { case NewObj call: if (call.Arguments.Count != 2) return false; target = call.Arguments[0]; var opCode = call.Arguments[1].OpCode; delegateType = call.Method.DeclaringType; if (!(opCode == OpCode.LdFtn || opCode == OpCode.LdVirtFtn || (allowTransformed && opCode == OpCode.ILFunction))) return false; targetMethod = ((IInstructionWithMethodOperand)call.Arguments[1]).Method; break; case LdVirtDelegate ldVirtDelegate: target = ldVirtDelegate.Argument; targetMethod = ldVirtDelegate.Method; delegateType = ldVirtDelegate.Type; break; default: return false; } return delegateType.Kind == TypeKind.Delegate || delegateType.Kind == TypeKind.Unknown; } static bool IsAnonymousMethod(ITypeDefinition decompiledTypeDefinition, IMethod method) { if (method == null) return false; if (!(method.HasGeneratedName() || method.Name.Contains("$") || method.IsCompilerGeneratedOrIsInCompilerGeneratedClass() || TransformDisplayClassUsage.IsPotentialClosure( decompiledTypeDefinition, method.DeclaringTypeDefinition) || ContainsAnonymousType(method))) { return false; } return true; } static bool ContainsAnonymousType(IMethod method) { if (method.ReturnType.ContainsAnonymousType()) return true; foreach (var p in method.Parameters) { if (p.Type.ContainsAnonymousType()) return true; } return false; } static GenericContext? GenericContextFromTypeArguments(TypeParameterSubstitution subst) { var classTypeParameters = new List<ITypeParameter>(); var methodTypeParameters = new List<ITypeParameter>(); if (subst.ClassTypeArguments != null) { foreach (var t in subst.ClassTypeArguments) { if (t is ITypeParameter tp) classTypeParameters.Add(tp); else return null; } } if (subst.MethodTypeArguments != null) { foreach (var t in subst.MethodTypeArguments) { if (t is ITypeParameter tp) methodTypeParameters.Add(tp); else return null; } } return new GenericContext(classTypeParameters, methodTypeParameters); } ILFunction TransformDelegateConstruction( ILInstruction value, IMethod targetMethod, ILInstruction target, IType delegateType) { if (!IsAnonymousMethod(decompilationContext.CurrentTypeDefinition, targetMethod)) return null; if (targetMethod.MetadataToken.IsNil) return null; if (LocalFunctionDecompiler.IsLocalFunctionMethod(targetMethod, context)) return null; if (!ValidateDelegateTarget(target)) return null; var handle = (MethodDefinitionHandle)targetMethod.MetadataToken; if (activeMethods.Contains(handle)) { this.context.Function.Warnings.Add(" Found self-referencing delegate construction. Abort transformation to avoid stack overflow."); return null; } var methodDefinition = context.PEFile.Metadata.GetMethodDefinition((MethodDefinitionHandle)targetMethod.MetadataToken); if (!methodDefinition.HasBody()) return null; var genericContext = GenericContextFromTypeArguments(targetMethod.Substitution); if (genericContext == null) return null; var ilReader = context.CreateILReader(); var body = context.PEFile.Reader.GetMethodBody(methodDefinition.RelativeVirtualAddress); var function = ilReader.ReadIL((MethodDefinitionHandle)targetMethod.MetadataToken, body, genericContext.Value, ILFunctionKind.Delegate, context.CancellationToken); function.DelegateType = delegateType; // Embed the lambda into the parent function's ILAst, so that "Show steps" can show // how the lambda body is being transformed. value.ReplaceWith(function); function.CheckInvariant(ILPhase.Normal); var contextPrefix = targetMethod.Name; foreach (ILVariable v in function.Variables.Where(v => v.Kind != VariableKind.Parameter)) { v.Name = contextPrefix + v.Name; } var nestedContext = new ILTransformContext(context, function); function.RunTransforms(CSharpDecompiler.GetILTransforms().TakeWhile(t => !(t is DelegateConstruction)).Concat(GetTransforms()), nestedContext); nestedContext.Step("DelegateConstruction (ReplaceDelegateTargetVisitor)", function); function.AcceptVisitor(new ReplaceDelegateTargetVisitor(target, function.Variables.SingleOrDefault(VariableKindExtensions.IsThis))); // handle nested lambdas nestedContext.StepStartGroup("DelegateConstruction (nested lambdas)", function); ((IILTransform)this).Run(function, nestedContext); nestedContext.StepEndGroup(); function.AddILRange(target); function.AddILRange(value); if (value is Call call) function.AddILRange(call.Arguments[1]); return function; } private static bool ValidateDelegateTarget(ILInstruction inst) { switch (inst) { case LdNull _: return true; case LdLoc ldloc: return ldloc.Variable.IsSingleDefinition; case LdObj ldobj: // TODO : should make sure that the display-class 'this' is unused, // if the delegate target is ldobj(ldsflda field). if (ldobj.Target is LdsFlda) return true; // TODO : ldfld chains must be validated more thoroughly, i.e., we should make sure // that the value of the field is never changed. ILInstruction target = ldobj; while (target is LdObj || target is LdFlda) { if (target is LdObj o) { target = o.Target; continue; } if (target is LdFlda f) { target = f.Target; continue; } } return target is LdLoc; default: return false; } } private IEnumerable<IILTransform> GetTransforms() { yield return new CombineExitsTransform(); } /// <summary> /// Replaces loads of 'this' with the target expression. /// Async delegates use: ldobj(ldloca this). /// </summary> internal class ReplaceDelegateTargetVisitor : ILVisitor { readonly ILVariable thisVariable; readonly ILInstruction target; public ReplaceDelegateTargetVisitor(ILInstruction target, ILVariable thisVariable) { this.target = target; this.thisVariable = thisVariable; } protected override void Default(ILInstruction inst) { foreach (var child in inst.Children) { child.AcceptVisitor(this); } } protected internal override void VisitILFunction(ILFunction function) { if (function == thisVariable?.Function) { ILVariable v = null; switch (target) { case LdLoc l: v = l.Variable; break; case LdObj lo: ILInstruction inner = lo.Target; while (inner is LdFlda ldf) { inner = ldf.Target; } if (inner is LdLoc l2) v = l2.Variable; break; } if (v != null) function.CapturedVariables.Add(v); } base.VisitILFunction(function); } protected internal override void VisitLdLoc(LdLoc inst) { if (inst.Variable == thisVariable) { inst.ReplaceWith(target.Clone()); return; } base.VisitLdLoc(inst); } protected internal override void VisitLdObj(LdObj inst) { if (inst.Target.MatchLdLoca(thisVariable)) { inst.ReplaceWith(target.Clone()); return; } base.VisitLdObj(inst); } } } }
ILSpy/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs", "repo_id": "ILSpy", "token_count": 3979 }
234
// Copyright (c) 2020 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using ICSharpCode.Decompiler.IL.Transforms; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.IL { class IntroduceNativeIntTypeOnLocals : IILTransform { public void Run(ILFunction function, ILTransformContext context) { if (!context.Settings.NativeIntegers) return; foreach (var nestedFunction in function.Descendants.OfType<ILFunction>()) { Dictionary<int, IType> variableTypeMapping = new(); foreach (var variable in nestedFunction.Variables) { if (variable.Kind != VariableKind.Local && variable.Kind != VariableKind.StackSlot && variable.Kind != VariableKind.PatternLocal && variable.Kind != VariableKind.ForeachLocal && variable.Kind != VariableKind.UsingLocal) { continue; } if (!(variable.Type.IsKnownType(KnownTypeCode.IntPtr) || variable.Type.IsKnownType(KnownTypeCode.UIntPtr))) continue; bool isUsedAsNativeInt = variable.LoadInstructions.Any(IsUsedAsNativeInt); bool isAssignedNativeInt = variable.StoreInstructions.Any(store => IsNativeIntStore(store, context.TypeSystem)); if (isUsedAsNativeInt || isAssignedNativeInt) { variable.Type = variable.Type.GetSign() == Sign.Unsigned ? SpecialType.NUInt : SpecialType.NInt; if (variable.Kind == VariableKind.Local && variable.Index.HasValue) variableTypeMapping[variable.Index.Value] = variable.Type; } } foreach (var variable in nestedFunction.Variables) { if (variable.Kind == VariableKind.Local && variable.Index.HasValue && variableTypeMapping.TryGetValue(variable.Index.Value, out var type)) { variable.Type = type; } } } } static bool IsUsedAsNativeInt(LdLoc load) { return load.Parent switch { BinaryNumericInstruction { UnderlyingResultType: StackType.I } => true, BitNot { UnderlyingResultType: StackType.I } => true, CallInstruction call => call.GetParameter(load.ChildIndex)?.Type.IsCSharpNativeIntegerType() ?? false, _ => false, }; } static bool IsNativeIntStore(IStoreInstruction store, ICompilation compilation) { if (store is StLoc stloc) { switch (stloc.Value) { case BinaryNumericInstruction { UnderlyingResultType: StackType.I }: return true; case Conv { ResultType: StackType.I }: return true; default: var inferredType = stloc.Value.InferType(compilation); return inferredType.IsCSharpNativeIntegerType(); } } return false; } } }
ILSpy/ICSharpCode.Decompiler/IL/Transforms/IntroduceNativeIntTypeOnLocals.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/IntroduceNativeIntTypeOnLocals.cs", "repo_id": "ILSpy", "token_count": 1274 }
235
// Copyright (c) 2017 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #nullable enable using System; using System.Diagnostics; namespace ICSharpCode.Decompiler.IL.Transforms { /// <summary> /// IL transform that runs on a sequence of statements within a block. /// </summary> /// <remarks> /// Interleaving different statement-combining transforms on a per-statement level /// improves detection of nested constructs. /// For example, array initializers can assume that each element assignment was already /// reduced to a single statement, even if the element contains a high-level construct /// detected by a different transform (e.g. object initializer). /// </remarks> public interface IStatementTransform { /// <summary> /// Runs the transform on the statements within a block. /// /// Note: the transform may only modify block.Instructions[pos..]. /// The transform will be called repeatedly for pos=block.Instructions.Count-1, pos=block.Instructions.Count-2, ..., pos=0. /// </summary> /// <param name="block">The current block.</param> /// <param name="pos">The starting position where the transform is allowed to work.</param> /// <param name="context">Additional parameters.</param> /// <remarks> /// Instructions prior to block.Instructions[pos] must not be modified. /// It is valid to read such instructions, but not recommended as those have not been transformed yet. /// /// This function is only called on control-flow blocks with unreachable end-point. /// Thus, the last instruction in the block always must have the EndPointUnreachable flag. /// ==> Instructions with reachable end can't be last. Some transforms use this to save some bounds checks. /// </remarks> void Run(Block block, int pos, StatementTransformContext context); } /// <summary> /// Parameter class holding various arguments for <see cref="IStatementTransform.Run"/>. /// </summary> public class StatementTransformContext : ILTransformContext { public BlockTransformContext BlockContext { get; } public StatementTransformContext(BlockTransformContext blockContext) : base(blockContext) { this.BlockContext = blockContext ?? throw new ArgumentNullException(nameof(blockContext)); } /// <summary> /// Gets the block on which the transform is running. /// </summary> public Block Block => BlockContext.Block; internal bool rerunCurrentPosition; internal int? rerunPosition; /// <summary> /// After the current statement transform has completed, /// do not continue with the next statement transform at the same position. /// Instead, re-run all statement transforms (including the current transform) starting at the specified position. /// </summary> public void RequestRerun(int pos) { if (rerunPosition == null || pos > rerunPosition) { rerunPosition = pos; } } /// <summary> /// After the current statement transform has completed, /// repeat all statement transforms on the current position. /// </summary> public void RequestRerun() { rerunCurrentPosition = true; } } /// <summary> /// Block transform that runs a list of statement transforms. /// </summary> public class StatementTransform : IBlockTransform { readonly IStatementTransform[] children; public StatementTransform(params IStatementTransform[] children) { this.children = children; } public void Run(Block block, BlockTransformContext context) { var ctx = new StatementTransformContext(context); int pos = 0; if (context.IndexOfFirstAlreadyTransformedInstruction == 0) { return; } ctx.rerunPosition = context.IndexOfFirstAlreadyTransformedInstruction - 1; while (pos >= 0) { if (ctx.rerunPosition != null) { Debug.Assert(ctx.rerunPosition >= pos); #if DEBUG for (; pos < ctx.rerunPosition; ++pos) { block.Instructions[pos].ResetDirty(); } #else pos = ctx.rerunPosition.Value; #endif Debug.Assert(pos == ctx.rerunPosition); ctx.rerunPosition = null; } foreach (var transform in children) { transform.Run(block, pos, ctx); #if DEBUG block.Instructions[pos].CheckInvariant(ILPhase.Normal); for (int i = Math.Max(0, pos - 100); i < pos; ++i) { if (block.Instructions[i].IsDirty) { Debug.Fail($"{transform.GetType().Name} modified an instruction before pos"); } } #endif if (ctx.rerunCurrentPosition) { ctx.rerunCurrentPosition = false; ctx.RequestRerun(pos); } if (ctx.rerunPosition != null) { break; } } if (ctx.rerunPosition == null) { pos--; } } // This invariant can be surprisingly expensive to check if the block has thousands // of instructions and is frequently modified by transforms (invalidating the flags each time) // so we'll check this only once at the end of the block. Debug.Assert(block.HasFlag(InstructionFlags.EndPointUnreachable)); } } }
ILSpy/ICSharpCode.Decompiler/IL/Transforms/StatementTransform.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/StatementTransform.cs", "repo_id": "ILSpy", "token_count": 1893 }
236
// Copyright (c) 2018 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using ICSharpCode.Decompiler.Util; using LightJson.Serialization; namespace ICSharpCode.Decompiler.Metadata { public class DotNetCorePathFinder { class DotNetCorePackageInfo { public readonly string Name; public readonly string Version; public readonly string Type; public readonly string Path; public readonly string[] RuntimeComponents; public DotNetCorePackageInfo(string fullName, string type, string path, string[] runtimeComponents) { var parts = fullName.Split('/'); this.Name = parts[0]; if (parts.Length > 1) { this.Version = parts[1]; } else { this.Version = "<UNKNOWN>"; } this.Type = type; this.Path = path; this.RuntimeComponents = runtimeComponents ?? Empty<string>.Array; } } static readonly string[] LookupPaths = new string[] { Environment.GetEnvironmentVariable("NUGET_PACKAGES"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages") }; static readonly string[] RuntimePacks = new[] { "Microsoft.NETCore.App", "Microsoft.WindowsDesktop.App", "Microsoft.AspNetCore.App", "Microsoft.AspNetCore.All" }; readonly DotNetCorePackageInfo[] packages; readonly List<string> searchPaths = new List<string>(); readonly List<string> packageBasePaths = new List<string>(); readonly Version targetFrameworkVersion; readonly string dotnetBasePath = FindDotNetExeDirectory(); readonly string preferredRuntimePack; public DotNetCorePathFinder(TargetFrameworkIdentifier targetFramework, Version targetFrameworkVersion, string preferredRuntimePack) { this.targetFrameworkVersion = targetFrameworkVersion; this.preferredRuntimePack = preferredRuntimePack; if (targetFramework == TargetFrameworkIdentifier.NETStandard) { // .NET Standard 2.1 is implemented by .NET Core 3.0 or higher if (targetFrameworkVersion.Major == 2 && targetFrameworkVersion.Minor == 1) { this.targetFrameworkVersion = new Version(3, 0, 0); } } } public DotNetCorePathFinder(string parentAssemblyFileName, string targetFrameworkIdString, string preferredRuntimePack, TargetFrameworkIdentifier targetFramework, Version targetFrameworkVersion, ReferenceLoadInfo loadInfo = null) : this(targetFramework, targetFrameworkVersion, preferredRuntimePack) { string assemblyName = Path.GetFileNameWithoutExtension(parentAssemblyFileName); string basePath = Path.GetDirectoryName(parentAssemblyFileName); searchPaths.Add(basePath); var depsJsonFileName = Path.Combine(basePath, $"{assemblyName}.deps.json"); if (File.Exists(depsJsonFileName)) { packages = LoadPackageInfos(depsJsonFileName, targetFrameworkIdString).ToArray(); foreach (var path in LookupPaths) { if (string.IsNullOrWhiteSpace(path)) { continue; } foreach (var p in packages) { foreach (var item in p.RuntimeComponents) { var itemPath = Path.GetDirectoryName(item); var fullPath = Path.Combine(path, p.Name, p.Version, itemPath).ToLowerInvariant(); if (Directory.Exists(fullPath)) packageBasePaths.Add(fullPath); } } } } else { loadInfo?.AddMessage(assemblyName, MessageKind.Warning, $"{assemblyName}.deps.json could not be found!"); } } public void AddSearchDirectory(string path) { this.searchPaths.Add(path); } public void RemoveSearchDirectory(string path) { this.searchPaths.Remove(path); } public string TryResolveDotNetCore(IAssemblyReference name) { foreach (var basePath in searchPaths.Concat(packageBasePaths)) { if (File.Exists(Path.Combine(basePath, name.Name + ".dll"))) { return Path.Combine(basePath, name.Name + ".dll"); } else if (File.Exists(Path.Combine(basePath, name.Name + ".exe"))) { return Path.Combine(basePath, name.Name + ".exe"); } } return TryResolveDotNetCoreShared(name, out _); } internal string GetReferenceAssemblyPath(string targetFramework) { var (tfi, version) = UniversalAssemblyResolver.ParseTargetFramework(targetFramework); string identifier, identifierExt; switch (tfi) { case TargetFrameworkIdentifier.NETCoreApp: identifier = "Microsoft.NETCore.App"; identifierExt = "netcoreapp" + version.Major + "." + version.Minor; break; case TargetFrameworkIdentifier.NETStandard: identifier = "NETStandard.Library"; identifierExt = "netstandard" + version.Major + "." + version.Minor; break; case TargetFrameworkIdentifier.NET: identifier = "Microsoft.NETCore.App"; identifierExt = "net" + version.Major + "." + version.Minor; break; default: throw new NotSupportedException(); } string basePath = Path.Combine(dotnetBasePath, "packs", identifier + ".Ref"); string versionFolder = GetClosestVersionFolder(basePath, version); return Path.Combine(basePath, versionFolder, "ref", identifierExt); } static IEnumerable<DotNetCorePackageInfo> LoadPackageInfos(string depsJsonFileName, string targetFramework) { var dependencies = JsonReader.Parse(File.ReadAllText(depsJsonFileName)); var runtimeInfos = dependencies["targets"][targetFramework].AsJsonObject; var libraries = dependencies["libraries"].AsJsonObject; if (runtimeInfos == null || libraries == null) yield break; foreach (var library in libraries) { var type = library.Value["type"].AsString; var path = library.Value["path"].AsString; var runtimeInfo = runtimeInfos[library.Key].AsJsonObject?["runtime"].AsJsonObject; string[] components = new string[runtimeInfo?.Count ?? 0]; if (runtimeInfo != null) { int i = 0; foreach (var component in runtimeInfo) { components[i] = component.Key; i++; } } yield return new DotNetCorePackageInfo(library.Key, type, path, components); } } public string TryResolveDotNetCoreShared(IAssemblyReference name, out string runtimePack) { if (dotnetBasePath == null) { runtimePack = null; return null; } IEnumerable<string> runtimePacks = RuntimePacks; if (preferredRuntimePack != null) { runtimePacks = new[] { preferredRuntimePack }.Concat(runtimePacks); } foreach (string pack in runtimePacks) { runtimePack = pack; string basePath = Path.Combine(dotnetBasePath, "shared", pack); if (!Directory.Exists(basePath)) continue; var closestVersion = GetClosestVersionFolder(basePath, targetFrameworkVersion); if (File.Exists(Path.Combine(basePath, closestVersion, name.Name + ".dll"))) { return Path.Combine(basePath, closestVersion, name.Name + ".dll"); } else if (File.Exists(Path.Combine(basePath, closestVersion, name.Name + ".exe"))) { return Path.Combine(basePath, closestVersion, name.Name + ".exe"); } } runtimePack = null; return null; } static string GetClosestVersionFolder(string basePath, Version version) { var foundVersions = new DirectoryInfo(basePath).GetDirectories() .Select(d => ConvertToVersion(d.Name)) .Where(v => v.version != null); foreach (var folder in foundVersions.OrderBy(v => v.version)) { if (folder.version >= version) return folder.directoryName; } return version.ToString(); } internal static (Version version, string directoryName) ConvertToVersion(string name) { string RemoveTrailingVersionInfo() { string shortName = name; int dashIndex = shortName.IndexOf('-'); if (dashIndex > 0) { shortName = shortName.Remove(dashIndex); } return shortName; } try { return (new Version(RemoveTrailingVersionInfo()), name); } catch (Exception ex) { Trace.TraceWarning(ex.ToString()); return (null, null); } } public static string FindDotNetExeDirectory() { string dotnetExeName = (Environment.OSVersion.Platform == PlatformID.Unix) ? "dotnet" : "dotnet.exe"; foreach (var item in Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator)) { try { string fileName = Path.Combine(item, dotnetExeName); if (!File.Exists(fileName)) continue; if (Environment.OSVersion.Platform == PlatformID.Unix) { if ((new FileInfo(fileName).Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) { fileName = GetRealPath(fileName, Encoding.Default); if (!File.Exists(fileName)) continue; } } return Path.GetDirectoryName(fileName); } catch (ArgumentException) { } } return null; } static unsafe string GetRealPath(string path, Encoding encoding) { var bytes = encoding.GetBytes(path); fixed (byte* input = bytes) { byte* output = GetRealPath(input, null); if (output == null) { return null; } int len = 0; for (byte* c = output; *c != 0; c++) { len++; } byte[] result = new byte[len]; Marshal.Copy((IntPtr)output, result, 0, result.Length); Free(output); return encoding.GetString(result); } } [DllImport("libc", EntryPoint = "realpath")] static extern unsafe byte* GetRealPath(byte* path, byte* resolvedPath); [DllImport("libc", EntryPoint = "free")] static extern unsafe void Free(void* ptr); } }
ILSpy/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs", "repo_id": "ILSpy", "token_count": 3933 }
237
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.Output { [Flags] public enum ConversionFlags { /// <summary> /// Convert only the name. /// </summary> None = 0, /// <summary> /// Show the parameter list /// </summary> ShowParameterList = 1, /// <summary> /// Show names for parameters /// </summary> ShowParameterNames = 2, /// <summary> /// Show the accessibility (private, public, etc.) /// </summary> ShowAccessibility = 4, /// <summary> /// Show the definition key word (class, struct, Sub, Function, etc.) /// </summary> ShowDefinitionKeyword = 8, /// <summary> /// Show the declaring type for the type or member /// </summary> ShowDeclaringType = 0x10, /// <summary> /// Show modifiers (virtual, override, etc.) /// </summary> ShowModifiers = 0x20, /// <summary> /// Show the return type /// </summary> ShowReturnType = 0x40, /// <summary> /// Use fully qualified names for types. /// </summary> UseFullyQualifiedTypeNames = 0x80, /// <summary> /// Show the list of type parameters on method and class declarations. /// Type arguments for parameter/return types are always shown. /// </summary> ShowTypeParameterList = 0x100, /// <summary> /// For fields, events and methods: adds a semicolon at the end. /// For properties: shows "{ get; }" or similar. /// </summary> ShowBody = 0x200, /// <summary> /// Use fully qualified names for members. /// </summary> UseFullyQualifiedEntityNames = 0x400, /// <summary> /// Instead of placing the return type before the entity name, /// append it after the parameter list, preceeded by a colon. /// </summary> PlaceReturnTypeAfterParameterList = 0x800, /// <summary> /// Show the variance modifier of the type parameter. /// If active, shows 'Func&lt;in T, out TResult&gt;' instead of 'Func&lt;T, TResult&gt;'. /// </summary> ShowTypeParameterVarianceModifier = 0x1000, /// <summary> /// Show modifiers of parameters, e.g. 'this', 'params', 'ref', 'out' and 'in'. /// </summary> ShowParameterModifiers = 0x2000, /// <summary> /// Show default values of parameters. /// </summary> ShowParameterDefaultValues = 0x4000, /// <summary> /// Use <c>T?</c> instead of <c>Nullable&lt;T&gt;</c>. /// </summary> UseNullableSpecifierForValueTypes = 0x8000, /// <summary> /// Support <c>init</c> accessors. /// </summary> SupportInitAccessors = 0x10000, /// <summary> /// Support <c>record</c> classes. /// </summary> SupportRecordClasses = 0x20000, /// <summary> /// Support <c>record</c> structs. /// </summary> SupportRecordStructs = 0x40000, /// <summary> /// Support <c>&gt;&gt;&gt;</c> as unsigned right shift operator. /// </summary> SupportUnsignedRightShift = 0x80000, /// <summary> /// Support C# 11 <c>operator checked</c>. /// </summary> SupportOperatorChecked = 0x100000, StandardConversionFlags = ShowParameterNames | ShowAccessibility | ShowParameterList | ShowParameterModifiers | ShowParameterDefaultValues | UseNullableSpecifierForValueTypes | ShowReturnType | ShowModifiers | ShowTypeParameterList | ShowTypeParameterVarianceModifier | ShowDefinitionKeyword | ShowBody, All = 0x1fffff, } /// <summary> /// Ambiences are used to convert type system symbols to text (usually for displaying the symbol to the user; e.g. in editor tooltips). /// </summary> public interface IAmbience { ConversionFlags ConversionFlags { get; set; } string ConvertSymbol(ISymbol symbol); string ConvertType(IType type); string ConvertConstantValue(object constantValue); string WrapComment(string comment); } }
ILSpy/ICSharpCode.Decompiler/Output/IAmbience.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Output/IAmbience.cs", "repo_id": "ILSpy", "token_count": 1584 }
238
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Immutable; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.Semantics { /// <summary> /// Holds information about a conversion between two types. /// </summary> public abstract class Conversion : IEquatable<Conversion> { #region Conversion factory methods /// <summary> /// Not a valid conversion. /// </summary> public static readonly Conversion None = new InvalidConversion(); /// <summary> /// Identity conversion. /// </summary> public static readonly Conversion IdentityConversion = new BuiltinConversion(true, 0); public static readonly Conversion ImplicitNumericConversion = new NumericOrEnumerationConversion(true, false); public static readonly Conversion ExplicitNumericConversion = new NumericOrEnumerationConversion(false, false); public static readonly Conversion ImplicitLiftedNumericConversion = new NumericOrEnumerationConversion(true, true); public static readonly Conversion ExplicitLiftedNumericConversion = new NumericOrEnumerationConversion(false, true); public static Conversion EnumerationConversion(bool isImplicit, bool isLifted) { return new NumericOrEnumerationConversion(isImplicit, isLifted, true); } public static readonly Conversion NullLiteralConversion = new BuiltinConversion(true, 1); /// <summary> /// The numeric conversion of a constant expression. /// </summary> public static readonly Conversion ImplicitConstantExpressionConversion = new BuiltinConversion(true, 2); public static readonly Conversion ImplicitReferenceConversion = new BuiltinConversion(true, 3); public static readonly Conversion ExplicitReferenceConversion = new BuiltinConversion(false, 3); public static readonly Conversion ImplicitDynamicConversion = new BuiltinConversion(true, 4); public static readonly Conversion ExplicitDynamicConversion = new BuiltinConversion(false, 4); public static readonly Conversion ImplicitNullableConversion = new BuiltinConversion(true, 5); public static readonly Conversion ExplicitNullableConversion = new BuiltinConversion(false, 5); public static readonly Conversion ImplicitPointerConversion = new BuiltinConversion(true, 6); public static readonly Conversion ExplicitPointerConversion = new BuiltinConversion(false, 6); public static readonly Conversion BoxingConversion = new BuiltinConversion(true, 7); public static readonly Conversion UnboxingConversion = new BuiltinConversion(false, 8); /// <summary> /// C# 'as' cast. /// </summary> public static readonly Conversion TryCast = new BuiltinConversion(false, 9); /// <summary> /// C# 6 string interpolation expression implicitly being converted to <see cref="System.IFormattable"/> or <see cref="System.FormattableString"/>. /// </summary> public static readonly Conversion ImplicitInterpolatedStringConversion = new BuiltinConversion(true, 10); /// <summary> /// C# 7 throw expression being converted to an arbitrary type. /// </summary> public static readonly Conversion ThrowExpressionConversion = new BuiltinConversion(true, 11); public static Conversion UserDefinedConversion(IMethod operatorMethod, bool isImplicit, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted = false, bool isAmbiguous = false) { if (operatorMethod == null) throw new ArgumentNullException(nameof(operatorMethod)); return new UserDefinedConv(isImplicit, operatorMethod, conversionBeforeUserDefinedOperator, conversionAfterUserDefinedOperator, isLifted, isAmbiguous); } public static Conversion MethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument) { if (chosenMethod == null) throw new ArgumentNullException(nameof(chosenMethod)); return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: true); } public static Conversion InvalidMethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument) { if (chosenMethod == null) throw new ArgumentNullException(nameof(chosenMethod)); return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: false); } public static Conversion TupleConversion(ImmutableArray<Conversion> conversions) { return new TupleConv(conversions); } #endregion #region Inner classes sealed class InvalidConversion : Conversion { public override bool IsValid { get { return false; } } public override string ToString() { return "None"; } } sealed class NumericOrEnumerationConversion : Conversion { readonly bool isImplicit; readonly bool isLifted; readonly bool isEnumeration; public NumericOrEnumerationConversion(bool isImplicit, bool isLifted, bool isEnumeration = false) { this.isImplicit = isImplicit; this.isLifted = isLifted; this.isEnumeration = isEnumeration; } public override bool IsImplicit { get { return isImplicit; } } public override bool IsExplicit { get { return !isImplicit; } } public override bool IsNumericConversion { get { return !isEnumeration; } } public override bool IsEnumerationConversion { get { return isEnumeration; } } public override bool IsLifted { get { return isLifted; } } public override string ToString() { return (isImplicit ? "implicit" : "explicit") + (isLifted ? " lifted" : "") + (isEnumeration ? " enumeration" : " numeric") + " conversion"; } public override bool Equals(Conversion other) { NumericOrEnumerationConversion o = other as NumericOrEnumerationConversion; return o != null && isImplicit == o.isImplicit && isLifted == o.isLifted && isEnumeration == o.isEnumeration; } public override int GetHashCode() { return (isImplicit ? 1 : 0) + (isLifted ? 2 : 0) + (isEnumeration ? 4 : 0); } } sealed class BuiltinConversion : Conversion { readonly bool isImplicit; readonly byte type; public BuiltinConversion(bool isImplicit, byte type) { this.isImplicit = isImplicit; this.type = type; } public override bool IsImplicit { get { return isImplicit; } } public override bool IsExplicit { get { return !isImplicit; } } public override bool IsIdentityConversion { get { return type == 0; } } public override bool IsNullLiteralConversion { get { return type == 1; } } public override bool IsConstantExpressionConversion { get { return type == 2; } } public override bool IsReferenceConversion { get { return type == 3; } } public override bool IsDynamicConversion { get { return type == 4; } } public override bool IsNullableConversion { get { return type == 5; } } public override bool IsPointerConversion { get { return type == 6; } } public override bool IsBoxingConversion { get { return type == 7; } } public override bool IsUnboxingConversion { get { return type == 8; } } public override bool IsTryCast { get { return type == 9; } } public override bool IsInterpolatedStringConversion => type == 10; public override bool IsThrowExpressionConversion { get { return type == 11; } } public override string ToString() { string name = null; switch (type) { case 0: return "identity conversion"; case 1: return "null-literal conversion"; case 2: name = "constant-expression"; break; case 3: name = "reference"; break; case 4: name = "dynamic"; break; case 5: name = "nullable"; break; case 6: name = "pointer"; break; case 7: return "boxing conversion"; case 8: return "unboxing conversion"; case 9: return "try cast"; case 10: return "interpolated string"; case 11: return "throw-expression conversion"; } return (isImplicit ? "implicit " : "explicit ") + name + " conversion"; } } sealed class UserDefinedConv : Conversion { readonly IMethod method; readonly bool isLifted; readonly Conversion conversionBeforeUserDefinedOperator; readonly Conversion conversionAfterUserDefinedOperator; readonly bool isImplicit; readonly bool isValid; public UserDefinedConv(bool isImplicit, IMethod method, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted, bool isAmbiguous) { this.method = method; this.isLifted = isLifted; this.conversionBeforeUserDefinedOperator = conversionBeforeUserDefinedOperator; this.conversionAfterUserDefinedOperator = conversionAfterUserDefinedOperator; this.isImplicit = isImplicit; this.isValid = !isAmbiguous; } public override bool IsValid { get { return isValid; } } public override bool IsImplicit { get { return isImplicit; } } public override bool IsExplicit { get { return !isImplicit; } } public override bool IsLifted { get { return isLifted; } } public override bool IsUserDefined { get { return true; } } public override Conversion ConversionBeforeUserDefinedOperator { get { return conversionBeforeUserDefinedOperator; } } public override Conversion ConversionAfterUserDefinedOperator { get { return conversionAfterUserDefinedOperator; } } public override IMethod Method { get { return method; } } public override bool Equals(Conversion other) { UserDefinedConv o = other as UserDefinedConv; return o != null && isLifted == o.isLifted && isImplicit == o.isImplicit && isValid == o.isValid && method.Equals(o.method); } public override int GetHashCode() { return unchecked(method.GetHashCode() + (isLifted ? 31 : 27) + (isImplicit ? 71 : 61) + (isValid ? 107 : 109)); } public override string ToString() { return (isImplicit ? "implicit" : "explicit") + (isLifted ? " lifted" : "") + (isValid ? "" : " ambiguous") + "user-defined conversion (" + method + ")"; } } sealed class MethodGroupConv : Conversion { readonly IMethod method; readonly bool isVirtualMethodLookup; readonly bool delegateCapturesFirstArgument; readonly bool isValid; public MethodGroupConv(IMethod method, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument, bool isValid) { this.method = method; this.isVirtualMethodLookup = isVirtualMethodLookup; this.delegateCapturesFirstArgument = delegateCapturesFirstArgument; this.isValid = isValid; } public override bool IsValid { get { return isValid; } } public override bool IsImplicit { get { return true; } } public override bool IsMethodGroupConversion { get { return true; } } public override bool IsVirtualMethodLookup { get { return isVirtualMethodLookup; } } public override bool DelegateCapturesFirstArgument { get { return delegateCapturesFirstArgument; } } public override IMethod Method { get { return method; } } public override bool Equals(Conversion other) { MethodGroupConv o = other as MethodGroupConv; return o != null && method.Equals(o.method); } public override int GetHashCode() { return method.GetHashCode(); } } sealed class TupleConv : Conversion { public override bool IsImplicit { get; } public override bool IsExplicit => !IsImplicit; public override ImmutableArray<Conversion> ElementConversions { get; } public override bool IsTupleConversion => true; public TupleConv(ImmutableArray<Conversion> elementConversions) { this.ElementConversions = elementConversions; this.IsImplicit = elementConversions.All(c => c.IsImplicit); } public override bool Equals(Conversion other) { return other is TupleConv o && ElementConversions.SequenceEqual(o.ElementConversions); } public override int GetHashCode() { unchecked { int hash = 0; foreach (var conv in ElementConversions) { hash *= 31; hash += conv.GetHashCode(); } return hash; } } public override string ToString() { return (IsImplicit ? "implicit " : "explicit ") + " tuple conversion"; } } #endregion /// <summary> /// Gets whether the conversion is valid. /// </summary> public virtual bool IsValid { get { return true; } } public virtual bool IsImplicit { get { return false; } } public virtual bool IsExplicit { get { return false; } } /// <summary> /// Gets whether the conversion is an '<c>as</c>' cast. /// </summary> public virtual bool IsTryCast { get { return false; } } public virtual bool IsThrowExpressionConversion { get { return false; } } public virtual bool IsIdentityConversion { get { return false; } } public virtual bool IsNullLiteralConversion { get { return false; } } public virtual bool IsConstantExpressionConversion { get { return false; } } public virtual bool IsNumericConversion { get { return false; } } /// <summary> /// Gets whether this conversion is a lifted version of another conversion. /// </summary> public virtual bool IsLifted { get { return false; } } /// <summary> /// Gets whether the conversion is dynamic. /// </summary> public virtual bool IsDynamicConversion { get { return false; } } /// <summary> /// Gets whether the conversion is a reference conversion. /// </summary> public virtual bool IsReferenceConversion { get { return false; } } /// <summary> /// Gets whether the conversion is an enumeration conversion. /// </summary> public virtual bool IsEnumerationConversion { get { return false; } } /// <summary> /// Gets whether the conversion is a nullable conversion /// (conversion between a nullable type and the regular type). /// </summary> public virtual bool IsNullableConversion { get { return false; } } /// <summary> /// Gets whether this conversion is user-defined (op_Implicit or op_Explicit). /// </summary> public virtual bool IsUserDefined { get { return false; } } /// <summary> /// The conversion that is applied to the input before the user-defined conversion operator is invoked. /// </summary> public virtual Conversion ConversionBeforeUserDefinedOperator { get { return null; } } /// <summary> /// The conversion that is applied to the result of the user-defined conversion operator. /// </summary> public virtual Conversion ConversionAfterUserDefinedOperator { get { return null; } } /// <summary> /// Gets whether this conversion is a boxing conversion. /// </summary> public virtual bool IsBoxingConversion { get { return false; } } /// <summary> /// Gets whether this conversion is an unboxing conversion. /// </summary> public virtual bool IsUnboxingConversion { get { return false; } } /// <summary> /// Gets whether this conversion is a pointer conversion. /// </summary> public virtual bool IsPointerConversion { get { return false; } } /// <summary> /// Gets whether this conversion is a method group conversion. /// </summary> public virtual bool IsMethodGroupConversion { get { return false; } } /// <summary> /// For method-group conversions, gets whether to perform a virtual method lookup at runtime. /// </summary> public virtual bool IsVirtualMethodLookup { get { return false; } } /// <summary> /// For method-group conversions, gets whether the conversion captures the first argument. /// /// For instance methods, this property always returns true for C# method-group conversions. /// For static methods, this property returns true for method-group conversions of an extension method performed on an instance (eg. <c>Func&lt;int&gt; f = myEnumerable.Single</c>). /// </summary> public virtual bool DelegateCapturesFirstArgument { get { return false; } } /// <summary> /// Gets whether this conversion is an anonymous function conversion. /// </summary> public virtual bool IsAnonymousFunctionConversion { get { return false; } } /// <summary> /// Gets the method associated with this conversion. /// For user-defined conversions, this is the method being called. /// For method-group conversions, this is the method that was chosen from the group. /// </summary> public virtual IMethod Method { get { return null; } } /// <summary> /// Gets whether this conversion is a tuple conversion. /// </summary> public virtual bool IsTupleConversion => false; /// <summary> /// Gets whether this is an interpolated string conversion to <see cref="IFormattable" /> or <see cref="FormattableString"/>. /// </summary> public virtual bool IsInterpolatedStringConversion => false; /// <summary> /// For a tuple conversion, gets the individual tuple element conversions. /// </summary> public virtual ImmutableArray<Conversion> ElementConversions => default(ImmutableArray<Conversion>); public override sealed bool Equals(object obj) { return Equals(obj as Conversion); } public override int GetHashCode() { return base.GetHashCode(); } public virtual bool Equals(Conversion other) { return this == other; } } }
ILSpy/ICSharpCode.Decompiler/Semantics/Conversion.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Semantics/Conversion.cs", "repo_id": "ILSpy", "token_count": 6216 }
239
// Copyright (c) 2018 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem.Implementation; using ICSharpCode.Decompiler.Util; using static ICSharpCode.Decompiler.Metadata.MetadataExtensions; using SRM = System.Reflection.Metadata; namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// Options that control how metadata is represented in the type system. /// </summary> [Flags] public enum TypeSystemOptions { /// <summary> /// No options enabled; stay as close to the metadata as possible. /// </summary> None = 0, /// <summary> /// [DynamicAttribute] is used to replace 'object' types with the 'dynamic' type. /// /// If this option is not active, the 'dynamic' type is not used, and the attribute is preserved. /// </summary> Dynamic = 1, /// <summary> /// Tuple types are represented using the TupleType class. /// [TupleElementNames] is used to name the tuple elements. /// /// If this option is not active, the tuples are represented using their underlying type, and the attribute is preserved. /// </summary> Tuple = 2, /// <summary> /// If this option is active, [ExtensionAttribute] is removed and methods are marked as IsExtensionMethod. /// Otherwise, the attribute is preserved but the methods are not marked. /// </summary> ExtensionMethods = 4, /// <summary> /// Only load the public API into the type system. /// </summary> OnlyPublicAPI = 8, /// <summary> /// Do not cache accessed entities. /// In a normal type system (without this option), every type or member definition has exactly one ITypeDefinition/IMember /// instance. This instance is kept alive until the whole type system can be garbage-collected. /// When this option is specified, the type system avoids these caches. /// This reduces the memory usage in many cases, but increases the number of allocations. /// Also, some code in the decompiler expects to be able to compare type/member definitions by reference equality, /// and thus will fail with uncached type systems. /// </summary> Uncached = 0x10, /// <summary> /// If this option is active, [DecimalConstantAttribute] is removed and constant values are transformed into simple decimal literals. /// </summary> DecimalConstants = 0x20, /// <summary> /// If this option is active, modopt and modreq types are preserved in the type system. /// /// Note: the decompiler currently does not support handling modified types; /// activating this option may lead to incorrect decompilation or internal errors. /// </summary> KeepModifiers = 0x40, /// <summary> /// If this option is active, [IsReadOnlyAttribute] on parameters+structs is removed /// and parameters are marked as in, structs as readonly. /// Otherwise, the attribute is preserved but the parameters and structs are not marked. /// </summary> ReadOnlyStructsAndParameters = 0x80, /// <summary> /// If this option is active, [IsByRefLikeAttribute] is removed and structs are marked as ref. /// Otherwise, the attribute is preserved but the structs are not marked. /// </summary> RefStructs = 0x100, /// <summary> /// If this option is active, [IsUnmanagedAttribute] is removed from type parameters, /// and HasUnmanagedConstraint is set instead. /// </summary> UnmanagedConstraints = 0x200, /// <summary> /// If this option is active, [NullableAttribute] is removed and reference types with /// nullability annotations are used instead. /// </summary> NullabilityAnnotations = 0x400, /// <summary> /// If this option is active, [IsReadOnlyAttribute] on methods is removed /// and the method marked as ThisIsRefReadOnly. /// </summary> ReadOnlyMethods = 0x800, /// <summary> /// [NativeIntegerAttribute] is used to replace 'IntPtr' types with the 'nint' type. /// </summary> NativeIntegers = 0x1000, /// <summary> /// Allow function pointer types. If this option is not enabled, function pointers are /// replaced with the 'IntPtr' type. /// </summary> FunctionPointers = 0x2000, /// <summary> /// Allow C# 11 scoped annotation. If this option is not enabled, ScopedRefAttribute /// will be reported as custom attribute. /// </summary> ScopedRef = 0x4000, [Obsolete("Use ScopedRef instead")] LifetimeAnnotations = ScopedRef, /// <summary> /// Replace 'IntPtr' types with the 'nint' type even in absence of [NativeIntegerAttribute]. /// Note: DecompilerTypeSystem constructor removes this setting from the options if /// not targeting .NET 7 or later. /// </summary> NativeIntegersWithoutAttribute = 0x8000, /// <summary> /// Default settings: typical options for the decompiler, with all C# languages features enabled. /// </summary> Default = Dynamic | Tuple | ExtensionMethods | DecimalConstants | ReadOnlyStructsAndParameters | RefStructs | UnmanagedConstraints | NullabilityAnnotations | ReadOnlyMethods | NativeIntegers | FunctionPointers | ScopedRef | NativeIntegersWithoutAttribute } /// <summary> /// Manages the NRefactory type system for the decompiler. /// </summary> /// <remarks> /// This class is thread-safe. /// </remarks> public class DecompilerTypeSystem : SimpleCompilation, IDecompilerTypeSystem { public static TypeSystemOptions GetOptions(DecompilerSettings settings) { var typeSystemOptions = TypeSystemOptions.None; if (settings.Dynamic) typeSystemOptions |= TypeSystemOptions.Dynamic; if (settings.TupleTypes) typeSystemOptions |= TypeSystemOptions.Tuple; if (settings.ExtensionMethods) typeSystemOptions |= TypeSystemOptions.ExtensionMethods; if (settings.DecimalConstants) typeSystemOptions |= TypeSystemOptions.DecimalConstants; if (settings.IntroduceRefModifiersOnStructs) typeSystemOptions |= TypeSystemOptions.RefStructs; if (settings.IntroduceReadonlyAndInModifiers) typeSystemOptions |= TypeSystemOptions.ReadOnlyStructsAndParameters; if (settings.IntroduceUnmanagedConstraint) typeSystemOptions |= TypeSystemOptions.UnmanagedConstraints; if (settings.NullableReferenceTypes) typeSystemOptions |= TypeSystemOptions.NullabilityAnnotations; if (settings.ReadOnlyMethods) typeSystemOptions |= TypeSystemOptions.ReadOnlyMethods; if (settings.NativeIntegers) typeSystemOptions |= TypeSystemOptions.NativeIntegers; if (settings.FunctionPointers) typeSystemOptions |= TypeSystemOptions.FunctionPointers; if (settings.ScopedRef) typeSystemOptions |= TypeSystemOptions.ScopedRef; if (settings.NumericIntPtr) typeSystemOptions |= TypeSystemOptions.NativeIntegersWithoutAttribute; return typeSystemOptions; } public static Task<DecompilerTypeSystem> CreateAsync(PEFile mainModule, IAssemblyResolver assemblyResolver) { return CreateAsync(mainModule, assemblyResolver, TypeSystemOptions.Default); } public static Task<DecompilerTypeSystem> CreateAsync(PEFile mainModule, IAssemblyResolver assemblyResolver, DecompilerSettings settings) { return CreateAsync(mainModule, assemblyResolver, GetOptions(settings ?? throw new ArgumentNullException(nameof(settings)))); } public static async Task<DecompilerTypeSystem> CreateAsync(PEFile mainModule, IAssemblyResolver assemblyResolver, TypeSystemOptions typeSystemOptions) { if (mainModule == null) throw new ArgumentNullException(nameof(mainModule)); if (assemblyResolver == null) throw new ArgumentNullException(nameof(assemblyResolver)); var ts = new DecompilerTypeSystem(); await ts.InitializeAsync(mainModule, assemblyResolver, typeSystemOptions) .ConfigureAwait(false); return ts; } private MetadataModule mainModule; private DecompilerTypeSystem() { } public DecompilerTypeSystem(PEFile mainModule, IAssemblyResolver assemblyResolver) : this(mainModule, assemblyResolver, TypeSystemOptions.Default) { } public DecompilerTypeSystem(PEFile mainModule, IAssemblyResolver assemblyResolver, DecompilerSettings settings) : this(mainModule, assemblyResolver, GetOptions(settings ?? throw new ArgumentNullException(nameof(settings)))) { } public DecompilerTypeSystem(PEFile mainModule, IAssemblyResolver assemblyResolver, TypeSystemOptions typeSystemOptions) { if (mainModule == null) throw new ArgumentNullException(nameof(mainModule)); if (assemblyResolver == null) throw new ArgumentNullException(nameof(assemblyResolver)); InitializeAsync(mainModule, assemblyResolver, typeSystemOptions).GetAwaiter().GetResult(); } static readonly string[] implicitReferences = new[] { "System.Runtime.InteropServices", "System.Runtime.CompilerServices.Unsafe" }; private async Task InitializeAsync(PEFile mainModule, IAssemblyResolver assemblyResolver, TypeSystemOptions typeSystemOptions) { // Load referenced assemblies and type-forwarder references. // This is necessary to make .NET Core/PCL binaries work better. var referencedAssemblies = new List<PEFile>(); var assemblyReferenceQueue = new Queue<(bool IsAssembly, PEFile MainModule, object Reference, Task<PEFile> ResolveTask)>(); var comparer = KeyComparer.Create(((bool IsAssembly, PEFile MainModule, object Reference) reference) => reference.IsAssembly ? "A:" + ((IAssemblyReference)reference.Reference).FullName : "M:" + reference.Reference); var assemblyReferencesInQueue = new HashSet<(bool IsAssembly, PEFile Parent, object Reference)>(comparer); var mainMetadata = mainModule.Metadata; var tfm = mainModule.DetectTargetFrameworkId(); var (identifier, version) = UniversalAssemblyResolver.ParseTargetFramework(tfm); foreach (var h in mainMetadata.GetModuleReferences()) { try { var moduleRef = mainMetadata.GetModuleReference(h); var moduleName = mainMetadata.GetString(moduleRef.Name); foreach (var fileHandle in mainMetadata.AssemblyFiles) { var file = mainMetadata.GetAssemblyFile(fileHandle); if (mainMetadata.StringComparer.Equals(file.Name, moduleName) && file.ContainsMetadata) { AddToQueue(false, mainModule, moduleName); break; } } } catch (BadImageFormatException) { } } foreach (var refs in mainModule.AssemblyReferences) { AddToQueue(true, mainModule, refs); } while (assemblyReferenceQueue.Count > 0) { var asmRef = assemblyReferenceQueue.Dequeue(); var asm = await asmRef.ResolveTask.ConfigureAwait(false); if (asm != null) { referencedAssemblies.Add(asm); var metadata = asm.Metadata; foreach (var h in metadata.ExportedTypes) { var exportedType = metadata.GetExportedType(h); switch (exportedType.Implementation.Kind) { case SRM.HandleKind.AssemblyReference: AddToQueue(true, asm, new AssemblyReference(asm, (SRM.AssemblyReferenceHandle)exportedType.Implementation)); break; case SRM.HandleKind.AssemblyFile: var file = metadata.GetAssemblyFile((SRM.AssemblyFileHandle)exportedType.Implementation); AddToQueue(false, asm, metadata.GetString(file.Name)); break; } } } if (assemblyReferenceQueue.Count == 0) { // For .NET Core and .NET 5 and newer, we need to pull in implicit references which are not included in the metadata, // as they contain compile-time-only types, such as System.Runtime.InteropServices.dll (for DllImport, MarshalAs, etc.) switch (identifier) { case TargetFrameworkIdentifier.NETCoreApp: case TargetFrameworkIdentifier.NETStandard: case TargetFrameworkIdentifier.NET: foreach (var item in implicitReferences) { var existing = referencedAssemblies.FirstOrDefault(asm => asm.Name == item); if (existing == null) { AddToQueue(true, mainModule, AssemblyNameReference.Parse(item + ", Version=" + version.ToString(3) + ".0, Culture=neutral")); } } break; } } } if (!(identifier == TargetFrameworkIdentifier.NET && version >= new Version(7, 0))) { typeSystemOptions &= ~TypeSystemOptions.NativeIntegersWithoutAttribute; } var mainModuleWithOptions = mainModule.WithOptions(typeSystemOptions); var referencedAssembliesWithOptions = referencedAssemblies.Select(file => file.WithOptions(typeSystemOptions)); // Primitive types are necessary to avoid assertions in ILReader. // Other known types are necessary in order for transforms to work (e.g. Task<T> for async transform). // Figure out which known types are missing from our type system so far: var missingKnownTypes = KnownTypeReference.AllKnownTypes.Where(IsMissing).ToList(); if (missingKnownTypes.Count > 0) { Init(mainModule.WithOptions(typeSystemOptions), referencedAssembliesWithOptions.Concat(new[] { MinimalCorlib.CreateWithTypes(missingKnownTypes) })); } else { Init(mainModuleWithOptions, referencedAssembliesWithOptions); } this.mainModule = (MetadataModule)base.MainModule; void AddToQueue(bool isAssembly, PEFile mainModule, object reference) { if (assemblyReferencesInQueue.Add((isAssembly, mainModule, reference))) { // Immediately start loading the referenced module as we add the entry to the queue. // This allows loading multiple modules in parallel. Task<PEFile> asm; if (isAssembly) { asm = assemblyResolver.ResolveAsync((IAssemblyReference)reference); } else { asm = assemblyResolver.ResolveModuleAsync(mainModule, (string)reference); } assemblyReferenceQueue.Enqueue((isAssembly, mainModule, reference, asm)); } } bool IsMissing(KnownTypeReference knownType) { var name = knownType.TypeName; if (!mainModule.GetTypeDefinition(name).IsNil) return false; foreach (var file in referencedAssemblies) { if (!file.GetTypeDefinition(name).IsNil) return false; } return true; } } public new MetadataModule MainModule => mainModule; } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs", "repo_id": "ILSpy", "token_count": 4920 }
240
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #nullable enable namespace ICSharpCode.Decompiler.TypeSystem { public interface INamedElement { /// <summary> /// Gets the fully qualified name of the class the return type is pointing to. /// </summary> /// <returns> /// "System.Int32[]" for int[]<br/> /// "System.Collections.Generic.List" for List&lt;string&gt; /// "System.Environment.SpecialFolder" for Environment.SpecialFolder /// </returns> string FullName { get; } /// <summary> /// Gets the short name of the class the return type is pointing to. /// </summary> /// <returns> /// "Int32[]" for int[]<br/> /// "List" for List&lt;string&gt; /// "SpecialFolder" for Environment.SpecialFolder /// </returns> string Name { get; } /// <summary> /// Gets the full reflection name of the element. /// </summary> /// <remarks> /// For types, the reflection name can be parsed back into a ITypeReference by using /// <see cref="ReflectionHelper.ParseReflectionName(string)"/>. /// </remarks> /// <returns> /// "System.Int32[]" for int[]<br/> /// "System.Int32[][,]" for C# int[,][]<br/> /// "System.Collections.Generic.List`1[[System.String]]" for List&lt;string&gt; /// "System.Environment+SpecialFolder" for Environment.SpecialFolder /// </returns> string ReflectionName { get; } /// <summary> /// Gets the full name of the namespace containing this entity. /// </summary> string Namespace { get; } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/INamedElement.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/INamedElement.cs", "repo_id": "ILSpy", "token_count": 788 }
241
// Copyright (c) 2018 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Text; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.Semantics; using ICSharpCode.Decompiler.Util; using SRM = System.Reflection.Metadata; namespace ICSharpCode.Decompiler.TypeSystem.Implementation { readonly struct AttributeListBuilder { readonly MetadataModule module; readonly List<IAttribute> attributes; public AttributeListBuilder(MetadataModule module) { Debug.Assert(module != null); this.module = module; this.attributes = new List<IAttribute>(); } public AttributeListBuilder(MetadataModule module, int capacity) { Debug.Assert(module != null); this.module = module; this.attributes = new List<IAttribute>(capacity); } public void Add(IAttribute attr) { attributes.Add(attr); } /// <summary> /// Add a builtin attribute without any arguments. /// </summary> public void Add(KnownAttribute type) { // use the assemblies' cache for simple attributes Add(module.MakeAttribute(type)); } /// <summary> /// Construct a builtin attribute with a single positional argument of known type. /// </summary> public void Add(KnownAttribute type, KnownTypeCode argType, object argValue) { Add(type, ImmutableArray.Create(new CustomAttributeTypedArgument<IType>(module.Compilation.FindType(argType), argValue))); } /// <summary> /// Construct a builtin attribute with a single positional argument of known type. /// </summary> public void Add(KnownAttribute type, TopLevelTypeName argType, object argValue) { Add(type, ImmutableArray.Create(new CustomAttributeTypedArgument<IType>(module.Compilation.FindType(argType), argValue))); } /// <summary> /// Construct a builtin attribute. /// </summary> public void Add(KnownAttribute type, ImmutableArray<CustomAttributeTypedArgument<IType>> fixedArguments) { Add(new DefaultAttribute(module.GetAttributeType(type), fixedArguments, ImmutableArray.Create<CustomAttributeNamedArgument<IType>>())); } #region MarshalAsAttribute (ConvertMarshalInfo) internal void AddMarshalInfo(BlobHandle marshalInfo) { if (marshalInfo.IsNil) return; var metadata = module.metadata; Add(ConvertMarshalInfo(metadata.GetBlobReader(marshalInfo))); } const string InteropServices = "System.Runtime.InteropServices"; IAttribute ConvertMarshalInfo(SRM.BlobReader marshalInfo) { var b = new AttributeBuilder(module, KnownAttribute.MarshalAs); IType unmanagedTypeType = module.Compilation.FindType(new TopLevelTypeName(InteropServices, nameof(UnmanagedType))); int type = marshalInfo.ReadByte(); b.AddFixedArg(unmanagedTypeType, type); int size; switch (type) { case 0x1e: // FixedArray if (!marshalInfo.TryReadCompressedInteger(out size)) size = 0; b.AddNamedArg("SizeConst", KnownTypeCode.Int32, size); if (marshalInfo.RemainingBytes > 0) { type = marshalInfo.ReadByte(); if (type != 0x66) // None b.AddNamedArg("ArraySubType", unmanagedTypeType, type); } break; case 0x1d: // SafeArray if (marshalInfo.RemainingBytes > 0) { VarEnum varType = (VarEnum)marshalInfo.ReadByte(); if (varType != VarEnum.VT_EMPTY) { var varEnumType = new TopLevelTypeName(InteropServices, nameof(VarEnum)); b.AddNamedArg("SafeArraySubType", varEnumType, (int)varType); } } break; case 0x2a: // NATIVE_TYPE_ARRAY if (marshalInfo.RemainingBytes > 0) { type = marshalInfo.ReadByte(); } else { type = 0x66; // Cecil uses NativeType.None as default. } if (type != 0x50) { // Max b.AddNamedArg("ArraySubType", unmanagedTypeType, type); } int sizeParameterIndex = marshalInfo.TryReadCompressedInteger(out int value) ? value : -1; size = marshalInfo.TryReadCompressedInteger(out value) ? value : -1; int sizeParameterMultiplier = marshalInfo.TryReadCompressedInteger(out value) ? value : -1; if (size >= 0) { b.AddNamedArg("SizeConst", KnownTypeCode.Int32, size); } if (sizeParameterMultiplier != 0 && sizeParameterIndex >= 0) { b.AddNamedArg("SizeParamIndex", KnownTypeCode.Int16, (short)sizeParameterIndex); } break; case 0x2c: // CustomMarshaler string guidValue = marshalInfo.ReadSerializedString(); string unmanagedType = marshalInfo.ReadSerializedString(); string managedType = marshalInfo.ReadSerializedString(); string cookie = marshalInfo.ReadSerializedString(); if (managedType != null) { b.AddNamedArg("MarshalType", KnownTypeCode.String, managedType); } if (!string.IsNullOrEmpty(cookie)) { b.AddNamedArg("MarshalCookie", KnownTypeCode.String, cookie); } break; case 0x17: // FixedSysString b.AddNamedArg("SizeConst", KnownTypeCode.Int32, marshalInfo.ReadCompressedInteger()); break; } return b.Build(); } #endregion #region Custom Attributes (ReadAttribute) public void Add(CustomAttributeHandleCollection attributes, SymbolKind target) { var metadata = module.metadata; foreach (var handle in attributes) { var attribute = metadata.GetCustomAttribute(handle); // Attribute types shouldn't be open generic, so we don't need a generic context. var ctor = module.ResolveMethod(attribute.Constructor, new GenericContext()); var type = ctor.DeclaringType; if (IgnoreAttribute(type, target)) { continue; } Add(new CustomAttribute(module, ctor, handle)); } } bool IgnoreAttribute(IType attributeType, SymbolKind target) { if (attributeType.DeclaringType != null || attributeType.TypeParameterCount != 0) return false; return IgnoreAttribute(new TopLevelTypeName(attributeType.Namespace, attributeType.Name), target); } internal bool IgnoreAttribute(TopLevelTypeName attributeType, SymbolKind target) { switch (attributeType.Namespace) { case "System.Runtime.CompilerServices": var options = module.TypeSystemOptions; switch (attributeType.Name) { case "DynamicAttribute": return (options & TypeSystemOptions.Dynamic) != 0; case "NativeIntegerAttribute": return (options & TypeSystemOptions.NativeIntegers) != 0; case "TupleElementNamesAttribute": return (options & TypeSystemOptions.Tuple) != 0; case "ExtensionAttribute": return (options & TypeSystemOptions.ExtensionMethods) != 0; case "DecimalConstantAttribute": return (options & TypeSystemOptions.DecimalConstants) != 0 && (target == SymbolKind.Field || target == SymbolKind.Parameter); case "IsReadOnlyAttribute": switch (target) { case SymbolKind.TypeDefinition: case SymbolKind.Parameter: return (options & TypeSystemOptions.ReadOnlyStructsAndParameters) != 0; case SymbolKind.Method: case SymbolKind.Accessor: return (options & TypeSystemOptions.ReadOnlyMethods) != 0; case SymbolKind.ReturnType: case SymbolKind.Property: case SymbolKind.Indexer: case SymbolKind.Field: return true; // "ref readonly" is currently always active default: return false; } case "IsByRefLikeAttribute": return (options & TypeSystemOptions.RefStructs) != 0 && target == SymbolKind.TypeDefinition; case "IsUnmanagedAttribute": return (options & TypeSystemOptions.UnmanagedConstraints) != 0 && target == SymbolKind.TypeParameter; case "NullableAttribute": return (options & TypeSystemOptions.NullabilityAnnotations) != 0; case "NullableContextAttribute": return (options & TypeSystemOptions.NullabilityAnnotations) != 0 && (target == SymbolKind.TypeDefinition || IsMethodLike(target)); case "ScopedRefAttribute": return (options & TypeSystemOptions.ScopedRef) != 0 && (target == SymbolKind.Parameter); default: return false; } case "System": return attributeType.Name == "ParamArrayAttribute" && target == SymbolKind.Parameter; default: return false; } } internal bool HasAttribute(MetadataReader metadata, CustomAttributeHandleCollection customAttributes, KnownAttribute attribute, SymbolKind symbolKind) { Debug.Assert(attribute.IsCustomAttribute()); foreach (var h in customAttributes) { var attr = metadata.GetCustomAttribute(h); if (attr.IsKnownAttribute(metadata, attribute)) { return !IgnoreAttribute(attribute.GetTypeName(), symbolKind); } } return false; } internal IAttribute GetAttribute(MetadataReader metadata, CustomAttributeHandleCollection customAttributes, KnownAttribute attribute, SymbolKind symbolKind) { Debug.Assert(attribute.IsCustomAttribute()); foreach (var h in customAttributes) { var attr = metadata.GetCustomAttribute(h); if (attr.IsKnownAttribute(metadata, attribute) && !IgnoreAttribute(attribute.GetTypeName(), symbolKind)) { // Attribute types shouldn't be open generic, so we don't need a generic context. var ctor = module.ResolveMethod(attr.Constructor, new GenericContext()); return new CustomAttribute(module, ctor, h); } } return null; } static bool IsMethodLike(SymbolKind kind) { return kind switch { SymbolKind.Method => true, SymbolKind.Operator => true, SymbolKind.Constructor => true, SymbolKind.Destructor => true, SymbolKind.Accessor => true, _ => false }; } #endregion #region Security Attributes public void AddSecurityAttributes(DeclarativeSecurityAttributeHandleCollection securityDeclarations) { var metadata = module.metadata; foreach (var secDecl in securityDeclarations) { if (secDecl.IsNil) continue; try { AddSecurityAttributes(metadata.GetDeclarativeSecurityAttribute(secDecl)); } catch (EnumUnderlyingTypeResolveException) { // ignore resolve errors } catch (BadImageFormatException) { // ignore invalid security declarations } } } public void AddSecurityAttributes(DeclarativeSecurityAttribute secDecl) { var securityActionType = module.Compilation.FindType(new TopLevelTypeName("System.Security.Permissions", "SecurityAction")); var securityAction = new CustomAttributeTypedArgument<IType>(securityActionType, (int)secDecl.Action); var metadata = module.metadata; var reader = metadata.GetBlobReader(secDecl.PermissionSet); if (reader.ReadByte() == '.') { // binary attribute int attributeCount = reader.ReadCompressedInteger(); for (int i = 0; i < attributeCount; i++) { Add(ReadBinarySecurityAttribute(ref reader, securityAction)); } } else { // for backward compatibility with .NET 1.0: XML-encoded attribute reader.Reset(); Add(ReadXmlSecurityAttribute(ref reader, securityAction)); } } private IAttribute ReadXmlSecurityAttribute(ref SRM.BlobReader reader, CustomAttributeTypedArgument<IType> securityAction) { string xml = reader.ReadUTF16(reader.RemainingBytes); var b = new AttributeBuilder(module, KnownAttribute.PermissionSet); b.AddFixedArg(securityAction); b.AddNamedArg("XML", KnownTypeCode.String, xml); return b.Build(); } private IAttribute ReadBinarySecurityAttribute(ref SRM.BlobReader reader, CustomAttributeTypedArgument<IType> securityAction) { string attributeTypeName = reader.ReadSerializedString(); IType attributeType = module.TypeProvider.GetTypeFromSerializedName(attributeTypeName); reader.ReadCompressedInteger(); // ?? // The specification seems to be incorrect here, so I'm using the logic from Cecil instead. int numNamed = reader.ReadCompressedInteger(); var decoder = new Metadata.CustomAttributeDecoder<IType>(module.TypeProvider, module.metadata); var namedArgs = decoder.DecodeNamedArguments(ref reader, numNamed); return new DefaultAttribute( attributeType, fixedArguments: ImmutableArray.Create(securityAction), namedArguments: namedArgs); } #endregion public IAttribute[] Build() { if (attributes.Count == 0) return Empty<IAttribute>.Array; else return attributes.ToArray(); } } struct AttributeBuilder { readonly ICompilation compilation; readonly IType attributeType; ImmutableArray<CustomAttributeTypedArgument<IType>>.Builder fixedArgs; ImmutableArray<CustomAttributeNamedArgument<IType>>.Builder namedArgs; public AttributeBuilder(MetadataModule module, KnownAttribute attributeType) : this(module, module.GetAttributeType(attributeType)) { } public AttributeBuilder(MetadataModule module, IType attributeType) { this.compilation = module.Compilation; this.attributeType = attributeType; this.fixedArgs = ImmutableArray.CreateBuilder<CustomAttributeTypedArgument<IType>>(); this.namedArgs = ImmutableArray.CreateBuilder<CustomAttributeNamedArgument<IType>>(); } public void AddFixedArg(CustomAttributeTypedArgument<IType> arg) { fixedArgs.Add(arg); } public void AddFixedArg(KnownTypeCode type, object value) { AddFixedArg(compilation.FindType(type), value); } public void AddFixedArg(TopLevelTypeName type, object value) { AddFixedArg(compilation.FindType(type), value); } public void AddFixedArg(IType type, object value) { fixedArgs.Add(new CustomAttributeTypedArgument<IType>(type, value)); } public void AddNamedArg(string name, KnownTypeCode type, object value) { AddNamedArg(name, compilation.FindType(type), value); } public void AddNamedArg(string name, TopLevelTypeName type, object value) { AddNamedArg(name, compilation.FindType(type), value); } public void AddNamedArg(string name, IType type, object value) { CustomAttributeNamedArgumentKind kind; if (attributeType.GetFields(f => f.Name == name, GetMemberOptions.ReturnMemberDefinitions).Any()) kind = CustomAttributeNamedArgumentKind.Field; else kind = CustomAttributeNamedArgumentKind.Property; namedArgs.Add(new CustomAttributeNamedArgument<IType>(name, kind, type, value)); } public IAttribute Build() { return new DefaultAttribute(attributeType, fixedArgs.ToImmutable(), namedArgs.ToImmutable()); } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs", "repo_id": "ILSpy", "token_count": 5549 }
242
// Copyright (c) 2019 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.TypeSystem.Implementation { /// <summary> /// A local function has zero or more compiler-generated parameters added at the end. /// </summary> class LocalFunctionMethod : IMethod { readonly IMethod baseMethod; public LocalFunctionMethod(IMethod baseMethod, string name, bool isStaticLocalFunction, int numberOfCompilerGeneratedParameters, int numberOfCompilerGeneratedTypeParameters) { if (baseMethod == null) throw new ArgumentNullException(nameof(baseMethod)); this.baseMethod = baseMethod; this.Name = name; this.IsStaticLocalFunction = isStaticLocalFunction; this.NumberOfCompilerGeneratedParameters = numberOfCompilerGeneratedParameters; this.NumberOfCompilerGeneratedTypeParameters = numberOfCompilerGeneratedTypeParameters; } public bool Equals(IMember obj, TypeVisitor typeNormalization) { if (!(obj is LocalFunctionMethod other)) return false; return baseMethod.Equals(other.baseMethod, typeNormalization) && NumberOfCompilerGeneratedParameters == other.NumberOfCompilerGeneratedParameters && NumberOfCompilerGeneratedTypeParameters == other.NumberOfCompilerGeneratedTypeParameters && IsStaticLocalFunction == other.IsStaticLocalFunction; } public override bool Equals(object obj) { if (!(obj is LocalFunctionMethod other)) return false; return baseMethod.Equals(other.baseMethod) && NumberOfCompilerGeneratedParameters == other.NumberOfCompilerGeneratedParameters && NumberOfCompilerGeneratedTypeParameters == other.NumberOfCompilerGeneratedTypeParameters && IsStaticLocalFunction == other.IsStaticLocalFunction; } public override int GetHashCode() { return baseMethod.GetHashCode(); } public override string ToString() { return string.Format("[LocalFunctionMethod: ReducedFrom={0}, Name={1}, NumberOfGeneratedParameters={2}, NumberOfCompilerGeneratedTypeParameters={3}, IsStaticLocalFunction={4}]", ReducedFrom, Name, NumberOfCompilerGeneratedParameters, NumberOfCompilerGeneratedTypeParameters, IsStaticLocalFunction); } internal int NumberOfCompilerGeneratedParameters { get; } internal int NumberOfCompilerGeneratedTypeParameters { get; } internal bool IsStaticLocalFunction { get; } public IMember MemberDefinition => this; public IType ReturnType => baseMethod.ReturnType; IEnumerable<IMember> IMember.ExplicitlyImplementedInterfaceMembers => baseMethod.ExplicitlyImplementedInterfaceMembers; bool IMember.IsExplicitInterfaceImplementation => baseMethod.IsExplicitInterfaceImplementation; public bool IsVirtual => baseMethod.IsVirtual; public bool IsOverride => baseMethod.IsOverride; public bool IsOverridable => baseMethod.IsOverridable; public TypeParameterSubstitution Substitution => baseMethod.Substitution; public IMethod Specialize(TypeParameterSubstitution substitution) { return new LocalFunctionMethod( baseMethod.Specialize(substitution), Name, IsStaticLocalFunction, NumberOfCompilerGeneratedParameters, NumberOfCompilerGeneratedTypeParameters); } IMember IMember.Specialize(TypeParameterSubstitution substitution) { return Specialize(substitution); } public bool IsExtensionMethod => baseMethod.IsExtensionMethod; public bool IsLocalFunction => true; public bool IsConstructor => baseMethod.IsConstructor; public bool IsDestructor => baseMethod.IsDestructor; public bool IsOperator => baseMethod.IsOperator; public bool HasBody => baseMethod.HasBody; public bool IsAccessor => baseMethod.IsAccessor; public IMember AccessorOwner => baseMethod.AccessorOwner; public MethodSemanticsAttributes AccessorKind => baseMethod.AccessorKind; public IMethod ReducedFrom => baseMethod; List<ITypeParameter> typeParameters; public IReadOnlyList<ITypeParameter> TypeParameters { get { if (typeParameters == null) typeParameters = new List<ITypeParameter>(baseMethod.TypeParameters.Skip(NumberOfCompilerGeneratedTypeParameters)); return typeParameters; } } List<IType> typeArguments; public IReadOnlyList<IType> TypeArguments { get { if (typeArguments == null) typeArguments = new List<IType>(baseMethod.TypeArguments.Skip(NumberOfCompilerGeneratedTypeParameters)); return typeArguments; } } List<IParameter> parameters; public IReadOnlyList<IParameter> Parameters { get { if (parameters == null) parameters = new List<IParameter>(baseMethod.Parameters.SkipLast(NumberOfCompilerGeneratedParameters)); return parameters; } } public System.Reflection.Metadata.EntityHandle MetadataToken => baseMethod.MetadataToken; public SymbolKind SymbolKind => baseMethod.SymbolKind; public ITypeDefinition DeclaringTypeDefinition => baseMethod.DeclaringTypeDefinition; public IType DeclaringType => baseMethod.DeclaringType; public IModule ParentModule => baseMethod.ParentModule; IEnumerable<IAttribute> IEntity.GetAttributes() => baseMethod.GetAttributes(); bool IEntity.HasAttribute(KnownAttribute attribute) => baseMethod.HasAttribute(attribute); IAttribute IEntity.GetAttribute(KnownAttribute attribute) => baseMethod.GetAttribute(attribute); IEnumerable<IAttribute> IMethod.GetReturnTypeAttributes() => baseMethod.GetReturnTypeAttributes(); bool IMethod.ReturnTypeIsRefReadOnly => baseMethod.ReturnTypeIsRefReadOnly; bool IMethod.ThisIsRefReadOnly => baseMethod.ThisIsRefReadOnly; bool IMethod.IsInitOnly => baseMethod.IsInitOnly; /// <summary> /// We consider local functions as always static, because they do not have a "this parameter". /// Even local functions in instance methods capture this. /// </summary> public bool IsStatic => true; public bool IsAbstract => baseMethod.IsAbstract; public bool IsSealed => baseMethod.IsSealed; public Accessibility Accessibility => baseMethod.Accessibility; public string FullName => Name; public string Name { get; set; } public string ReflectionName => baseMethod.ReflectionName; public string Namespace => baseMethod.Namespace; public ICompilation Compilation => baseMethod.Compilation; } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/LocalFunctionMethod.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/LocalFunctionMethod.cs", "repo_id": "ILSpy", "token_count": 2147 }
243
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.TypeSystem.Implementation { /// <summary> /// Represents a specialized IField (field after type substitution). /// </summary> public class SpecializedField : SpecializedMember, IField { internal static IField Create(IField fieldDefinition, TypeParameterSubstitution substitution) { if (TypeParameterSubstitution.Identity.Equals(substitution) || fieldDefinition.DeclaringType.TypeParameterCount == 0) { return fieldDefinition; } if (substitution.MethodTypeArguments != null && substitution.MethodTypeArguments.Count > 0) substitution = new TypeParameterSubstitution(substitution.ClassTypeArguments, EmptyList<IType>.Instance); return new SpecializedField(fieldDefinition, substitution); } readonly IField fieldDefinition; public SpecializedField(IField fieldDefinition, TypeParameterSubstitution substitution) : base(fieldDefinition) { this.fieldDefinition = fieldDefinition; AddSubstitution(substitution); } public bool IsReadOnly => fieldDefinition.IsReadOnly; public bool ReturnTypeIsRefReadOnly => fieldDefinition.ReturnTypeIsRefReadOnly; public bool IsVolatile => fieldDefinition.IsVolatile; IType IVariable.Type { get { return this.ReturnType; } } public bool IsConst { get { return fieldDefinition.IsConst; } } public object GetConstantValue(bool throwOnInvalidMetadata) { return fieldDefinition.GetConstantValue(throwOnInvalidMetadata); } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedField.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedField.cs", "repo_id": "ILSpy", "token_count": 760 }
244
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.Semantics; using ICSharpCode.Decompiler.TypeSystem.Implementation; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// Contains extension methods for the type system. /// </summary> public static class TypeSystemExtensions { #region GetAllBaseTypes /// <summary> /// Gets all base types. /// </summary> /// <remarks>This is the reflexive and transitive closure of <see cref="IType.DirectBaseTypes"/>. /// Note that this method does not return all supertypes - doing so is impossible due to contravariance /// (and undesirable for covariance as the list could become very large). /// /// The output is ordered so that base types occur before derived types. /// </remarks> public static IEnumerable<IType> GetAllBaseTypes(this IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); BaseTypeCollector collector = new BaseTypeCollector(); collector.CollectBaseTypes(type); return collector; } /// <summary> /// Gets all non-interface base types. /// </summary> /// <remarks> /// When <paramref name="type"/> is an interface, this method will also return base interfaces (return same output as GetAllBaseTypes()). /// /// The output is ordered so that base types occur before derived types. /// </remarks> public static IEnumerable<IType> GetNonInterfaceBaseTypes(this IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); BaseTypeCollector collector = new BaseTypeCollector(); collector.SkipImplementedInterfaces = true; collector.CollectBaseTypes(type); return collector; } #endregion #region GetAllBaseTypeDefinitions /// <summary> /// Gets all base type definitions. /// The output is ordered so that base types occur before derived types. /// </summary> /// <remarks> /// This is equivalent to type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct(). /// </remarks> public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); return type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct(); } /// <summary> /// Gets whether this type definition is derived from the base type definition. /// </summary> public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType) { if (type == null) throw new ArgumentNullException(nameof(type)); if (baseType == null) return false; if (type.Compilation != baseType.Compilation) { throw new InvalidOperationException("Both arguments to IsDerivedFrom() must be from the same compilation."); } return type.GetAllBaseTypeDefinitions().Contains(baseType); } /// <summary> /// Gets whether this type definition is derived from a given known type. /// </summary> public static bool IsDerivedFrom(this ITypeDefinition type, KnownTypeCode baseType) { if (type == null) throw new ArgumentNullException(nameof(type)); if (baseType == KnownTypeCode.None) return false; return IsDerivedFrom(type, type.Compilation.FindType(baseType).GetDefinition()); } #endregion #region GetDeclaringTypeDefinitionsOrThis /// <summary> /// Returns all declaring type definitions of this type definition. /// The output is ordered so that inner types occur before outer types. /// </summary> public static IEnumerable<ITypeDefinition> GetDeclaringTypeDefinitions(this ITypeDefinition definition) { if (definition == null) { throw new ArgumentNullException(nameof(definition)); } while (definition != null) { yield return definition; definition = definition.DeclaringTypeDefinition; } } #endregion #region IsOpen / IsUnbound / IsUnmanagedType / IsKnownType sealed class TypeClassificationVisitor : TypeVisitor { internal bool isOpen; internal IEntity typeParameterOwner; int typeParameterOwnerNestingLevel; public override IType VisitTypeParameter(ITypeParameter type) { isOpen = true; // If both classes and methods, or different classes (nested types) // are involved, find the most specific one int newNestingLevel = GetNestingLevel(type.Owner); if (newNestingLevel > typeParameterOwnerNestingLevel) { typeParameterOwner = type.Owner; typeParameterOwnerNestingLevel = newNestingLevel; } return base.VisitTypeParameter(type); } static int GetNestingLevel(IEntity entity) { int level = 0; while (entity != null) { level++; entity = entity.DeclaringTypeDefinition; } return level; } } /// <summary> /// Gets whether the type is an open type (contains type parameters). /// </summary> /// <example> /// <code> /// class X&lt;T&gt; { /// List&lt;T&gt; open; /// X&lt;X&lt;T[]&gt;&gt; open; /// X&lt;string&gt; closed; /// int closed; /// } /// </code> /// </example> public static bool IsOpen(this IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); TypeClassificationVisitor v = new TypeClassificationVisitor(); type.AcceptVisitor(v); return v.isOpen; } /// <summary> /// Gets the entity that owns the type parameters occurring in the specified type. /// If both class and method type parameters are present, the method is returned. /// Returns null if the specified type is closed. /// </summary> /// <seealso cref="IsOpen"/> static IEntity GetTypeParameterOwner(IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); TypeClassificationVisitor v = new TypeClassificationVisitor(); type.AcceptVisitor(v); return v.typeParameterOwner; } /// <summary> /// Gets whether the type is unbound (is a generic type, but no type arguments were provided). /// </summary> /// <remarks> /// In "<c>typeof(List&lt;Dictionary&lt;,&gt;&gt;)</c>", only the Dictionary is unbound, the List is considered /// bound despite containing an unbound type. /// This method returns false for partially parameterized types (<c>Dictionary&lt;string, &gt;</c>). /// </remarks> public static bool IsUnbound(this IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); return (type is ITypeDefinition || type is UnknownType) && type.TypeParameterCount > 0; } /// <summary> /// Gets whether the type is considered unmanaged. /// </summary> /// <remarks> /// The C# 6.0 spec lists the following criteria: An unmanaged type is one of the following /// * sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool /// * any enum type /// * any pointer type /// * any user-defined struct type that is not a constructed (= generic) type and contains fields of unmanaged types only. /// /// C# 8.0 removes the restriction that constructed (= generic) types are not considered unmanaged types. /// </remarks> public static bool IsUnmanagedType(this IType type, bool allowGenerics) { HashSet<IType> types = null; return IsUnmanagedTypeInternal(type); bool IsUnmanagedTypeInternal(IType type) { if (type.Kind is TypeKind.Enum or TypeKind.Pointer or TypeKind.FunctionPointer or TypeKind.NInt or TypeKind.NUInt) { return true; } if (type is ITypeParameter tp) { return tp.HasUnmanagedConstraint; } var def = type.GetDefinition(); if (def == null) { return false; } switch (def.KnownTypeCode) { case KnownTypeCode.Void: case KnownTypeCode.Boolean: case KnownTypeCode.Char: case KnownTypeCode.SByte: case KnownTypeCode.Byte: case KnownTypeCode.Int16: case KnownTypeCode.UInt16: case KnownTypeCode.Int32: case KnownTypeCode.UInt32: case KnownTypeCode.Int64: case KnownTypeCode.UInt64: case KnownTypeCode.Decimal: case KnownTypeCode.Single: case KnownTypeCode.Double: case KnownTypeCode.IntPtr: case KnownTypeCode.UIntPtr: case KnownTypeCode.TypedReference: //case KnownTypeCode.ArgIterator: //case KnownTypeCode.RuntimeArgumentHandle: return true; } if (type.Kind == TypeKind.Struct) { if (!allowGenerics && def.TypeParameterCount > 0) { return false; } if (types == null) { types = new HashSet<IType>(); } types.Add(type); foreach (var f in type.GetFields(f => !f.IsStatic)) { if (types.Contains(f.Type)) { types.Remove(type); return false; } if (!IsUnmanagedTypeInternal(f.Type)) { types.Remove(type); return false; } } types.Remove(type); return true; } return false; } } /// <summary> /// Gets whether the type is the specified known type. /// For generic known types, this returns true for any parameterization of the type (and also for the definition itself). /// </summary> public static bool IsKnownType(this IType type, KnownTypeCode knownType) { var def = type.GetDefinition(); return def != null && def.KnownTypeCode == knownType; } /// <summary> /// Gets whether the type is the specified known type. /// For generic known types, this returns true for any parameterization of the type (and also for the definition itself). /// </summary> internal static bool IsKnownType(this IType type, KnownAttribute knownType) { var def = type.GetDefinition(); return def != null && def.FullTypeName.IsKnownType(knownType); } public static bool IsKnownType(this FullTypeName typeName, KnownTypeCode knownType) { return typeName == KnownTypeReference.Get(knownType).TypeName; } public static bool IsKnownType(this TopLevelTypeName typeName, KnownTypeCode knownType) { return typeName == KnownTypeReference.Get(knownType).TypeName; } internal static bool IsKnownType(this FullTypeName typeName, KnownAttribute knownType) { return typeName == knownType.GetTypeName(); } internal static bool IsKnownType(this TopLevelTypeName typeName, KnownAttribute knownType) { return typeName == knownType.GetTypeName(); } #endregion #region GetDelegateInvokeMethod /// <summary> /// Gets the invoke method for a delegate type. /// </summary> /// <remarks> /// Returns null if the type is not a delegate type; or if the invoke method could not be found. /// </remarks> public static IMethod GetDelegateInvokeMethod(this IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); if (type.Kind == TypeKind.Delegate) return type.GetMethods(m => m.Name == "Invoke", GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault(); else return null; } #endregion public static IType SkipModifiers(this IType ty) { while (ty is ModifiedType mt) { ty = mt.ElementType; } return ty; } public static IType UnwrapByRef(this IType type) { if (type is ByReferenceType byRef) { type = byRef.ElementType; } return type; } public static bool HasReadonlyModifier(this IMethod accessor) { return accessor.ThisIsRefReadOnly && accessor.DeclaringTypeDefinition?.IsReadOnly == false; } public static bool IsAnyPointer(this TypeKind typeKind) { return typeKind switch { TypeKind.Pointer => true, TypeKind.FunctionPointer => true, _ => false }; } #region GetType/Member /// <summary> /// Gets all type definitions in the compilation. /// This may include types from referenced assemblies that are not accessible in the main assembly. /// </summary> public static IEnumerable<ITypeDefinition> GetAllTypeDefinitions(this ICompilation compilation) { return compilation.Modules.SelectMany(a => a.TypeDefinitions); } /// <summary> /// Gets all top level type definitions in the compilation. /// This may include types from referenced assemblies that are not accessible in the main assembly. /// </summary> public static IEnumerable<ITypeDefinition> GetTopLevelTypeDefinitions(this ICompilation compilation) { return compilation.Modules.SelectMany(a => a.TopLevelTypeDefinitions); } #endregion #region Resolve on collections public static IReadOnlyList<IType> Resolve(this IList<ITypeReference> typeReferences, ITypeResolveContext context) { if (typeReferences == null) throw new ArgumentNullException(nameof(typeReferences)); if (typeReferences.Count == 0) return EmptyList<IType>.Instance; else return new ProjectedList<ITypeResolveContext, ITypeReference, IType>(context, typeReferences, (c, t) => t.Resolve(c)); } // There is intentionally no Resolve() overload for IList<IMemberReference>: the resulting IList<Member> would // contains nulls when there are resolve errors. #endregion #region IAssembly.GetTypeDefinition() /// <summary> /// Retrieves the specified type in this compilation. /// Returns an <see cref="UnknownType"/> if the type cannot be found in this compilation. /// </summary> /// <remarks> /// There can be multiple types with the same full name in a compilation, as a /// full type name is only unique per assembly. /// If there are multiple possible matches, this method will return just one of them. /// When possible, use <see cref="IModule.GetTypeDefinition"/> instead to /// retrieve a type from a specific assembly. /// </remarks> public static IType FindType(this ICompilation compilation, FullTypeName fullTypeName) { if (compilation == null) throw new ArgumentNullException(nameof(compilation)); foreach (IModule asm in compilation.Modules) { ITypeDefinition def = asm.GetTypeDefinition(fullTypeName); if (def != null) return def; } return new UnknownType(fullTypeName); } /// <summary> /// Gets the type definition for the specified unresolved type. /// Returns null if the unresolved type does not belong to this assembly. /// </summary> public static ITypeDefinition GetTypeDefinition(this IModule module, FullTypeName fullTypeName) { if (module == null) throw new ArgumentNullException("assembly"); TopLevelTypeName topLevelTypeName = fullTypeName.TopLevelTypeName; ITypeDefinition typeDef = module.GetTypeDefinition(topLevelTypeName); if (typeDef == null) return null; int typeParameterCount = topLevelTypeName.TypeParameterCount; for (int i = 0; i < fullTypeName.NestingLevel; i++) { string name = fullTypeName.GetNestedTypeName(i); typeParameterCount += fullTypeName.GetNestedTypeAdditionalTypeParameterCount(i); typeDef = FindNestedType(typeDef, name, typeParameterCount); if (typeDef == null) break; } return typeDef; } static ITypeDefinition FindNestedType(ITypeDefinition typeDef, string name, int typeParameterCount) { foreach (var nestedType in typeDef.NestedTypes) { if (nestedType.Name == name && nestedType.TypeParameterCount == typeParameterCount) return nestedType; } return null; } #endregion #region IEntity.GetAttribute /// <summary> /// Gets whether the entity has an attribute of the specified attribute type. /// </summary> /// <param name="entity">The entity on which the attributes are declared.</param> /// <param name="attributeType">The attribute type to look for.</param> /// <param name="inherit"> /// Specifies whether attributes inherited from base classes and base members /// (if the given <paramref name="entity"/> in an <c>override</c>) /// should be returned. /// </param> public static bool HasAttribute(this IEntity entity, KnownAttribute attributeType, bool inherit) { if (!inherit) return entity.HasAttribute(attributeType); return GetAttribute(entity, attributeType, inherit) != null; } /// <summary> /// Gets the attribute of the specified attribute type. /// </summary> /// <param name="entity">The entity on which the attributes are declared.</param> /// <param name="attributeType">The attribute type to look for.</param> /// <param name="inherit"> /// Specifies whether attributes inherited from base classes and base members /// (if the given <paramref name="entity"/> in an <c>override</c>) /// should be returned. /// </param> /// <returns> /// Returns the attribute that was found; or <c>null</c> if none was found. /// If inherit is true, an from the entity itself will be returned if possible; /// and the base entity will only be searched if none exists. /// </returns> public static IAttribute GetAttribute(this IEntity entity, KnownAttribute attributeType, bool inherit) { if (inherit) { if (entity is ITypeDefinition td) { return InheritanceHelper.GetAttribute(td, attributeType); } else if (entity is IMember m) { return InheritanceHelper.GetAttribute(m, attributeType); } else { throw new NotSupportedException("Unknown entity type"); } } else { return entity.GetAttribute(attributeType); } } /// <summary> /// Gets the attributes on the entity. /// </summary> /// <param name="entity">The entity on which the attributes are declared.</param> /// <param name="inherit"> /// Specifies whether attributes inherited from base classes and base members /// (if the given <paramref name="entity"/> in an <c>override</c>) /// should be returned. /// </param> /// <returns> /// Returns the list of attributes that were found. /// If inherit is true, attributes from the entity itself are returned first; /// followed by attributes inherited from the base entity. /// </returns> public static IEnumerable<IAttribute> GetAttributes(this IEntity entity, bool inherit) { if (inherit) { if (entity is ITypeDefinition td) { return InheritanceHelper.GetAttributes(td); } else if (entity is IMember m) { return InheritanceHelper.GetAttributes(m); } else { throw new NotSupportedException("Unknown entity type"); } } else { return entity.GetAttributes(); } } #endregion #region IParameter.GetAttribute /// <summary> /// Gets whether the parameter has an attribute of the specified attribute type. /// </summary> /// <param name="parameter">The parameter on which the attributes are declared.</param> /// <param name="attributeType">The attribute type to look for.</param> public static bool HasAttribute(this IParameter parameter, KnownAttribute attributeType) { return GetAttribute(parameter, attributeType) != null; } /// <summary> /// Gets the attribute of the specified attribute type. /// </summary> /// <param name="parameter">The parameter on which the attributes are declared.</param> /// <param name="attributeType">The attribute type to look for.</param> /// <returns> /// Returns the attribute that was found; or <c>null</c> if none was found. /// </returns> public static IAttribute GetAttribute(this IParameter parameter, KnownAttribute attributeType) { return parameter.GetAttributes().FirstOrDefault(a => a.AttributeType.IsKnownType(attributeType)); } #endregion #region IAssembly.GetTypeDefinition(string,string,int) /// <summary> /// Gets the type definition for a top-level type. /// </summary> /// <remarks>This method uses ordinal name comparison, not the compilation's name comparer.</remarks> public static ITypeDefinition GetTypeDefinition(this IModule module, string namespaceName, string name, int typeParameterCount = 0) { if (module == null) throw new ArgumentNullException("assembly"); return module.GetTypeDefinition(new TopLevelTypeName(namespaceName, name, typeParameterCount)); } #endregion #region ResolveResult public static ISymbol GetSymbol(this ResolveResult rr) { if (rr is LocalResolveResult) { return ((LocalResolveResult)rr).Variable; } else if (rr is MemberResolveResult) { return ((MemberResolveResult)rr).Member; } else if (rr is TypeResolveResult) { return ((TypeResolveResult)rr).Type.GetDefinition(); } else if (rr is ConversionResolveResult) { return ((ConversionResolveResult)rr).Input.GetSymbol(); } return null; } #endregion public static IType GetElementTypeFromIEnumerable(this IType collectionType, ICompilation compilation, bool allowIEnumerator, out bool? isGeneric) { bool foundNonGenericIEnumerable = false; foreach (IType baseType in collectionType.GetAllBaseTypes()) { ITypeDefinition baseTypeDef = baseType.GetDefinition(); if (baseTypeDef != null) { KnownTypeCode typeCode = baseTypeDef.KnownTypeCode; if (typeCode == KnownTypeCode.IEnumerableOfT || (allowIEnumerator && typeCode == KnownTypeCode.IEnumeratorOfT)) { ParameterizedType pt = baseType as ParameterizedType; if (pt != null) { isGeneric = true; return pt.GetTypeArgument(0); } } if (typeCode == KnownTypeCode.IEnumerable || (allowIEnumerator && typeCode == KnownTypeCode.IEnumerator)) foundNonGenericIEnumerable = true; } } // System.Collections.IEnumerable found in type hierarchy -> Object is element type. if (foundNonGenericIEnumerable) { isGeneric = false; return compilation.FindType(KnownTypeCode.Object); } isGeneric = null; return SpecialType.UnknownType; } public static bool FullNameIs(this IMember member, string type, string name) { return member.Name == name && member.DeclaringType?.FullName == type; } public static KnownAttribute IsBuiltinAttribute(this ITypeDefinition type) { return KnownAttributes.IsKnownAttributeType(type); } public static IType WithoutNullability(this IType type) { return type.ChangeNullability(Nullability.Oblivious); } public static bool IsDirectImportOf(this ITypeDefinition type, IModule module) { var moduleReference = type.ParentModule; foreach (var asmRef in module.PEFile.AssemblyReferences) { if (asmRef.FullName == moduleReference.FullAssemblyName) return true; if (asmRef.Name == "netstandard" && asmRef.GetPublicKeyToken() != null) { var referencedModule = module.Compilation.FindModuleByReference(asmRef); if (referencedModule != null && !referencedModule.PEFile.GetTypeForwarder(type.FullTypeName).IsNil) return true; } } return false; } public static IModule FindModuleByReference(this ICompilation compilation, IAssemblyReference assemblyName) { foreach (var module in compilation.Modules) { if (string.Equals(module.FullAssemblyName, assemblyName.FullName, StringComparison.OrdinalIgnoreCase)) { return module; } } foreach (var module in compilation.Modules) { if (string.Equals(module.Name, assemblyName.Name, StringComparison.OrdinalIgnoreCase)) { return module; } } return null; } /// <summary> /// When given a generic type definition, returns the self-parameterized type /// (i.e. the type of "this" within the type definition). /// When given a non-generic type definition, returns that definition unchanged. /// </summary> public static IType AsParameterizedType(this ITypeDefinition td) { if (td.TypeParameterCount == 0) { return td; } else { return new ParameterizedType(td, td.TypeArguments); } } public static INamespace GetNamespaceByFullName(this ICompilation compilation, string name) { if (string.IsNullOrEmpty(name)) return compilation.RootNamespace; var parts = name.Split('.'); var ns = compilation.RootNamespace; foreach (var part in parts) { var child = ns.GetChildNamespace(part); if (child == null) return null; ns = child; } return ns; } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs", "repo_id": "ILSpy", "token_count": 8597 }
245
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System { /// <summary>Represent a type can be used to index a collection either from the start or the end.</summary> /// <remarks> /// Index is used by the C# compiler to support the new index syntax /// <code> /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ; /// int lastElement = someArray[^1]; // lastElement = 5 /// </code> /// </remarks> #if SYSTEM_PRIVATE_CORELIB public #else internal #endif readonly struct Index : IEquatable<Index> { private readonly int _value; /// <summary>Construct an Index using a value and indicating if the index is from the start or from the end.</summary> /// <param name="value">The index value. it has to be zero or positive number.</param> /// <param name="fromEnd">Indicating if the index is from the start or from the end.</param> /// <remarks> /// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Index(int value, bool fromEnd = false) { if (value < 0) { ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } if (fromEnd) _value = ~value; else _value = value; } // The following private constructors mainly created for perf reason to avoid the checks private Index(int value) { _value = value; } /// <summary>Create an Index pointing at first element.</summary> public static Index Start => new Index(0); /// <summary>Create an Index pointing at beyond last element.</summary> public static Index End => new Index(~0); /// <summary>Create an Index from the start at the position indicated by the value.</summary> /// <param name="value">The index value from the start.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromStart(int value) { if (value < 0) { ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return new Index(value); } /// <summary>Create an Index from the end at the position indicated by the value.</summary> /// <param name="value">The index value from the end.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromEnd(int value) { if (value < 0) { ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return new Index(~value); } /// <summary>Returns the index value.</summary> public int Value { get { if (_value < 0) return ~_value; else return _value; } } /// <summary>Indicates whether the index is from the start or the end.</summary> public bool IsFromEnd => _value < 0; /// <summary>Calculate the offset from the start using the giving collection length.</summary> /// <param name="length">The length of the collection that the Index will be used with. length has to be a positive value</param> /// <remarks> /// For performance reason, we don't validate the input length parameter and the returned offset value against negative values. /// we don't validate either the returned offset is greater than the input length. /// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and /// then used to index a collection will get out of range exception which will be same affect as the validation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetOffset(int length) { int offset = _value; if (IsFromEnd) { // offset = length - (~value) // offset = length + (~(~value) + 1) // offset = length + value + 1 offset += length + 1; } return offset; } /// <summary>Indicates whether the current Index object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> public override bool Equals([NotNullWhen(true)] object? value) => value is Index && _value == ((Index)value)._value; /// <summary>Indicates whether the current Index object is equal to another Index object.</summary> /// <param name="other">An object to compare with this object</param> public bool Equals(Index other) => _value == other._value; /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() => _value; /// <summary>Converts integer number to an Index.</summary> public static implicit operator Index(int value) => FromStart(value); /// <summary>Converts the value of the current Index object to its equivalent string representation.</summary> public override string ToString() { if (IsFromEnd) return ToStringFromEnd(); return ((uint)Value).ToString(); } private static void ThrowValueArgumentOutOfRange_NeedNonNegNumException() { #if SYSTEM_PRIVATE_CORELIB throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); #else throw new ArgumentOutOfRangeException("value", "value must be non-negative"); #endif } private string ToStringFromEnd() { #if (!NETSTANDARD2_0 && !NETFRAMEWORK) Span<char> span = stackalloc char[11]; // 1 for ^ and 10 for longest possible uint value bool formatted = ((uint)Value).TryFormat(span.Slice(1), out int charsWritten); Debug.Assert(formatted); span[0] = '^'; return new string(span.Slice(0, charsWritten + 1)); #else return '^' + Value.ToString(); #endif } } }
ILSpy/ICSharpCode.Decompiler/Util/Index.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Util/Index.cs", "repo_id": "ILSpy", "token_count": 1834 }
246