text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
namespace DotRecast.Recast { public interface IRecastBuilderProgressListener { void OnProgress(int completed, int total); } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/IRecastBuilderProgressListener.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/IRecastBuilderProgressListener.cs", "repo_id": "ET", "token_count": 55 }
162
/* 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; namespace DotRecast.Recast { /// Specifies a configuration to use when performing Recast builds. /// @ingroup recast public class RcConfig { public readonly int Partition; public readonly bool UseTiles; /** The width/depth size of tile's on the xz-plane. [Limit: &gt;= 0] [Units: vx] **/ public readonly int TileSizeX; public readonly int TileSizeZ; /** The xz-plane cell size to use for fields. [Limit: &gt; 0] [Units: wu] **/ public readonly float Cs; /** The y-axis cell size to use for fields. [Limit: &gt; 0] [Units: wu] **/ public readonly float Ch; /** The maximum slope that is considered walkable. [Limits: 0 &lt;= value &lt; 90] [Units: Degrees] **/ public readonly float WalkableSlopeAngle; /** * Minimum floor to 'ceiling' height that will still allow the floor area to be considered walkable. [Limit: &gt;= 3] * [Units: vx] **/ public readonly int WalkableHeight; /** Maximum ledge height that is considered to still be traversable. [Limit: &gt;=0] [Units: vx] **/ public readonly int WalkableClimb; /** * The distance to erode/shrink the walkable area of the heightfield away from obstructions. [Limit: &gt;=0] [Units: * vx] **/ public readonly int WalkableRadius; /** The maximum allowed length for contour edges along the border of the mesh. [Limit: &gt;=0] [Units: vx] **/ public readonly int MaxEdgeLen; /** * The maximum distance a simplfied contour's border edges should deviate the original raw contour. [Limit: &gt;=0] * [Units: vx] **/ public readonly float MaxSimplificationError; /** The minimum number of cells allowed to form isolated island areas. [Limit: &gt;=0] [Units: vx] **/ public readonly int MinRegionArea; /** * Any regions with a span count smaller than this value will, if possible, be merged with larger regions. [Limit:&gt;=0] [Units: vx] **/ public readonly int MergeRegionArea; /** * The maximum number of vertices allowed for polygons generated during the contour to polygon conversion process. * [Limit: &gt;= 3] **/ public readonly int MaxVertsPerPoly; /** * Sets the sampling distance to use when generating the detail mesh. (For height detail only.) [Limits: 0 or >= 0.9] [Units: wu] **/ public readonly float DetailSampleDist; /** * The maximum distance the detail mesh surface should deviate from heightfield data. (For height detail only.) * [Limit: &gt;=0] [Units: wu] **/ public readonly float DetailSampleMaxError; public readonly RcAreaModification WalkableAreaMod; public readonly bool FilterLowHangingObstacles; public readonly bool FilterLedgeSpans; public readonly bool FilterWalkableLowHeightSpans; /** Set to false to disable building detailed mesh **/ public readonly bool BuildMeshDetail; /** The size of the non-navigable border around the heightfield. [Limit: &gt;=0] [Units: vx] **/ public readonly int BorderSize; /** Set of original settings passed in world units */ public readonly float MinRegionAreaWorld; public readonly float MergeRegionAreaWorld; public readonly float WalkableHeightWorld; public readonly float WalkableClimbWorld; public readonly float WalkableRadiusWorld; public readonly float MaxEdgeLenWorld; /** * Non-tiled build configuration */ public RcConfig( RcPartition partitionType, float cellSize, float cellHeight, float agentMaxSlope, float agentHeight, float agentRadius, float agentMaxClimb, int regionMinSize, int regionMergeSize, float edgeMaxLen, float edgeMaxError, int vertsPerPoly, float detailSampleDist, float detailSampleMaxError, bool filterLowHangingObstacles, bool filterLedgeSpans, bool filterWalkableLowHeightSpans, RcAreaModification walkableAreaMod, bool buildMeshDetail) : this(false, 0, 0, 0, partitionType, cellSize, cellHeight, agentMaxSlope, agentHeight, agentRadius, agentMaxClimb, regionMinSize * regionMinSize * cellSize * cellSize, regionMergeSize * regionMergeSize * cellSize * cellSize, edgeMaxLen, edgeMaxError, vertsPerPoly, detailSampleDist, detailSampleMaxError, filterLowHangingObstacles, filterLedgeSpans, filterWalkableLowHeightSpans, walkableAreaMod, buildMeshDetail) { // Note: area = size*size in [Units: wu] } public RcConfig( bool useTiles, int tileSizeX, int tileSizeZ, int borderSize, RcPartition partition, float cellSize, float cellHeight, float agentMaxSlope, float agentHeight, float agentRadius, float agentMaxClimb, float minRegionArea, float mergeRegionArea, float edgeMaxLen, float edgeMaxError, int vertsPerPoly, float detailSampleDist, float detailSampleMaxError, bool filterLowHangingObstacles, bool filterLedgeSpans, bool filterWalkableLowHeightSpans, RcAreaModification walkableAreaMod, bool buildMeshDetail) { UseTiles = useTiles; TileSizeX = tileSizeX; TileSizeZ = tileSizeZ; BorderSize = borderSize; Partition = RcPartitionType.Of(partition).Value; Cs = cellSize; Ch = cellHeight; WalkableSlopeAngle = agentMaxSlope; WalkableHeight = (int)Math.Ceiling(agentHeight / Ch); WalkableHeightWorld = agentHeight; WalkableClimb = (int)Math.Floor(agentMaxClimb / Ch); WalkableClimbWorld = agentMaxClimb; WalkableRadius = (int)Math.Ceiling(agentRadius / Cs); WalkableRadiusWorld = agentRadius; MinRegionArea = (int)Math.Round(minRegionArea / (Cs * Cs)); MinRegionAreaWorld = minRegionArea; MergeRegionArea = (int)Math.Round(mergeRegionArea / (Cs * Cs)); MergeRegionAreaWorld = mergeRegionArea; MaxEdgeLen = (int)(edgeMaxLen / cellSize); MaxEdgeLenWorld = edgeMaxLen; MaxSimplificationError = edgeMaxError; MaxVertsPerPoly = vertsPerPoly; DetailSampleDist = detailSampleDist < 0.9f ? 0 : cellSize * detailSampleDist; DetailSampleMaxError = cellHeight * detailSampleMaxError; WalkableAreaMod = walkableAreaMod; FilterLowHangingObstacles = filterLowHangingObstacles; FilterLedgeSpans = filterLedgeSpans; FilterWalkableLowHeightSpans = filterWalkableLowHeightSpans; BuildMeshDetail = buildMeshDetail; } public static int CalcBorder(float agentRadius, float cs) { return 3 + (int)Math.Ceiling(agentRadius / cs); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcConfig.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcConfig.cs", "repo_id": "ET", "token_count": 3342 }
163
namespace DotRecast.Recast { public class RcHeightPatch { public int xmin; public int ymin; public int width; public int height; public int[] data; } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcHeightPatch.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcHeightPatch.cs", "repo_id": "ET", "token_count": 98 }
164
/* 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. */ namespace DotRecast.Recast { /** * Contains triangle meshes that represent detailed height data associated with the polygons in its associated polygon * mesh object. */ public class RcPolyMeshDetail { /** The sub-mesh data. [Size: 4*#nmeshes] */ public int[] meshes; /** The mesh vertices. [Size: 3*#nverts] */ public float[] verts; /** The mesh triangles. [Size: 4*#ntris] */ public int[] tris; /** The number of sub-meshes defined by #meshes. */ public int nmeshes; /** The number of vertices in #verts. */ public int nverts; /** The number of triangles in #tris. */ public int ntris; } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPolyMeshDetail.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPolyMeshDetail.cs", "repo_id": "ET", "token_count": 534 }
165
/* 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 DotRecast.Core; namespace DotRecast.Recast { using static RcConstants; public static class RecastArea { /// Erodes the walkable area within the heightfield by the specified radius. /// /// Basically, any spans that are closer to a boundary or obstruction than the specified radius /// are marked as un-walkable. /// /// This method is usually called immediately after the heightfield has been built. /// /// @see rcCompactHeightfield, rcBuildCompactHeightfield, rcConfig::walkableRadius /// @ingroup recast /// /// @param[in,out] context The build context to use during the operation. /// @param[in] erosionRadius The radius of erosion. [Limits: 0 < value < 255] [Units: vx] /// @param[in,out] compactHeightfield The populated compact heightfield to erode. /// @returns True if the operation completed successfully. public static void ErodeWalkableArea(RcTelemetry context, int erosionRadius, RcCompactHeightfield compactHeightfield) { int xSize = compactHeightfield.width; int zSize = compactHeightfield.height; int zStride = xSize; // For readability using var timer = context.ScopedTimer(RcTimerLabel.RC_TIMER_ERODE_AREA); int[] distanceToBoundary = new int[compactHeightfield.spanCount]; Array.Fill(distanceToBoundary, 255); // Mark boundary cells. for (int z = 0; z < zSize; ++z) { for (int x = 0; x < xSize; ++x) { RcCompactCell cell = compactHeightfield.cells[x + z * zStride]; for (int spanIndex = cell.index, maxSpanIndex = cell.index + cell.count; spanIndex < maxSpanIndex; ++spanIndex) { if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) { distanceToBoundary[spanIndex] = 0; } else { RcCompactSpan span = compactHeightfield.spans[spanIndex]; // Check that there is a non-null adjacent span in each of the 4 cardinal directions. int neighborCount = 0; for (int direction = 0; direction < 4; ++direction) { int neighborConnection = RecastCommon.GetCon(span, direction); if (neighborConnection == RC_NOT_CONNECTED) { break; } int neighborX = x + RecastCommon.GetDirOffsetX(direction); int neighborZ = z + RecastCommon.GetDirOffsetY(direction); int neighborSpanIndex = compactHeightfield.cells[neighborX + neighborZ * zStride].index + RecastCommon.GetCon(span, direction); if (compactHeightfield.areas[neighborSpanIndex] == RC_NULL_AREA) { break; } neighborCount++; } // At least one missing neighbour, so this is a boundary cell. if (neighborCount != 4) { distanceToBoundary[spanIndex] = 0; } } } } } int newDistance; // Pass 1 for (int z = 0; z < zSize; ++z) { for (int x = 0; x < xSize; ++x) { RcCompactCell cell = compactHeightfield.cells[x + z * zStride]; int maxSpanIndex = cell.index + cell.count; for (int spanIndex = cell.index; spanIndex < maxSpanIndex; ++spanIndex) { RcCompactSpan span = compactHeightfield.spans[spanIndex]; if (RecastCommon.GetCon(span, 0) != RC_NOT_CONNECTED) { // (-1,0) int aX = x + RecastCommon.GetDirOffsetX(0); int aY = z + RecastCommon.GetDirOffsetY(0); int aIndex = compactHeightfield.cells[aX + aY * xSize].index + RecastCommon.GetCon(span, 0); RcCompactSpan aSpan = compactHeightfield.spans[aIndex]; newDistance = Math.Min(distanceToBoundary[aIndex] + 2, 255); if (newDistance < distanceToBoundary[spanIndex]) { distanceToBoundary[spanIndex] = newDistance; } // (-1,-1) if (RecastCommon.GetCon(aSpan, 3) != RC_NOT_CONNECTED) { int bX = aX + RecastCommon.GetDirOffsetX(3); int bY = aY + RecastCommon.GetDirOffsetY(3); int bIndex = compactHeightfield.cells[bX + bY * xSize].index + RecastCommon.GetCon(aSpan, 3); newDistance = Math.Min(distanceToBoundary[bIndex] + 3, 255); if (newDistance < distanceToBoundary[spanIndex]) { distanceToBoundary[spanIndex] = newDistance; } } } if (RecastCommon.GetCon(span, 3) != RC_NOT_CONNECTED) { // (0,-1) int aX = x + RecastCommon.GetDirOffsetX(3); int aY = z + RecastCommon.GetDirOffsetY(3); int aIndex = compactHeightfield.cells[aX + aY * xSize].index + RecastCommon.GetCon(span, 3); RcCompactSpan aSpan = compactHeightfield.spans[aIndex]; newDistance = Math.Min(distanceToBoundary[aIndex] + 2, 255); if (newDistance < distanceToBoundary[spanIndex]) { distanceToBoundary[spanIndex] = newDistance; } // (1,-1) if (RecastCommon.GetCon(aSpan, 2) != RC_NOT_CONNECTED) { int bX = aX + RecastCommon.GetDirOffsetX(2); int bY = aY + RecastCommon.GetDirOffsetY(2); int bIndex = compactHeightfield.cells[bX + bY * xSize].index + RecastCommon.GetCon(aSpan, 2); newDistance = Math.Min(distanceToBoundary[bIndex] + 3, 255); if (newDistance < distanceToBoundary[spanIndex]) { distanceToBoundary[spanIndex] = newDistance; } } } } } } // Pass 2 for (int z = zSize - 1; z >= 0; --z) { for (int x = xSize - 1; x >= 0; --x) { RcCompactCell cell = compactHeightfield.cells[x + z * zStride]; int maxSpanIndex = cell.index + cell.count; for (int i = cell.index; i < maxSpanIndex; ++i) { RcCompactSpan span = compactHeightfield.spans[i]; if (RecastCommon.GetCon(span, 2) != RC_NOT_CONNECTED) { // (1,0) int aX = x + RecastCommon.GetDirOffsetX(2); int aY = z + RecastCommon.GetDirOffsetY(2); int aIndex = compactHeightfield.cells[aX + aY * xSize].index + RecastCommon.GetCon(span, 2); RcCompactSpan aSpan = compactHeightfield.spans[aIndex]; newDistance = Math.Min(distanceToBoundary[aIndex] + 2, 255); if (newDistance < distanceToBoundary[i]) { distanceToBoundary[i] = newDistance; } // (1,1) if (RecastCommon.GetCon(aSpan, 1) != RC_NOT_CONNECTED) { int bX = aX + RecastCommon.GetDirOffsetX(1); int bY = aY + RecastCommon.GetDirOffsetY(1); int bIndex = compactHeightfield.cells[bX + bY * xSize].index + RecastCommon.GetCon(aSpan, 1); newDistance = Math.Min(distanceToBoundary[bIndex] + 3, 255); if (newDistance < distanceToBoundary[i]) { distanceToBoundary[i] = newDistance; } } } if (RecastCommon.GetCon(span, 1) != RC_NOT_CONNECTED) { // (0,1) int aX = x + RecastCommon.GetDirOffsetX(1); int aY = z + RecastCommon.GetDirOffsetY(1); int aIndex = compactHeightfield.cells[aX + aY * xSize].index + RecastCommon.GetCon(span, 1); RcCompactSpan aSpan = compactHeightfield.spans[aIndex]; newDistance = Math.Min(distanceToBoundary[aIndex] + 2, 255); if (newDistance < distanceToBoundary[i]) { distanceToBoundary[i] = newDistance; } // (-1,1) if (RecastCommon.GetCon(aSpan, 0) != RC_NOT_CONNECTED) { int bX = aX + RecastCommon.GetDirOffsetX(0); int bY = aY + RecastCommon.GetDirOffsetY(0); int bIndex = compactHeightfield.cells[bX + bY * xSize].index + RecastCommon.GetCon(aSpan, 0); newDistance = Math.Min(distanceToBoundary[bIndex] + 3, 255); if (newDistance < distanceToBoundary[i]) { distanceToBoundary[i] = newDistance; } } } } } } int minBoundaryDistance = erosionRadius * 2; for (int spanIndex = 0; spanIndex < compactHeightfield.spanCount; ++spanIndex) { if (distanceToBoundary[spanIndex] < minBoundaryDistance) { compactHeightfield.areas[spanIndex] = RC_NULL_AREA; } } } /// Applies a median filter to walkable area types (based on area id), removing noise. /// /// This filter is usually applied after applying area id's using functions /// such as #rcMarkBoxArea, #rcMarkConvexPolyArea, and #rcMarkCylinderArea. /// /// @see rcCompactHeightfield /// @ingroup recast /// /// @param[in,out] context The build context to use during the operation. /// @param[in,out] compactHeightfield A populated compact heightfield. /// @returns True if the operation completed successfully. public static bool MedianFilterWalkableArea(RcTelemetry context, RcCompactHeightfield compactHeightfield) { int xSize = compactHeightfield.width; int zSize = compactHeightfield.height; int zStride = xSize; // For readability using var timer = context.ScopedTimer(RcTimerLabel.RC_TIMER_MEDIAN_AREA); int[] areas = new int[compactHeightfield.spanCount]; for (int z = 0; z < zSize; ++z) { for (int x = 0; x < xSize; ++x) { RcCompactCell cell = compactHeightfield.cells[x + z * zStride]; int maxSpanIndex = cell.index + cell.count; for (int spanIndex = cell.index; spanIndex < maxSpanIndex; ++spanIndex) { RcCompactSpan span = compactHeightfield.spans[spanIndex]; if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) { areas[spanIndex] = compactHeightfield.areas[spanIndex]; continue; } int[] neighborAreas = new int[9]; for (int neighborIndex = 0; neighborIndex < 9; ++neighborIndex) { neighborAreas[neighborIndex] = compactHeightfield.areas[spanIndex]; } for (int dir = 0; dir < 4; ++dir) { if (RecastCommon.GetCon(span, dir) == RC_NOT_CONNECTED) { continue; } int aX = x + RecastCommon.GetDirOffsetX(dir); int aZ = z + RecastCommon.GetDirOffsetY(dir); int aIndex = compactHeightfield.cells[aX + aZ * zStride].index + RecastCommon.GetCon(span, dir); if (compactHeightfield.areas[aIndex] != RC_NULL_AREA) { neighborAreas[dir * 2 + 0] = compactHeightfield.areas[aIndex]; } RcCompactSpan aSpan = compactHeightfield.spans[aIndex]; int dir2 = (dir + 1) & 0x3; int neighborConnection2 = RecastCommon.GetCon(aSpan, dir2); if (neighborConnection2 != RC_NOT_CONNECTED) { int bX = aX + RecastCommon.GetDirOffsetX(dir2); int bZ = aZ + RecastCommon.GetDirOffsetY(dir2); int bIndex = compactHeightfield.cells[bX + bZ * zStride].index + RecastCommon.GetCon(aSpan, dir2); if (compactHeightfield.areas[bIndex] != RC_NULL_AREA) { neighborAreas[dir * 2 + 1] = compactHeightfield.areas[bIndex]; } } } //Array.Sort(neighborAreas); neighborAreas.InsertSort(); areas[spanIndex] = neighborAreas[4]; } } } compactHeightfield.areas = areas; return true; } /// Applies an area id to all spans within the specified bounding box. (AABB) /// /// @see rcCompactHeightfield, rcMedianFilterWalkableArea /// @ingroup recast /// /// @param[in,out] context The build context to use during the operation. /// @param[in] boxMinBounds The minimum extents of the bounding box. [(x, y, z)] [Units: wu] /// @param[in] boxMaxBounds The maximum extents of the bounding box. [(x, y, z)] [Units: wu] /// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] /// @param[in,out] compactHeightfield A populated compact heightfield. public static void MarkBoxArea(RcTelemetry context, float[] boxMinBounds, float[] boxMaxBounds, RcAreaModification areaId, RcCompactHeightfield compactHeightfield) { using var timer = context.ScopedTimer(RcTimerLabel.RC_TIMER_MARK_BOX_AREA); int xSize = compactHeightfield.width; int zSize = compactHeightfield.height; int zStride = xSize; // For readability // Find the footprint of the box area in grid cell coordinates. int minX = (int)((boxMinBounds[0] - compactHeightfield.bmin.x) / compactHeightfield.cs); int minY = (int)((boxMinBounds[1] - compactHeightfield.bmin.y) / compactHeightfield.ch); int minZ = (int)((boxMinBounds[2] - compactHeightfield.bmin.z) / compactHeightfield.cs); int maxX = (int)((boxMaxBounds[0] - compactHeightfield.bmin.x) / compactHeightfield.cs); int maxY = (int)((boxMaxBounds[1] - compactHeightfield.bmin.y) / compactHeightfield.ch); int maxZ = (int)((boxMaxBounds[2] - compactHeightfield.bmin.z) / compactHeightfield.cs); if (maxX < 0) { return; } if (minX >= xSize) { return; } if (maxZ < 0) { return; } if (minZ >= zSize) { return; } if (minX < 0) { minX = 0; } if (maxX >= xSize) { maxX = xSize - 1; } if (minZ < 0) { minZ = 0; } if (maxZ >= zSize) { maxZ = zSize - 1; } for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { RcCompactCell cell = compactHeightfield.cells[x + z * zStride]; int maxSpanIndex = cell.index + cell.count; for (int spanIndex = cell.index; spanIndex < maxSpanIndex; ++spanIndex) { RcCompactSpan span = compactHeightfield.spans[spanIndex]; // Skip if the span is outside the box extents. if (span.y < minY || span.y > maxY) { continue; } // Skip if the span has been removed. if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) { continue; } // Mark the span. compactHeightfield.areas[spanIndex] = areaId.Apply(compactHeightfield.areas[spanIndex]); } } } } /// Applies the area id to the all spans within the specified convex polygon. /// /// The value of spacial parameters are in world units. /// /// The y-values of the polygon vertices are ignored. So the polygon is effectively /// projected onto the xz-plane, translated to @p minY, and extruded to @p maxY. /// /// @see rcCompactHeightfield, rcMedianFilterWalkableArea /// @ingroup recast /// /// @param[in,out] context The build context to use during the operation. /// @param[in] verts The vertices of the polygon [For: (x, y, z) * @p numVerts] /// @param[in] numVerts The number of vertices in the polygon. /// @param[in] minY The height of the base of the polygon. [Units: wu] /// @param[in] maxY The height of the top of the polygon. [Units: wu] /// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] /// @param[in,out] compactHeightfield A populated compact heightfield. public static void MarkConvexPolyArea(RcTelemetry context, float[] verts, float minY, float maxY, RcAreaModification areaId, RcCompactHeightfield compactHeightfield) { using var timer = context.ScopedTimer(RcTimerLabel.RC_TIMER_MARK_CONVEXPOLY_AREA); int xSize = compactHeightfield.width; int zSize = compactHeightfield.height; int zStride = xSize; // For readability // Compute the bounding box of the polygon RcVec3f bmin = new RcVec3f(); RcVec3f bmax = new RcVec3f(); RcVec3f.Copy(ref bmin, verts, 0); RcVec3f.Copy(ref bmax, verts, 0); for (int i = 3; i < verts.Length; i += 3) { bmin.Min(verts, i); bmax.Max(verts, i); } bmin.y = minY; bmax.y = maxY; // Compute the grid footprint of the polygon int minx = (int)((bmin.x - compactHeightfield.bmin.x) / compactHeightfield.cs); int miny = (int)((bmin.y - compactHeightfield.bmin.y) / compactHeightfield.ch); int minz = (int)((bmin.z - compactHeightfield.bmin.z) / compactHeightfield.cs); int maxx = (int)((bmax.x - compactHeightfield.bmin.x) / compactHeightfield.cs); int maxy = (int)((bmax.y - compactHeightfield.bmin.y) / compactHeightfield.ch); int maxz = (int)((bmax.z - compactHeightfield.bmin.z) / compactHeightfield.cs); // Early-out if the polygon lies entirely outside the grid. if (maxx < 0) { return; } if (minx >= xSize) { return; } if (maxz < 0) { return; } if (minz >= zSize) { return; } // Clamp the polygon footprint to the grid if (minx < 0) { minx = 0; } if (maxx >= xSize) { maxx = xSize - 1; } if (minz < 0) { minz = 0; } if (maxz >= zSize) { maxz = zSize - 1; } // TODO: Optimize. for (int z = minz; z <= maxz; ++z) { for (int x = minx; x <= maxx; ++x) { RcCompactCell cell = compactHeightfield.cells[x + z * zStride]; int maxSpanIndex = cell.index + cell.count; for (int spanIndex = cell.index; spanIndex < maxSpanIndex; ++spanIndex) { RcCompactSpan span = compactHeightfield.spans[spanIndex]; // Skip if span is removed. if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) continue; // Skip if y extents don't overlap. if (span.y < miny || span.y > maxy) { continue; } RcVec3f point = new RcVec3f( compactHeightfield.bmin.x + (x + 0.5f) * compactHeightfield.cs, 0, compactHeightfield.bmin.z + (z + 0.5f) * compactHeightfield.cs ); if (PolyUtils.PointInPoly(verts, point)) { compactHeightfield.areas[spanIndex] = areaId.Apply(compactHeightfield.areas[spanIndex]); } } } } } /// Applies the area id to all spans within the specified y-axis-aligned cylinder. /// /// @see rcCompactHeightfield, rcMedianFilterWalkableArea /// /// @ingroup recast /// /// @param[in,out] context The build context to use during the operation. /// @param[in] position The center of the base of the cylinder. [Form: (x, y, z)] [Units: wu] /// @param[in] radius The radius of the cylinder. [Units: wu] [Limit: > 0] /// @param[in] height The height of the cylinder. [Units: wu] [Limit: > 0] /// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] /// @param[in,out] compactHeightfield A populated compact heightfield. public static void MarkCylinderArea(RcTelemetry context, float[] position, float radius, float height, RcAreaModification areaId, RcCompactHeightfield compactHeightfield) { using var timer = context.ScopedTimer(RcTimerLabel.RC_TIMER_MARK_CYLINDER_AREA); int xSize = compactHeightfield.width; int zSize = compactHeightfield.height; int zStride = xSize; // For readability // Compute the bounding box of the cylinder RcVec3f cylinderBBMin = new RcVec3f( position[0] - radius, position[1], position[2] - radius ); RcVec3f cylinderBBMax = new RcVec3f( position[0] + radius, position[1] + height, position[2] + radius ); // Compute the grid footprint of the cylinder int minx = (int)((cylinderBBMin.x - compactHeightfield.bmin.x) / compactHeightfield.cs); int miny = (int)((cylinderBBMin.y - compactHeightfield.bmin.y) / compactHeightfield.ch); int minz = (int)((cylinderBBMin.z - compactHeightfield.bmin.z) / compactHeightfield.cs); int maxx = (int)((cylinderBBMax.x - compactHeightfield.bmin.x) / compactHeightfield.cs); int maxy = (int)((cylinderBBMax.y - compactHeightfield.bmin.y) / compactHeightfield.ch); int maxz = (int)((cylinderBBMax.z - compactHeightfield.bmin.z) / compactHeightfield.cs); // Early-out if the cylinder is completely outside the grid bounds. if (maxx < 0) { return; } if (minx >= xSize) { return; } if (maxz < 0) { return; } if (minz >= zSize) { return; } // Clamp the cylinder bounds to the grid. if (minx < 0) { minx = 0; } if (maxx >= xSize) { maxx = xSize - 1; } if (minz < 0) { minz = 0; } if (maxz >= zSize) { maxz = zSize - 1; } float radiusSq = radius * radius; for (int z = minz; z <= maxz; ++z) { for (int x = minx; x <= maxx; ++x) { RcCompactCell cell = compactHeightfield.cells[x + z * zStride]; int maxSpanIndex = cell.index + cell.count; float cellX = compactHeightfield.bmin[0] + ((float)x + 0.5f) * compactHeightfield.cs; float cellZ = compactHeightfield.bmin[2] + ((float)z + 0.5f) * compactHeightfield.cs; float deltaX = cellX - position[0]; float deltaZ = cellZ - position[2]; // Skip this column if it's too far from the center point of the cylinder. if (RcMath.Sqr(deltaX) + RcMath.Sqr(deltaZ) >= radiusSq) { continue; } // Mark all overlapping spans for (int spanIndex = cell.index; spanIndex < maxSpanIndex; ++spanIndex) { RcCompactSpan span = compactHeightfield.spans[spanIndex]; // Skip if span is removed. if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) { continue; } // Mark if y extents overlap. if (span.y >= miny && span.y <= maxy) { compactHeightfield.areas[spanIndex] = areaId.Apply(compactHeightfield.areas[spanIndex]); } } } } } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastArea.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastArea.cs", "repo_id": "ET", "token_count": 16977 }
166
/* 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 DotRecast.Core; namespace DotRecast.Recast { using static RcConstants; public static class RecastFilter { /// @par /// /// Allows the formation of walkable regions that will flow over low lying /// objects such as curbs, and up structures such as stairways. /// /// Two neighboring spans are walkable if: <tt>RcAbs(currentSpan.smax - neighborSpan.smax) < walkableClimb</tt> /// /// @warning Will override the effect of #rcFilterLedgeSpans. So if both filters are used, call /// #rcFilterLedgeSpans after calling this filter. /// /// @see rcHeightfield, rcConfig public static void FilterLowHangingWalkableObstacles(RcTelemetry ctx, int walkableClimb, RcHeightfield solid) { using var timer = ctx.ScopedTimer(RcTimerLabel.RC_TIMER_FILTER_LOW_OBSTACLES); int w = solid.width; int h = solid.height; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { RcSpan ps = null; bool previousWalkable = false; int previousArea = RC_NULL_AREA; for (RcSpan s = solid.spans[x + y * w]; s != null; ps = s, s = s.next) { bool walkable = s.area != RC_NULL_AREA; // If current span is not walkable, but there is walkable // span just below it, mark the span above it walkable too. if (!walkable && previousWalkable) { if (Math.Abs(s.smax - ps.smax) <= walkableClimb) s.area = previousArea; } // Copy walkable flag so that it cannot propagate // past multiple non-walkable objects. previousWalkable = walkable; previousArea = s.area; } } } } /// @par /// /// A ledge is a span with one or more neighbors whose maximum is further away than @p walkableClimb /// from the current span's maximum. /// This method removes the impact of the overestimation of conservative voxelization /// so the resulting mesh will not have regions hanging in the air over ledges. /// /// A span is a ledge if: <tt>RcAbs(currentSpan.smax - neighborSpan.smax) > walkableClimb</tt> /// /// @see rcHeightfield, rcConfig public static void FilterLedgeSpans(RcTelemetry ctx, int walkableHeight, int walkableClimb, RcHeightfield solid) { using var timer = ctx.ScopedTimer(RcTimerLabel.RC_TIMER_FILTER_BORDER); int w = solid.width; int h = solid.height; // Mark border spans. for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { for (RcSpan s = solid.spans[x + y * w]; s != null; s = s.next) { // Skip non walkable spans. if (s.area == RC_NULL_AREA) continue; int bot = (s.smax); int top = s.next != null ? s.next.smin : SPAN_MAX_HEIGHT; // Find neighbours minimum height. int minh = SPAN_MAX_HEIGHT; // Min and max height of accessible neighbours. int asmin = s.smax; int asmax = s.smax; for (int dir = 0; dir < 4; ++dir) { int dx = x + RecastCommon.GetDirOffsetX(dir); int dy = y + RecastCommon.GetDirOffsetY(dir); // Skip neighbours which are out of bounds. if (dx < 0 || dy < 0 || dx >= w || dy >= h) { minh = Math.Min(minh, -walkableClimb - bot); continue; } // From minus infinity to the first span. RcSpan ns = solid.spans[dx + dy * w]; int nbot = -walkableClimb; int ntop = ns != null ? ns.smin : SPAN_MAX_HEIGHT; // Skip neightbour if the gap between the spans is too small. if (Math.Min(top, ntop) - Math.Max(bot, nbot) > walkableHeight) minh = Math.Min(minh, nbot - bot); // Rest of the spans. for (ns = solid.spans[dx + dy * w]; ns != null; ns = ns.next) { nbot = ns.smax; ntop = ns.next != null ? ns.next.smin : SPAN_MAX_HEIGHT; // Skip neightbour if the gap between the spans is too small. if (Math.Min(top, ntop) - Math.Max(bot, nbot) > walkableHeight) { minh = Math.Min(minh, nbot - bot); // Find min/max accessible neighbour height. if (Math.Abs(nbot - bot) <= walkableClimb) { if (nbot < asmin) asmin = nbot; if (nbot > asmax) asmax = nbot; } } } } // The current span is close to a ledge if the drop to any // neighbour span is less than the walkableClimb. if (minh < -walkableClimb) s.area = RC_NULL_AREA; // If the difference between all neighbours is too large, // we are at steep slope, mark the span as ledge. if ((asmax - asmin) > walkableClimb) { s.area = RC_NULL_AREA; } } } } } /// @par /// /// For this filter, the clearance above the span is the distance from the span's /// maximum to the next higher span's minimum. (Same grid column.) /// /// @see rcHeightfield, rcConfig public static void FilterWalkableLowHeightSpans(RcTelemetry ctx, int walkableHeight, RcHeightfield solid) { using var timer = ctx.ScopedTimer(RcTimerLabel.RC_TIMER_FILTER_WALKABLE); int w = solid.width; int h = solid.height; // Remove walkable flag from spans which do not have enough // space above them for the agent to stand there. for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { for (RcSpan s = solid.spans[x + y * w]; s != null; s = s.next) { int bot = (s.smax); int top = s.next != null ? s.next.smin : SPAN_MAX_HEIGHT; if ((top - bot) < walkableHeight) s.area = RC_NULL_AREA; } } } } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastFilter.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastFilter.cs", "repo_id": "ET", "token_count": 4813 }
167
fileFormatVersion: 2 guid: bf2682587b9394aa89238524a4ef1ef9 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/ETTask/AsyncETTaskCompletedMethodBuilder.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/ETTask/AsyncETTaskCompletedMethodBuilder.cs.meta", "repo_id": "ET", "token_count": 94 }
168
fileFormatVersion: 2 guid: d48c67734d0468148be856dbd3051d19 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/ETTask/IAwaiter.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/ETTask/IAwaiter.cs.meta", "repo_id": "ET", "token_count": 93 }
169
using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace NativeCollection { public unsafe partial struct FixedSizeMemoryPool: IDisposable { // 最大维护的空slab 多出的空slab直接释放 public int MaxUnUsedSlabs; public int ItemSize; public int BlockSize; public SlabLinkedList InUsedSlabs; public SlabLinkedList UnUsedSlabs; public FixedSizeMemoryPool* Self { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (FixedSizeMemoryPool*)Unsafe.AsPointer(ref this); } } public static FixedSizeMemoryPool* Create(int blockSize, int itemSize , int maxUnUsedSlabs = 3) { FixedSizeMemoryPool* memoryPool = (FixedSizeMemoryPool*)NativeMemoryHelper.Alloc((UIntPtr)Unsafe.SizeOf<FixedSizeMemoryPool>()); memoryPool->ItemSize = itemSize; memoryPool->BlockSize = blockSize; memoryPool->MaxUnUsedSlabs = maxUnUsedSlabs; Slab* initSlab = Slab.Create(blockSize, itemSize,null,null); memoryPool->InUsedSlabs = new SlabLinkedList(initSlab); memoryPool->UnUsedSlabs = new SlabLinkedList(null); return memoryPool; } public void* Alloc() { Debug.Assert(InUsedSlabs.Top!=null && InUsedSlabs.Top->FreeSize>0); byte* allocPtr = InUsedSlabs.Top->Alloc(); if (InUsedSlabs.Top->IsAllAlloc()) { InUsedSlabs.MoveTopToBottom(); if (InUsedSlabs.Top->IsAllAlloc()) { Slab* newSlab = Slab.Create(BlockSize, ItemSize,null,null); InUsedSlabs.AddToTop(newSlab); } } return allocPtr; } public void Free(void* ptr) { Debug.Assert(ptr!=null); ListNode* listNode = (ListNode*)((byte*)ptr - Unsafe.SizeOf<ListNode>()); Debug.Assert(listNode!=null); Slab* slab = listNode->ParentSlab; slab->Free(listNode); if (slab==InUsedSlabs.Top) { return; } // 当前链表头为空时 移至空闲链表 if (InUsedSlabs.Top->IsAllFree()) { Slab* oldTopSlab = InUsedSlabs.Top; InUsedSlabs.SplitOut(oldTopSlab); UnUsedSlabs.AddToTop(oldTopSlab); // 释放多于的空slab if (UnUsedSlabs.SlabCount>MaxUnUsedSlabs) { var bottomSlab = UnUsedSlabs.Bottom; UnUsedSlabs.SplitOut(bottomSlab); bottomSlab->Dispose(); } } // 对应slab移至链表头部 if (slab!=InUsedSlabs.Top) { InUsedSlabs.SplitOut(slab); InUsedSlabs.AddToTop(slab); } } public void ReleaseUnUsedSlabs() { Slab* unUsedSlab = UnUsedSlabs.Top; while (unUsedSlab!=null) { Slab* currentSlab = unUsedSlab; unUsedSlab = unUsedSlab->Next; currentSlab->Dispose(); } UnUsedSlabs = new SlabLinkedList(null); } public void Dispose() { Slab* inUsedSlab = InUsedSlabs.Top; while (inUsedSlab!=null) { Slab* currentSlab = inUsedSlab; inUsedSlab = inUsedSlab->Next; currentSlab->Dispose(); } ReleaseUnUsedSlabs(); if (Self!=null) { NativeMemoryHelper.Free(Self); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<FixedSizeMemoryPool>()); } } } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/FixedSizeMemoryPool/FixedSizeMemoryPool.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/FixedSizeMemoryPool/FixedSizeMemoryPool.cs", "repo_id": "ET", "token_count": 2264 }
170
using System; using System.Runtime.CompilerServices; using NativeCollection.UnsafeType; namespace NativeCollection { public unsafe class NativePool<T> : INativeCollectionClass where T: unmanaged,IEquatable<T>,IPool { private UnsafeType.NativeStackPool<T>* _nativePool; private const int _defaultPoolSize = 200; private int _poolSize; public NativePool(int maxPoolSize = _defaultPoolSize) { _poolSize = maxPoolSize; _nativePool = UnsafeType.NativeStackPool<T>.Create(_poolSize); IsDisposed = false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T* Alloc() { return _nativePool->Alloc(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Return(T* ptr) { _nativePool->Return(ptr); } public void Dispose() { if (IsDisposed) { return; } if (_nativePool != null) { _nativePool->Dispose(); NativeMemoryHelper.Free(_nativePool); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.NativeStackPool<T>>()); IsDisposed = true; } } public void ReInit() { if (IsDisposed) { _nativePool = UnsafeType.NativeStackPool<T>.Create(_poolSize); IsDisposed = false; } } public bool IsDisposed { get; private set; } } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/NativePool.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/NativePool.cs", "repo_id": "ET", "token_count": 826 }
171
fileFormatVersion: 2 guid: 72d098fcb0407df47a71437960937e8b MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/Queue.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/Queue.cs.meta", "repo_id": "ET", "token_count": 93 }
172
fileFormatVersion: 2 guid: 06b82dc043ec3094394e95c4014f32fc folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Settings/IgnoreAsmdef/Hotfix/Client.meta/0
{ "file_path": "ET/Unity/Assets/Settings/IgnoreAsmdef/Hotfix/Client.meta", "repo_id": "ET", "token_count": 67 }
173
fileFormatVersion: 2 guid: 68daac35c9406574aa962b7d062cee1d TextScriptImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Settings/IgnoreAsmdef/README.txt.meta/0
{ "file_path": "ET/Unity/Assets/Settings/IgnoreAsmdef/README.txt.meta", "repo_id": "ET", "token_count": 66 }
174
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!55 &1 PhysicsManager: m_ObjectHideFlags: 0 serializedVersion: 2 m_Gravity: {x: 0, y: -9.81, z: 0} m_DefaultMaterial: {fileID: 0} m_BounceThreshold: 2 m_SleepThreshold: 0.005 m_DefaultContactOffset: 0.01 m_SolverIterationCount: 6 m_SolverVelocityIterations: 1 m_QueriesHitTriggers: 1 m_EnableAdaptiveForce: 0 m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ET/Unity/ProjectSettings/DynamicsManager.asset/0
{ "file_path": "ET/Unity/ProjectSettings/DynamicsManager.asset", "repo_id": "ET", "token_count": 240 }
175
<Project> <PropertyGroup> <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> <CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled> </PropertyGroup> <ItemGroup> <PackageVersion Include="AvalonEdit" Version="6.3.0.90" /> <PackageVersion Include="CliWrap" Version="3.6.6" /> <PackageVersion Include="DataGridExtensions" Version="2.6.0" /> <PackageVersion Include="DiffLib" Version="2017.7.26.1241" /> <PackageVersion Include="Dirkster.AvalonDock.Themes.VS2013" Version="4.72.1" /> <PackageVersion Include="FluentAssertions" Version="6.12.0" /> <PackageVersion Include="ILCompiler.Reflection.ReadyToRun.Experimental" Version="8.0.0-rc.2.23471.30" /> <PackageVersion Include="Iced" Version="1.21.0" /> <PackageVersion Include="JunitXml.TestLogger" Version="3.1.12" /> <PackageVersion Include="K4os.Compression.LZ4" Version="1.3.6" /> <PackageVersion Include="McMaster.Extensions.Hosting.CommandLine" Version="4.1.0" /> <PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" /> <PackageVersion Include="Microsoft.CodeAnalysis.VisualBasic" Version="4.8.0" /> <PackageVersion Include="Microsoft.DiaSymReader.Converter.Xml" Version="1.1.0-beta2-22171-02" /> <PackageVersion Include="Microsoft.DiaSymReader" Version="1.4.0" /> <PackageVersion Include="Microsoft.DiaSymReader.Native" Version="17.0.0-beta1.21524.1" /> <PackageVersion Include="Microsoft.Extensions.Hosting" Version="8.0.0" /> <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.9.0" /> <PackageVersion Include="Microsoft.NETCore.ILAsm" Version="8.0.0" /> <PackageVersion Include="Microsoft.NETCore.ILDAsm" Version="8.0.0" /> <PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" /> <PackageVersion Include="Microsoft.VisualStudio.Composition" Version="17.7.40" /> <PackageVersion Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.77" /> <PackageVersion Include="Mono.Cecil" Version="0.11.5" /> <PackageVersion Include="NSubstitute" Version="5.1.0" /> <PackageVersion Include="NSubstitute.Analyzers.CSharp" Version="1.0.17" /> <PackageVersion Include="NUnit" Version="4.0.1" /> <PackageVersion Include="NUnit3TestAdapter" Version="4.5.0" /> <PackageVersion Include="NuGet.Protocol" Version="6.9.1" /> <PackageVersion Include="PowerShellStandard.Library" Version="5.1.1" /> <PackageVersion Include="System.Collections.Immutable" Version="8.0.0" /> <PackageVersion Include="System.Composition" Version="8.0.0" /> <PackageVersion Include="System.Memory" Version="4.5.5" /> <PackageVersion Include="System.Reflection.Metadata" Version="8.0.0" /> <PackageVersion Include="System.Resources.Extensions" Version="8.0.0" /> <PackageVersion Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" /> <PackageVersion Include="TomsToolbox.Wpf.Styles" Version="2.14.0" /> <PackageVersion Include="coverlet.collector" Version="6.0.0" /> </ItemGroup> </Project>
ILSpy/Directory.Packages.props/0
{ "file_path": "ILSpy/Directory.Packages.props", "repo_id": "ILSpy", "token_count": 1097 }
176
/* 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 ICSharpCode.BamlDecompiler.Baml; namespace ICSharpCode.BamlDecompiler.Xaml { internal class XamlResourceKey { XamlResourceKey(BamlNode node) { KeyNode = node; StaticResources = new List<BamlNode>(); IBamlDeferRecord keyRecord; if (node is BamlBlockNode) keyRecord = (IBamlDeferRecord)((BamlBlockNode)node).Header; else keyRecord = (IBamlDeferRecord)((BamlRecordNode)node).Record; if (keyRecord.Record.Type == BamlRecordType.ElementEnd) { Debug.Assert(node.Parent.Footer == keyRecord.Record); node.Parent.Annotation = this; node.Annotation = this; return; } if (keyRecord.Record.Type != BamlRecordType.ElementStart && node.Parent.Type == BamlRecordType.ElementStart) { node.Parent.Annotation = this; node.Annotation = this; return; } if (keyRecord.Record.Type != BamlRecordType.ElementStart) { Debug.WriteLine($"Key record @{keyRecord.Position} must be attached to ElementStart (actual {keyRecord.Record.Type})"); } foreach (var child in node.Parent.Children) { if (child.Record != keyRecord.Record) continue; child.Annotation = this; node.Annotation = this; return; } Debug.WriteLine("Cannot find corresponding value element of key record @" + keyRecord.Position); } public static XamlResourceKey Create(BamlNode node) => new XamlResourceKey(node); public BamlNode KeyNode { get; set; } public BamlElement KeyElement { get; set; } public IList<BamlNode> StaticResources { get; } public static XamlResourceKey FindKeyInSiblings(BamlNode node) { var children = node.Parent.Children; var index = children.IndexOf(node); for (int i = index; i >= 0; i--) { if (children[i].Annotation is XamlResourceKey) return (XamlResourceKey)children[i].Annotation; } return null; } public static XamlResourceKey FindKeyInAncestors(BamlNode node) => FindKeyInAncestors(node, out var found); public static XamlResourceKey FindKeyInAncestors(BamlNode node, out BamlNode found) { BamlNode n = node; do { if (n.Annotation is XamlResourceKey) { found = n; return (XamlResourceKey)n.Annotation; } n = n.Parent; } while (n != null); found = null; return null; } } }
ILSpy/ICSharpCode.BamlDecompiler/Xaml/XamlResourceKey.cs/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/Xaml/XamlResourceKey.cs", "repo_id": "ILSpy", "token_count": 1203 }
177
// 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.IO; using ICSharpCode.Decompiler.CSharp.OutputVisitor; using ICSharpCode.Decompiler.CSharp.Syntax; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests.Output { [TestFixture] public class InsertParenthesesVisitorTests { CSharpFormattingOptions policy; [SetUp] public void SetUp() { policy = FormattingOptionsFactory.CreateMono(); } string InsertReadable(Expression expr) { expr = expr.Clone(); expr.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true }); StringWriter w = new StringWriter(); w.NewLine = " "; expr.AcceptVisitor(new CSharpOutputVisitor(new TextWriterTokenWriter(w) { IndentationString = "" }, policy)); return w.ToString(); } string InsertRequired(Expression expr) { expr = expr.Clone(); expr.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = false }); StringWriter w = new StringWriter(); w.NewLine = " "; expr.AcceptVisitor(new CSharpOutputVisitor(new TextWriterTokenWriter(w) { IndentationString = "" }, policy)); return w.ToString(); } [Test] public void EqualityInAssignment() { Expression expr = new AssignmentExpression( new IdentifierExpression("cond"), new BinaryOperatorExpression( new IdentifierExpression("a"), BinaryOperatorType.Equality, new IdentifierExpression("b") ) ); Assert.That(InsertRequired(expr), Is.EqualTo("cond = a == b")); Assert.That(InsertReadable(expr), Is.EqualTo("cond = a == b")); } [Test] public void LambdaInAssignment() { Expression expr = new AssignmentExpression( new IdentifierExpression("p"), new LambdaExpression { Body = new BinaryOperatorExpression( new IdentifierExpression("a"), BinaryOperatorType.Add, new IdentifierExpression("b") ) } ); Assert.That(InsertRequired(expr), Is.EqualTo("p = () => a + b")); Assert.That(InsertReadable(expr), Is.EqualTo("p = () => a + b")); } [Test] public void LambdaInDelegateAdditionRHS() { Expression expr = new BinaryOperatorExpression { Left = new IdentifierExpression("p"), Operator = BinaryOperatorType.Add, Right = new LambdaExpression { Body = new BinaryOperatorExpression( new IdentifierExpression("a"), BinaryOperatorType.Add, new IdentifierExpression("b") ) } }; Assert.That(InsertRequired(expr), Is.EqualTo("p + () => a + b")); Assert.That(InsertReadable(expr), Is.EqualTo("p + (() => a + b)")); } [Test] public void LambdaInDelegateAdditionLHS() { Expression expr = new BinaryOperatorExpression { Left = new LambdaExpression { Body = new BinaryOperatorExpression( new IdentifierExpression("a"), BinaryOperatorType.Add, new IdentifierExpression("b") ) }, Operator = BinaryOperatorType.Add, Right = new IdentifierExpression("p"), }; Assert.That(InsertRequired(expr), Is.EqualTo("(() => a + b) + p")); Assert.That(InsertReadable(expr), Is.EqualTo("(() => a + b) + p")); } [Test] public void TrickyCast1() { Expression expr = new CastExpression { Type = new PrimitiveType("int"), Expression = new UnaryOperatorExpression( UnaryOperatorType.Minus, new IdentifierExpression("a") ) }; Assert.That(InsertRequired(expr), Is.EqualTo("(int)-a")); Assert.That(InsertReadable(expr), Is.EqualTo("(int)(-a)")); } [Test] public void TrickyCast2() { Expression expr = new CastExpression { Type = new SimpleType("MyType"), Expression = new UnaryOperatorExpression( UnaryOperatorType.Minus, new IdentifierExpression("a") ) }; Assert.That(InsertRequired(expr), Is.EqualTo("(MyType)(-a)")); Assert.That(InsertReadable(expr), Is.EqualTo("(MyType)(-a)")); } [Test] public void TrickyCast3() { Expression expr = new CastExpression { Type = new SimpleType("MyType"), Expression = new UnaryOperatorExpression( UnaryOperatorType.Not, new IdentifierExpression("a") ) }; Assert.That(InsertRequired(expr), Is.EqualTo("(MyType)!a")); Assert.That(InsertReadable(expr), Is.EqualTo("(MyType)(!a)")); } [Test] public void TrickyCast4() { Expression expr = new CastExpression { Type = new SimpleType("MyType"), Expression = new PrimitiveExpression(int.MinValue), }; Assert.That(InsertRequired(expr), Is.EqualTo("(MyType)(-2147483648)")); Assert.That(InsertReadable(expr), Is.EqualTo("(MyType)(-2147483648)")); } [Test] public void TrickyCast5() { Expression expr = new CastExpression { Type = new SimpleType("MyType"), Expression = new PrimitiveExpression(-1.0), }; Assert.That(InsertRequired(expr), Is.EqualTo("(MyType)(-1.0)")); Assert.That(InsertReadable(expr), Is.EqualTo("(MyType)(-1.0)")); } [Test] public void TrickyCast6() { Expression expr = new CastExpression { Type = new PrimitiveType("double"), Expression = new PrimitiveExpression(int.MinValue), }; Assert.That(InsertRequired(expr), Is.EqualTo("(double)-2147483648")); Assert.That(InsertReadable(expr), Is.EqualTo("(double)(-2147483648)")); } [Test] public void CastAndInvoke() { Expression expr = new MemberReferenceExpression { Target = new CastExpression { Type = new PrimitiveType("string"), Expression = new IdentifierExpression("a") }, MemberName = "Length" }; Assert.That(InsertRequired(expr), Is.EqualTo("((string)a).Length")); Assert.That(InsertReadable(expr), Is.EqualTo("((string)a).Length")); } [Test] public void DoubleNegation() { Expression expr = new UnaryOperatorExpression( UnaryOperatorType.Minus, new UnaryOperatorExpression(UnaryOperatorType.Minus, new IdentifierExpression("a")) ); Assert.That(InsertRequired(expr), Is.EqualTo("- -a")); Assert.That(InsertReadable(expr), Is.EqualTo("-(-a)")); } [Test] public void AdditionWithConditional() { Expression expr = new BinaryOperatorExpression { Left = new IdentifierExpression("a"), Operator = BinaryOperatorType.Add, Right = new ConditionalExpression { Condition = new BinaryOperatorExpression { Left = new IdentifierExpression("b"), Operator = BinaryOperatorType.Equality, Right = new PrimitiveExpression(null) }, TrueExpression = new IdentifierExpression("c"), FalseExpression = new IdentifierExpression("d") } }; Assert.That(InsertRequired(expr), Is.EqualTo("a + (b == null ? c : d)")); Assert.That(InsertReadable(expr), Is.EqualTo("a + ((b == null) ? c : d)")); } [Test] public void TypeTestInConditional() { Expression expr = new ConditionalExpression { Condition = new IsExpression { Expression = new IdentifierExpression("a"), Type = new ComposedType { BaseType = new PrimitiveType("int"), HasNullableSpecifier = true } }, TrueExpression = new IdentifierExpression("b"), FalseExpression = new IdentifierExpression("c") }; Assert.That(InsertRequired(expr), Is.EqualTo("a is int? ? b : c")); Assert.That(InsertReadable(expr), Is.EqualTo("(a is int?) ? b : c")); policy.SpaceBeforeConditionalOperatorCondition = false; policy.SpaceAfterConditionalOperatorCondition = false; policy.SpaceBeforeConditionalOperatorSeparator = false; policy.SpaceAfterConditionalOperatorSeparator = false; Assert.That(InsertRequired(expr), Is.EqualTo("a is int? ?b:c")); Assert.That(InsertReadable(expr), Is.EqualTo("(a is int?)?b:c")); } [Test] public void MethodCallOnQueryExpression() { Expression expr = new InvocationExpression(new MemberReferenceExpression { Target = new QueryExpression { Clauses = { new QueryFromClause { Identifier = "a", Expression = new IdentifierExpression("b") }, new QuerySelectClause { Expression = new InvocationExpression(new MemberReferenceExpression { Target = new IdentifierExpression("a"), MemberName = "c" }) } } }, MemberName = "ToArray" }); Assert.That(InsertRequired(expr), Is.EqualTo("(from a in b select a.c ()).ToArray ()")); Assert.That(InsertReadable(expr), Is.EqualTo("(from a in b select a.c ()).ToArray ()")); } [Test] public void SumOfQueries() { QueryExpression query = new QueryExpression { Clauses = { new QueryFromClause { Identifier = "a", Expression = new IdentifierExpression("b") }, new QuerySelectClause { Expression = new IdentifierExpression("a") } } }; Expression expr = new BinaryOperatorExpression( query, BinaryOperatorType.Add, query.Clone() ); Assert.That(InsertRequired(expr), Is.EqualTo("(from a in b select a) + " + "from a in b select a")); Assert.That(InsertReadable(expr), Is.EqualTo("(from a in b select a) + " + "(from a in b select a)")); } [Test] public void QueryInTypeTest() { Expression expr = new IsExpression { Expression = new QueryExpression { Clauses = { new QueryFromClause { Identifier = "a", Expression = new IdentifierExpression("b") }, new QuerySelectClause { Expression = new IdentifierExpression("a") } } }, Type = new PrimitiveType("int") }; Assert.That(InsertRequired(expr), Is.EqualTo("(from a in b select a) is int")); Assert.That(InsertReadable(expr), Is.EqualTo("(from a in b select a) is int")); } [Test] public void PrePost() { Expression expr = new UnaryOperatorExpression( UnaryOperatorType.Increment, new UnaryOperatorExpression( UnaryOperatorType.PostIncrement, new IdentifierExpression("a") ) ); Assert.That(InsertRequired(expr), Is.EqualTo("++a++")); Assert.That(InsertReadable(expr), Is.EqualTo("++(a++)")); } [Test] public void PostPre() { Expression expr = new UnaryOperatorExpression( UnaryOperatorType.PostIncrement, new UnaryOperatorExpression( UnaryOperatorType.Increment, new IdentifierExpression("a") ) ); Assert.That(InsertRequired(expr), Is.EqualTo("(++a)++")); Assert.That(InsertReadable(expr), Is.EqualTo("(++a)++")); } [Test] public void Logical1() { Expression expr = new BinaryOperatorExpression( new BinaryOperatorExpression( new IdentifierExpression("a"), BinaryOperatorType.ConditionalAnd, new IdentifierExpression("b") ), BinaryOperatorType.ConditionalAnd, new IdentifierExpression("c") ); Assert.That(InsertRequired(expr), Is.EqualTo("a && b && c")); Assert.That(InsertReadable(expr), Is.EqualTo("a && b && c")); } [Test] public void Logical2() { Expression expr = new BinaryOperatorExpression( new IdentifierExpression("a"), BinaryOperatorType.ConditionalAnd, new BinaryOperatorExpression( new IdentifierExpression("b"), BinaryOperatorType.ConditionalAnd, new IdentifierExpression("c") ) ); Assert.That(InsertRequired(expr), Is.EqualTo("a && (b && c)")); Assert.That(InsertReadable(expr), Is.EqualTo("a && (b && c)")); } [Test] public void Logical3() { Expression expr = new BinaryOperatorExpression( new IdentifierExpression("a"), BinaryOperatorType.ConditionalOr, new BinaryOperatorExpression( new IdentifierExpression("b"), BinaryOperatorType.ConditionalAnd, new IdentifierExpression("c") ) ); Assert.That(InsertRequired(expr), Is.EqualTo("a || b && c")); Assert.That(InsertReadable(expr), Is.EqualTo("a || (b && c)")); } [Test] public void Logical4() { Expression expr = new BinaryOperatorExpression( new IdentifierExpression("a"), BinaryOperatorType.ConditionalAnd, new BinaryOperatorExpression( new IdentifierExpression("b"), BinaryOperatorType.ConditionalOr, new IdentifierExpression("c") ) ); Assert.That(InsertRequired(expr), Is.EqualTo("a && (b || c)")); Assert.That(InsertReadable(expr), Is.EqualTo("a && (b || c)")); } [Test] public void ArrayCreationInIndexer() { Expression expr = new IndexerExpression { Target = new ArrayCreateExpression { Type = new PrimitiveType("int"), Arguments = { new PrimitiveExpression(1) } }, Arguments = { new PrimitiveExpression(0) } }; Assert.That(InsertRequired(expr), Is.EqualTo("(new int[1]) [0]")); Assert.That(InsertReadable(expr), Is.EqualTo("(new int[1]) [0]")); } [Test] public void ArrayCreationWithInitializerInIndexer() { Expression expr = new IndexerExpression { Target = new ArrayCreateExpression { Type = new PrimitiveType("int"), Arguments = { new PrimitiveExpression(1) }, Initializer = new ArrayInitializerExpression { Elements = { new PrimitiveExpression(42) } } }, Arguments = { new PrimitiveExpression(0) } }; Assert.That(InsertRequired(expr), Is.EqualTo("new int[1] { 42 } [0]")); Assert.That(InsertReadable(expr), Is.EqualTo("(new int[1] { 42 }) [0]")); } } }
ILSpy/ICSharpCode.Decompiler.Tests/Output/InsertParenthesesVisitorTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/Output/InsertParenthesesVisitorTests.cs", "repo_id": "ILSpy", "token_count": 5664 }
178
// 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; namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness { class ControlFlow { public static int Main() { int result = 0; EmptyIf("Empty", ref result); EmptyIf("test", ref result); NormalIf("none", ref result); NormalIf("test", ref result); NormalIf2("none", ref result); NormalIf2("test", ref result); NormalIf3("none", ref result); NormalIf3("test", ref result); Test("none", ref result); Test("test", ref result); Console.WriteLine(result); ForeachWithAssignment(new int[] { 1, 5, 25 }); BreakUnlessContinue(true); BreakUnlessContinue(false); TestConditionals(); Console.WriteLine("Issue1946:\n" + Issue1946()); return 0; } static void EmptyIf(string input, ref int result) { if (input.Contains("test")) { } result = result + 1; Console.WriteLine("EmptyIf"); } static void NormalIf(string input, ref int result) { if (input.Contains("test")) { Console.WriteLine("result"); } else { Console.WriteLine("else"); } result = result + 1; Console.WriteLine("end"); } static void NormalIf2(string input, ref int result) { if (input.Contains("test")) { Console.WriteLine("result"); } result = result + 1; Console.WriteLine("end"); } static void NormalIf3(string input, ref int result) { if (input.Contains("test")) { Console.WriteLine("result"); } else { Console.WriteLine("else"); } result = result + 1; } static void Test(string input, ref int result) { foreach (char c in input) { Console.Write(c); result = result + 1; } if (input.Contains("test")) { Console.WriteLine("result"); } else { Console.WriteLine("else"); } } int Dim2Search(int arg) { var tens = new[] { 10, 20, 30 }; var ones = new[] { 1, 2, 3 }; for (int i = 0; i < tens.Length; i++) { for (int j = 0; j < ones.Length; j++) { if (tens[i] + ones[j] == arg) return i; } } return -1; } static void ForeachWithAssignment(IEnumerable<int> inputs) { Console.WriteLine("ForeachWithAssignment"); foreach (int input in inputs) { int i = input; if (i < 10) i *= 2; Console.WriteLine(i); } } static void BreakUnlessContinue(bool b) { Console.WriteLine("BreakUnlessContinue({0})", b); for (int i = 0; i < 5; i++) { if ((i % 3) == 0) continue; Console.WriteLine(i); if (b) { Console.WriteLine("continuing"); continue; } Console.WriteLine("breaking out of loop"); break; } Console.WriteLine("BreakUnlessContinue (end)"); } static void TestConditionals() { Console.WriteLine(CastAfterConditional(0)); Console.WriteLine(CastAfterConditional(128)); } static byte CastAfterConditional(int value) { byte answer = (byte)(value == 128 ? 255 : 0); return answer; } static string Issue1946() { string obj = "1"; try { obj = "2"; } catch { obj = "3"; } finally { obj = "4"; } return obj; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/ControlFlow.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/ControlFlow.cs", "repo_id": "ILSpy", "token_count": 1694 }
179
// 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 System; namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness { class NullableTests { static void Main() { AvoidLifting(); BitNot(); FieldAccessOrderOfEvaluation(null); FieldAccessOrderOfEvaluationWithStruct(null); ArrayAccessOrderOfEvaluation(); } struct SomeStruct { public int IntField; } static void AvoidLifting() { Console.WriteLine("MayThrow:"); Console.WriteLine(MayThrow(10, 2, 3)); Console.WriteLine(MayThrow(10, 0, null)); Console.WriteLine("NotUsingAllInputs:"); Console.WriteLine(NotUsingAllInputs(5, 3)); Console.WriteLine(NotUsingAllInputs(5, null)); Console.WriteLine("UsingUntestedValue:"); Console.WriteLine(UsingUntestedValue(5, 3)); Console.WriteLine(UsingUntestedValue(5, null)); } static int? MayThrow(int? a, int? b, int? c) { // cannot be lifted without changing the exception behavior return a.HasValue & b.HasValue & c.HasValue ? a.GetValueOrDefault() / b.GetValueOrDefault() + c.GetValueOrDefault() : default(int?); } static int? NotUsingAllInputs(int? a, int? b) { // cannot be lifted because the value differs if b == null return a.HasValue & b.HasValue ? a.GetValueOrDefault() + a.GetValueOrDefault() : default(int?); } static int? UsingUntestedValue(int? a, int? b) { // cannot be lifted because the value differs if b == null return a.HasValue ? a.GetValueOrDefault() + b.GetValueOrDefault() : default(int?); } static void BitNot() { UInt32? value = 0; Assert(~value == UInt32.MaxValue); UInt64? value2 = 0; Assert(~value2 == UInt64.MaxValue); UInt16? value3 = 0; Assert((UInt16)~value3 == (UInt16)UInt16.MaxValue); UInt32 value4 = 0; Assert(~value4 == UInt32.MaxValue); UInt64 value5 = 0; Assert(~value5 == UInt64.MaxValue); UInt16 value6 = 0; Assert((UInt16)~value6 == UInt16.MaxValue); } static void Assert(bool b) { if (!b) throw new InvalidOperationException(); } static T GetValue<T>() { Console.WriteLine("GetValue"); return default(T); } int intField; static void FieldAccessOrderOfEvaluation(NullableTests c) { Console.WriteLine("GetInt, then NRE:"); try { c.intField = GetValue<int>(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("NRE before GetInt:"); try { #if CS70 ref int i = ref c.intField; i = GetValue<int>(); #endif } catch (Exception ex) { Console.WriteLine(ex.Message); } } SomeStruct structField; static void FieldAccessOrderOfEvaluationWithStruct(NullableTests c) { Console.WriteLine("GetInt, then NRE (with struct):"); try { c.structField.IntField = GetValue<int>(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("NRE before GetInt (with struct):"); try { #if CS70 ref SomeStruct s = ref c.structField; s.IntField = GetValue<int>(); #endif } catch (Exception ex) { Console.WriteLine(ex.Message); } } static T[] GetArray<T>() { Console.WriteLine("GetArray"); return null; } static int GetIndex() { Console.WriteLine("GetIndex"); return 0; } static void ArrayAccessOrderOfEvaluation() { Console.WriteLine("GetArray direct:"); try { GetArray<int>()[GetIndex()] = GetValue<int>(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("GetArray with ref:"); try { #if CS70 ref int elem = ref GetArray<int>()[GetIndex()]; elem = GetValue<int>(); #endif } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("GetArray direct with value-type:"); try { // This line is mis-compiled by legacy csc: // with the legacy compiler the NRE is thrown before the GetValue call; // with Roslyn the NRE is thrown after the GetValue call. GetArray<TimeSpan>()[GetIndex()] = GetValue<TimeSpan>(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/NullableTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/NullableTests.cs", "repo_id": "ILSpy", "token_count": 2013 }
180
.assembly extern mscorlib { .publickeytoken = ( b7 7a 5c 56 19 34 e0 89 ) .ver 4:0:0:0 } .assembly InterfaceImplAttributes { .custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = ( 01 00 07 31 2e 30 2e 30 2e 30 00 00 ) .hash algorithm 0x00008004 // SHA1 .ver 1:0:0:0 } .module InterfaceImplAttributes.dll .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WindowsCui .corflags 0x00000001 // ILOnly .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi beforefieldinit TestType extends [mscorlib]System.Object implements ITestInterfaceA { .interfaceimpl type ITestInterfaceA .custom instance void TestAttributeA::.ctor() = ( 01 00 00 00 ) // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Header size: 1 // Code size: 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method TestType::.ctor } // end of class TestType .class interface public auto ansi abstract ITestInterfaceA { } // end of class ITestInterfaceA .class public auto ansi beforefieldinit TestAttributeA extends [mscorlib]System.Attribute { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2058 // Header size: 1 // Code size: 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: ret } // end of method TestAttributeA::.ctor } // end of class TestAttributeA
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Disassembler/Pretty/InterfaceImplAttributes.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Disassembler/Pretty/InterfaceImplAttributes.il", "repo_id": "ILSpy", "token_count": 618 }
181
#define CORE_ASSEMBLY "System.Runtime" .assembly extern CORE_ASSEMBLY { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: .ver 4:0:0:0 } .class private auto ansi beforefieldinit EmptyBodies extends [CORE_ASSEMBLY]System.Object { // I cannot test a truly empty body because the assembler will automatically add a ret instruction. .method public hidebysig static void RetVoid () cil managed { .maxstack 8 ret } .method public hidebysig static int32 RetInt () cil managed { .maxstack 8 ret } .method public hidebysig static void Nop () cil managed { .maxstack 8 nop } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x206e // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Private.CoreLib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Example::.ctor } // end of class EmptyBodies
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/EmptyBodies.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/EmptyBodies.il", "repo_id": "ILSpy", "token_count": 464 }
182
// 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 extern System { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System.Core { .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 public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<TK, class .ctor TR> { // Fields .field private class [System.Core]System.Action`2<!TK, !TR> TestEvent .field private static class [System.Core]System.Action`2<!TK, !TR> '<>f__am$cache0' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 ldarg.0 ldsfld class [System.Core]System.Action`2<!0, !1> class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::'<>f__am$cache0' brtrue.s IL_0019 ldnull ldftn void class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::'<TestEvent>m__0'(!0, !1) newobj instance void class [System.Core]System.Action`2<!TK, !TR>::.ctor(object, native int) stsfld class [System.Core]System.Action`2<!0, !1> class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::'<>f__am$cache0' IL_0019: ldsfld class [System.Core]System.Action`2<!0, !1> class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::'<>f__am$cache0' stfld class [System.Core]System.Action`2<!0, !1> class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::TestEvent ret } .method public hidebysig specialname instance void add_TestEvent (class [System.Core]System.Action`2<!TK, !TR> 'value') cil managed { .maxstack 3 .locals init ( [0] class [System.Core]System.Action`2<!TK, !TR>, [1] class [System.Core]System.Action`2<!TK, !TR> ) ldarg.0 ldfld class [System.Core]System.Action`2<!0, !1> class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::TestEvent stloc.0 IL_0007: ldloc.0 stloc.1 ldarg.0 ldflda class [System.Core]System.Action`2<!0, !1> class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::TestEvent ldloc.1 ldarg.1 call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) castclass class [System.Core]System.Action`2<!TK, !TR> ldloc.0 call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [System.Core]System.Action`2<!TK, !TR>>(!!0&, !!0, !!0) stloc.0 ldloc.0 ldloc.1 bne.un IL_0007 ret } .method public hidebysig specialname instance void remove_TestEvent (class [System.Core]System.Action`2<!TK, !TR> 'value') cil managed { .maxstack 3 .locals init ( [0] class [System.Core]System.Action`2<!TK, !TR>, [1] class [System.Core]System.Action`2<!TK, !TR> ) ldarg.0 ldfld class [System.Core]System.Action`2<!0, !1> class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::TestEvent stloc.0 IL_0007: ldloc.0 stloc.1 ldarg.0 ldflda class [System.Core]System.Action`2<!0, !1> class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2<!TK, !TR>::TestEvent ldloc.1 ldarg.1 call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) castclass class [System.Core]System.Action`2<!TK, !TR> ldloc.0 call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [System.Core]System.Action`2<!TK, !TR>>(!!0&, !!0, !!0) stloc.0 ldloc.0 ldloc.1 bne.un IL_0007 ret } .method private hidebysig static void '<TestEvent>m__0' (!TK '', !TR '') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 ret } // Events .event class [System.Core]System.Action`2<!TK, !TR> TestEvent { .addon instance void ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2::add_TestEvent(class [System.Core]System.Action`2<!0, !1>) .removeon instance void ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1038`2::remove_TestEvent(class [System.Core]System.Action`2<!0, !1>) } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1038.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1038.il", "repo_id": "ILSpy", "token_count": 2139 }
183
using System.Collections; namespace ICSharpCode.Decompiler.Tests.TestCases.ILPretty { public class Issue1454 { public static int GetCardinality(BitArray bitArray) { int[] array = new int[(bitArray.Count >> 5) + 1]; bitArray.CopyTo(array, 0); int num = 0; array[array.Length - 1] &= ~(-1 << bitArray.Count % 32); for (int i = 0; i < array.Length; i++) { int num2 = array[i]; num2 -= (num2 >> 1) & 0x55555555; num2 = (num2 & 0x33333333) + ((num2 >> 2) & 0x33333333); num2 = ((num2 + (num2 >> 4)) & 0xF0F0F0F) * 16843009 >> 24; num += num2; } return num; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1454.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1454.cs", "repo_id": "ILSpy", "token_count": 288 }
184
using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.VisualBasic.CompilerServices; namespace ICSharpCode.Decompiler.Tests.TestCases.ILPretty { [StandardModule] internal sealed class Issue646 { [STAThread] public static void Main() { List<string> list = new List<string>(); foreach (string item in list) { Debug.WriteLine(item); } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue646.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue646.cs", "repo_id": "ILSpy", "token_count": 154 }
185
using System; namespace TestEnum { public enum BooleanEnum : bool { Min = false, Zero = false, One = true, Max = byte.MaxValue } public enum EnumWithNestedClass { #pragma warning disable format // error: nested types are not permitted in C#. public class NestedClass { } , #pragma warning enable format Zero, One } public enum NativeIntEnum : IntPtr { Zero = 0L, One = 1L, FortyTwo = 42L } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/WeirdEnums.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/WeirdEnums.cs", "repo_id": "ILSpy", "token_count": 181 }
186
using System; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class AsyncUsing { internal class AsyncDisposableClass : IAsyncDisposable { public ValueTask DisposeAsync() { throw new NotImplementedException(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct AsyncDisposableStruct : IAsyncDisposable { public ValueTask DisposeAsync() { throw new NotImplementedException(); } } public static async void TestAsyncUsing(IAsyncDisposable disposable) { await using (disposable) { Console.WriteLine("Hello"); } } public static async void TestAsyncUsingClass() { await using (AsyncDisposableClass test = new AsyncDisposableClass()) { Use(test); } } public static async void TestAsyncUsingStruct() { await using (AsyncDisposableStruct asyncDisposableStruct = default(AsyncDisposableStruct)) { Use(asyncDisposableStruct); } } public static async void TestAsyncUsingNullableStruct() { await using (AsyncDisposableStruct? asyncDisposableStruct = new AsyncDisposableStruct?(default(AsyncDisposableStruct))) { Use(asyncDisposableStruct); } } private static void Use(IAsyncDisposable test) { throw new NotImplementedException(); } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/AsyncUsing.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/AsyncUsing.cs", "repo_id": "ILSpy", "token_count": 510 }
187
// Copyright (c) 2020 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.Runtime.InteropServices; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public static class DeconstructionExt { public static void Deconstruct<K, V>(this KeyValuePair<K, V> pair, out K key, out V value) { key = pair.Key; value = pair.Value; } } internal class DeconstructionTests { [StructLayout(LayoutKind.Sequential, Size = 1)] public struct MyInt { public static implicit operator int(MyInt x) { return 0; } public static implicit operator MyInt(int x) { return default(MyInt); } } private class DeconstructionSource<T, T2> { public int Dummy { get; set; } public void Deconstruct(out T a, out T2 b) { a = default(T); b = default(T2); } } private class DeconstructionSource<T, T2, T3> { public int Dummy { get; set; } public void Deconstruct(out T a, out T2 b, out T3 c) { a = default(T); b = default(T2); c = default(T3); } } private class AssignmentTargets { public int IntField; public long LongField; public float FloatField; public double DoubleField; public decimal DecimalField; public MyInt MyField; public MyInt? NMyField; public string StringField; public object ObjectField; public dynamic DynamicField; public int? NullableIntField; public MyInt MyIntField; public MyInt? NullableMyIntField; public int Int { get; set; } public long Long { get; set; } public float Float { get; set; } public double Double { get; set; } public decimal Decimal { get; set; } public string String { get; set; } public object Object { get; set; } public dynamic Dynamic { get; set; } public int? NInt { get; set; } public MyInt My { get; set; } public MyInt? NMy { get; set; } public static MyInt StaticMy { get; set; } public static MyInt? StaticNMy { get; set; } } private DeconstructionSource<T, T2> GetSource<T, T2>() { return null; } private DeconstructionSource<T, T2, T3> GetSource<T, T2, T3>() { return null; } private ref T GetRef<T>() { throw new NotImplementedException(); } private (T, T2) GetTuple<T, T2>() { return default((T, T2)); } private (T, T2, T3) GetTuple<T, T2, T3>() { return default((T, T2, T3)); } private AssignmentTargets Get(int i) { return null; } public void LocalVariable_NoConversion_Custom() { var (myInt3, myInt4) = GetSource<MyInt?, MyInt>(); Console.WriteLine(myInt3); Console.WriteLine(myInt4); } public void LocalVariable_NoConversion_Tuple() { var (myInt, myInt2) = GetTuple<MyInt?, MyInt>(); Console.WriteLine(myInt); Console.WriteLine(myInt2); } public void LocalVariable_NoConversion_Custom_DiscardFirst() { var (_, myInt3, value) = GetSource<MyInt?, MyInt, int>(); Console.WriteLine(myInt3); Console.WriteLine(value); } // currently we detect deconstruction, iff the first element is not discarded //public void LocalVariable_NoConversion_Tuple_DiscardFirst() //{ // var (_, x, value) = GetTuple<MyInt?, MyInt, int>(); // Console.WriteLine(x); // Console.WriteLine(value); //} public void LocalVariable_NoConversion_Custom_DiscardLast() { var (myInt3, myInt4, _) = GetSource<MyInt?, MyInt, int>(); Console.WriteLine(myInt3); Console.WriteLine(myInt4); } public void LocalVariable_NoConversion_Tuple_DiscardLast() { var (myInt, myInt2, _) = GetTuple<MyInt?, MyInt, int>(); Console.WriteLine(myInt); Console.WriteLine(myInt2); } public void LocalVariable_NoConversion_Custom_DiscardSecond() { var (myInt3, _, value) = GetSource<MyInt?, MyInt, int>(); Console.WriteLine(myInt3); Console.WriteLine(value); } public void LocalVariable_NoConversion_Tuple_DiscardSecond() { var (myInt, _, value) = GetTuple<MyInt?, MyInt, int>(); Console.WriteLine(myInt); Console.WriteLine(value); } public void LocalVariable_NoConversion_Custom_ReferenceTypes() { var (value, value2) = GetSource<string, string>(); Console.WriteLine(value); Console.WriteLine(value2); } public void LocalVariable_NoConversion_Tuple_ReferenceTypes() { var (value, value2) = GetTuple<string, string>(); Console.WriteLine(value); Console.WriteLine(value2); } public void Issue2378(Tuple<object, object> tuple) { var (value, value2) = tuple; Console.WriteLine(value2); Console.WriteLine(value); } public void Issue2378_IntToLongConversion(Tuple<int, int> tuple) { int value; long value2; (value, value2) = tuple; Console.WriteLine(value2); Console.WriteLine(value); } public void LocalVariable_IntToLongConversion_Custom() { int value; long value2; (value, value2) = GetSource<int, int>(); Console.WriteLine(value); Console.WriteLine(value2); } public void LocalVariable_IntToLongConversion_Tuple() { int value; long value2; (value, value2) = GetTuple<int, int>(); Console.WriteLine(value); Console.WriteLine(value2); } public void LocalVariable_FloatToDoubleConversion_Custom() { int value; double value2; (value, value2) = GetSource<int, float>(); Console.WriteLine(value); Console.WriteLine(value2); } public void LocalVariable_FloatToDoubleConversion_Tuple() { int value; double value2; (value, value2) = GetTuple<int, float>(); Console.WriteLine(value); Console.WriteLine(value2); } // dynamic conversion is currently not supported //public void LocalVariable_ImplicitReferenceConversion_Custom() //{ // object value; // dynamic value2; // (value, value2) = GetSource<string, string>(); // Console.WriteLine(value); // value2.UseMe(); //} //public void LocalVariable_ImplicitReferenceConversion_Tuple() //{ // object value; // dynamic value2; // (value, value2) = GetTuple<string, string>(); // Console.WriteLine(value); // value2.UseMe(); //} public void LocalVariable_NoConversion_ComplexValue_Custom() { var (myInt3, myInt4) = new DeconstructionSource<MyInt?, MyInt> { Dummy = 3 }; Console.WriteLine(myInt3); Console.WriteLine(myInt4); } public void Property_NoConversion_Custom() { (Get(0).NMy, Get(1).My) = GetSource<MyInt?, MyInt>(); } public void Property_IntToLongConversion_Custom() { (Get(0).Int, Get(1).Long) = GetSource<int, int>(); } public void Property_FloatToDoubleConversion_Custom() { (Get(0).Int, Get(1).Double) = GetSource<int, float>(); } // dynamic conversion is not supported //public void Property_ImplicitReferenceConversion_Custom() //{ // (Get(0).Object, Get(1).Dynamic) = GetSource<string, string>(); //} public void Property_NoConversion_Custom_DiscardFirst() { (_, Get(1).My) = GetSource<MyInt?, MyInt>(); } public void Property_NoConversion_Custom_DiscardLast() { (Get(0).NMy, _) = GetSource<MyInt?, MyInt>(); } public void Property_NoConversion_Tuple() { (Get(0).NMy, Get(1).My) = GetTuple<MyInt?, MyInt>(); } public void Property_NoConversion_Tuple_DiscardLast() { (Get(0).NMy, Get(1).My, _) = GetTuple<MyInt?, MyInt, int>(); } // currently we detect deconstruction, iff the first element is not discarded //public void Property_NoConversion_Tuple_DiscardFirst() //{ // (_, Get(1).My, Get(2).Int) = GetTuple<MyInt?, MyInt, int>(); //} public void Property_NoConversion_Custom_DiscardSecond() { (Get(0).NMy, _, Get(2).Int) = GetSource<MyInt?, MyInt, int>(); } public void Property_NoConversion_Tuple_DiscardSecond() { (Get(0).NMy, _, Get(2).Int) = GetTuple<MyInt?, MyInt, int>(); } public void Property_NoConversion_Custom_ReferenceTypes() { (Get(0).String, Get(1).String) = GetSource<string, string>(); } public void Property_NoConversion_Tuple_ReferenceTypes() { (Get(0).String, Get(1).String) = GetTuple<string, string>(); } public void Property_IntToLongConversion_Tuple() { (Get(0).Int, Get(1).Long) = GetTuple<int, int>(); } public void Property_FloatToDoubleConversion_Tuple() { (Get(0).Int, Get(1).Double) = GetTuple<int, float>(); } public void RefLocal_NoConversion_Custom(out double a) { (a, GetRef<float>()) = GetSource<double, float>(); } public void RefLocal_NoConversion_Tuple(out double a) { (a, GetRef<float>()) = GetTuple<double, float>(); } public void RefLocal_FloatToDoubleConversion_Custom(out double a) { (a, GetRef<double>()) = GetSource<double, float>(); } public void RefLocal_FloatToDoubleConversion_Custom2(out double a) { (a, GetRef<double>()) = GetSource<float, float>(); } public void RefLocal_FloatToDoubleConversion_Tuple(out double a) { (a, GetRef<double>()) = GetTuple<double, float>(); } public void RefLocal_NoConversion_Custom(out MyInt? a) { (a, GetRef<MyInt>()) = GetSource<MyInt?, MyInt>(); } public void RefLocal_IntToLongConversion_Custom(out long a) { (a, GetRef<long>()) = GetSource<int, int>(); } // dynamic conversion is not supported //public void RefLocal_ImplicitReferenceConversion_Custom(out object a) //{ // (a, GetRef<dynamic>()) = GetSource<string, string>(); //} public void RefLocal_NoConversion_Custom_DiscardFirst() { (_, GetRef<MyInt>()) = GetSource<MyInt?, MyInt>(); } public void RefLocal_NoConversion_Custom_DiscardLast(out MyInt? a) { (a, _) = GetSource<MyInt?, MyInt>(); } public void RefLocal_NoConversion_Tuple(out MyInt? a) { (a, GetRef<MyInt>()) = GetTuple<MyInt?, MyInt>(); } public void RefLocal_NoConversion_Tuple_DiscardLast(out MyInt? a) { (a, GetRef<MyInt>(), _) = GetTuple<MyInt?, MyInt, int>(); } // currently we detect deconstruction, iff the first element is not discarded //public void RefLocal_NoConversion_Tuple_DiscardFirst(out var a) //{ // (_, GetRef<var>(), GetRef<var>()) = GetTuple<MyInt?, MyInt, int>(); //} public void RefLocal_NoConversion_Custom_DiscardSecond(out MyInt? a) { (a, _, GetRef<int>()) = GetSource<MyInt?, MyInt, int>(); } public void RefLocal_NoConversion_Tuple_DiscardSecond(out MyInt? a) { (a, _, GetRef<int>()) = GetTuple<MyInt?, MyInt, int>(); } public void RefLocal_NoConversion_Custom_ReferenceTypes(out string a) { (a, GetRef<string>()) = GetSource<string, string>(); } public void RefLocal_NoConversion_Tuple_ReferenceTypes(out string a) { (a, GetRef<string>()) = GetTuple<string, string>(); } public void RefLocal_IntToLongConversion_Tuple(out long a) { (a, GetRef<long>()) = GetTuple<int, int>(); } //public void ArrayAssign_FloatToDoubleConversion_Custom(double[] arr) //{ // (arr[0], arr[1], arr[2]) = GetSource<double, float, double>(); //} public void Field_NoConversion_Custom() { (Get(0).IntField, Get(1).IntField) = GetSource<int, int>(); } public void Field_NoConversion_Tuple() { (Get(0).IntField, Get(1).IntField) = GetTuple<int, int>(); } public void Field_IntToLongConversion_Custom() { (Get(0).IntField, Get(1).LongField) = GetSource<int, int>(); } public void Field_IntToLongConversion_Tuple() { (Get(0).IntField, Get(1).LongField) = GetTuple<int, int>(); } public void Field_FloatToDoubleConversion_Custom() { (Get(0).DoubleField, Get(1).DoubleField) = GetSource<double, float>(); } public void Field_FloatToDoubleConversion_Tuple() { (Get(0).DoubleField, Get(1).DoubleField) = GetTuple<double, float>(); } // dynamic conversion is not supported //public void Field_ImplicitReferenceConversion_Custom() //{ // (Get(0).ObjectField, Get(1).DynamicField) = GetSource<string, string>(); //} public void Field_NoConversion_Custom_DiscardFirst() { (_, Get(1).MyField) = GetSource<MyInt?, MyInt>(); } public void Field_NoConversion_Custom_DiscardLast() { (Get(0).NMyField, _) = GetSource<MyInt?, MyInt>(); } public void Field_NoConversion_Tuple_DiscardLast() { (Get(0).NMyField, Get(1).MyField, _) = GetTuple<MyInt?, MyInt, int>(); } // currently we detect deconstruction, iff the first element is not discarded //public void Field_NoConversion_Tuple_DiscardFirst() //{ // (_, Get(1).MyField, Get(2).IntField) = GetTuple<MyInt?, MyInt, int>(); //} public void Field_NoConversion_Custom_DiscardSecond() { (Get(0).NMyField, _, Get(2).IntField) = GetSource<MyInt?, MyInt, int>(); } public void Field_NoConversion_Tuple_DiscardSecond() { (Get(0).NMyField, _, Get(2).IntField) = GetTuple<MyInt?, MyInt, int>(); } public void Field_NoConversion_Custom_ReferenceTypes() { (Get(0).StringField, Get(1).StringField) = GetSource<string, string>(); } public void Field_NoConversion_Tuple_ReferenceTypes() { (Get(0).StringField, Get(1).StringField) = GetTuple<string, string>(); } public void DeconstructDictionaryForEach(Dictionary<string, int> dictionary) { foreach (var (text2, num2) in dictionary) { Console.WriteLine(text2 + ": " + num2); } } public void DeconstructTupleListForEach(List<(string, int)> tuples) { foreach (var (text, num) in tuples) { Console.WriteLine(text + ": " + num); } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/DeconstructionTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/DeconstructionTests.cs", "repo_id": "ILSpy", "token_count": 5700 }
188
using ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceA; using ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceA.SpaceB; using ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceC; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080 { internal static class ExtensionsTest { private static void Dummy(ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceA.SpaceB.Type2 intf) { } private static void Test(object obj) { ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceA.Type2 type = obj as ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceA.Type2; if (type != null) { ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceC.Extensions.Extension(type); } } } } namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceA { internal interface Type2 : ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceA.SpaceB.Type2, Type1 { } } namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceA.SpaceB { internal static class Extensions { public static void Extension(this Type1 obj) { } } internal interface Type1 { } internal interface Type2 : Type1 { } } namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1080.SpaceC { internal static class Extensions { public static void Extension(this Type1 obj) { } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/Issue1080.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/Issue1080.cs", "repo_id": "ILSpy", "token_count": 533 }
189
using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public class PatternMatching { public class X { public int? NullableIntField; public S? NullableCustomStructField; public int I { get; set; } public string Text { get; set; } public object Obj { get; set; } public S CustomStruct { get; set; } public int? NullableIntProp { get; set; } public S? NullableCustomStructProp { get; set; } } public struct S { public int I; public string Text { get; set; } public object Obj { get; set; } public S2 S2 { get; set; } } public struct S2 { public int I; public float F; public decimal D; public string Text { get; set; } public object Obj { get; set; } } public void SimpleTypePattern(object x) { if (x is string value) { Console.WriteLine(value); } } public void TypePatternWithShortcircuit(object x) { Use(F() && x is string text && text.Contains("a")); if (F() && x is string text2 && text2.Contains("a")) { Console.WriteLine(text2); } } public void TypePatternWithShortcircuitAnd(object x) { if (x is string text && text.Contains("a")) { Console.WriteLine(text); } else { Console.WriteLine(); } } public void TypePatternWithShortcircuitOr(object x) { if (!(x is string text) || text.Contains("a")) { Console.WriteLine(); } else { Console.WriteLine(text); } } public void TypePatternWithShortcircuitOr2(object x) { if (F() || !(x is string value)) { Console.WriteLine(); } else { Console.WriteLine(value); } } public void TypePatternValueTypesCondition(object x) { if (x is int num) { Console.WriteLine("Integer: " + num); } else { Console.WriteLine("else"); } } public void TypePatternValueTypesCondition2() { if (GetObject() is int num) { Console.WriteLine("Integer: " + num); } else { Console.WriteLine("else"); } } public void TypePatternValueTypesWithShortcircuitAnd(object x) { if (x is int num && num.GetHashCode() > 0) { Console.WriteLine("Positive integer: " + num); } else { Console.WriteLine("else"); } } public void TypePatternValueTypesWithShortcircuitOr(object x) { if (!(x is int value) || value.GetHashCode() > 0) { Console.WriteLine(); } else { Console.WriteLine(value); } } #if ROSLYN3 || OPT // Roslyn 2.x generates a complex infeasible path in debug builds, which RemoveInfeasiblePathTransform // currently cannot handle. Because this would increase the complexity of that transform, we ignore // this case. public void TypePatternValueTypesWithShortcircuitOr2(object x) { if (F() || !(x is int value)) { Console.WriteLine(); } else { Console.WriteLine(value); } } #endif public void TypePatternGenerics<T>(object x) { if (x is T val) { Console.WriteLine(val.GetType().FullName); } else { Console.WriteLine("not a " + typeof(T).FullName); } } public void TypePatternGenericRefType<T>(object x) where T : class { if (x is T val) { Console.WriteLine(val.GetType().FullName); } else { Console.WriteLine("not a " + typeof(T).FullName); } } public void TypePatternGenericValType<T>(object x) where T : struct { if (x is T val) { Console.WriteLine(val.GetType().FullName); } else { Console.WriteLine("not a " + typeof(T).FullName); } } public void TypePatternValueTypesWithShortcircuitAndMultiUse(object x) { if (x is int num && num.GetHashCode() > 0 && num % 2 == 0) { Console.WriteLine("Positive integer: " + num); } else { Console.WriteLine("else"); } } public void TypePatternValueTypesWithShortcircuitAndMultiUse2(object x) { if ((x is int num && num.GetHashCode() > 0 && num % 2 == 0) || F()) { Console.WriteLine("true"); } else { Console.WriteLine("else"); } } public void TypePatternValueTypesWithShortcircuitAndMultiUse3(object x) { if (F() || (x is int num && num.GetHashCode() > 0 && num % 2 == 0)) { Console.WriteLine("true"); } else { Console.WriteLine("else"); } } public void TypePatternValueTypes() { Use(F() && GetObject() is int num && num.GetHashCode() > 0 && num % 2 == 0); } public static void NotTypePatternVariableUsedOutsideTrueBranch(object x) { string text = x as string; if (text != null && text.Length > 5) { Console.WriteLine("pattern matches"); } if (text != null && text.Length > 10) { Console.WriteLine("other use!"); } } public static void NotTypePatternBecauseVarIsNotDefAssignedInCaseOfFallthrough(object x) { #if OPT string obj = x as string; if (obj == null) { Console.WriteLine("pattern doesn't match"); } Console.WriteLine(obj == null); #else string text = x as string; if (text == null) { Console.WriteLine("pattern doesn't match"); } Console.WriteLine(text == null); #endif } public void GenericTypePatternInt<T>(T x) { if (x is int value) { Console.WriteLine(value); } else { Console.WriteLine("not an int"); } } public void GenericValueTypePatternInt<T>(T x) where T : struct { if (x is int value) { Console.WriteLine(value); } else { Console.WriteLine("not an int"); } } public void GenericRefTypePatternInt<T>(T x) where T : class { if (x is int value) { Console.WriteLine(value); } else { Console.WriteLine("not an int"); } } public void GenericTypePatternString<T>(T x) { if (x is string value) { Console.WriteLine(value); } else { Console.WriteLine("not a string"); } } public void GenericRefTypePatternString<T>(T x) where T : class { if (x is string value) { Console.WriteLine(value); } else { Console.WriteLine("not a string"); } } public void GenericValueTypePatternStringRequiresCastToObject<T>(T x) where T : struct { if ((object)x is string value) { Console.WriteLine(value); } else { Console.WriteLine("not a string"); } } #if CS80 public void RecursivePattern_Type(object x) { if (x is X { Obj: string obj }) { Console.WriteLine("Test " + obj); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_TypeAndConst(object x) { if (x is X { Obj: string obj, I: 42 }) { Console.WriteLine("Test " + obj); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_Constant(object obj) { if (obj is X { Obj: null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_StringConstant(object obj) { if (obj is X { Text: "Hello" } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_MultipleConstants(object obj) { if (obj is X { I: 42, Text: "Hello" } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_ValueTypeWithField(object obj) { if (obj is S { I: 42 } s) { Console.WriteLine("Test " + s); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_MultipleConstantsMixedWithVar(object x) { if (x is X { I: 42, Obj: var obj, Text: "Hello" }) { Console.WriteLine("Test " + obj); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NonTypePattern(object obj) { if (obj is X { I: 42, Text: { Length: 0 } } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePatternValueType_NonTypePatternTwoProps(object obj) { if (obj is X { I: 42, CustomStruct: { I: 0, Text: "Test" } } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NonTypePatternNotNull(object o) { if (o is X { I: 42, Text: not null, Obj: var obj } x) { Console.WriteLine("Test " + x.I + " " + obj.GetType()); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_VarLengthPattern(object obj) { if (obj is X { I: 42, Text: { Length: var length } } x) { Console.WriteLine("Test " + x.I + ": " + length); } else { Console.WriteLine("not Test"); } } public void RecursivePatternValueType_VarLengthPattern(object obj) { if (obj is S { I: 42, Text: { Length: var length } } s) { Console.WriteLine("Test " + s.I + ": " + length); } else { Console.WriteLine("not Test"); } } public void RecursivePatternValueType_VarLengthPattern_SwappedProps(object obj) { if (obj is S { Text: { Length: var length }, I: 42 } s) { Console.WriteLine("Test " + s.I + ": " + length); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_VarLengthPattern_SwappedProps(object obj) { if (obj is X { Text: { Length: var length }, I: 42 } x) { Console.WriteLine("Test " + x.I + ": " + length); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableIntField_Const(object obj) { if (obj is X { NullableIntField: 42 } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableIntField_Null(object obj) { if (obj is X { NullableIntField: null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableIntField_NotNull(object obj) { if (obj is X { NullableIntField: not null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableIntField_Var(object obj) { if (obj is X { NullableIntField: var nullableIntField }) { Console.WriteLine("Test " + nullableIntField.Value); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableIntProp_Const(object obj) { if (obj is X { NullableIntProp: 42 } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableIntProp_Null(object obj) { if (obj is X { NullableIntProp: null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableIntProp_NotNull(object obj) { if (obj is X { NullableIntProp: not null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableIntProp_Var(object obj) { if (obj is X { NullableIntProp: var nullableIntProp }) { Console.WriteLine("Test " + nullableIntProp.Value); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableCustomStructField_Const(object obj) { if (obj is X { NullableCustomStructField: { I: 42, Obj: not null } nullableCustomStructField }) { Console.WriteLine("Test " + nullableCustomStructField.I); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableCustomStructField_Null(object obj) { if (obj is X { NullableCustomStructField: null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableCustomStructField_NotNull(object obj) { if (obj is X { NullableCustomStructField: not null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableCustomStructField_Var(object obj) { if (obj is X { NullableCustomStructField: var nullableCustomStructField, Obj: null }) { Console.WriteLine("Test " + nullableCustomStructField.Value); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableCustomStructProp_Const(object obj) { if (obj is X { NullableCustomStructProp: { I: 42, Obj: not null } nullableCustomStructProp }) { Console.WriteLine("Test " + nullableCustomStructProp.Text); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableCustomStructProp_Null(object obj) { if (obj is X { NullableCustomStructProp: null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableCustomStructProp_NotNull(object obj) { if (obj is X { NullableCustomStructProp: not null } x) { Console.WriteLine("Test " + x); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_NullableCustomStructProp_Var(object obj) { if (obj is X { NullableCustomStructProp: var nullableCustomStructProp, Obj: null }) { Console.WriteLine("Test " + nullableCustomStructProp.Value); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_CustomStructNested_Null(object obj) { if (obj is S { S2: { Obj: null } }) { Console.WriteLine("Test " + obj); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_CustomStructNested_TextLengthZero(object obj) { if (obj is S { S2: { Text: { Length: 0 } } }) { Console.WriteLine("Test " + obj); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_CustomStructNested_EmptyString(object obj) { if (obj is S { S2: { Text: "" } }) { Console.WriteLine("Test " + obj); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_CustomStructNested_Float(object obj) { if (obj is S { S2: { F: 3.141f, Obj: null } }) { Console.WriteLine("Test " + obj); } else { Console.WriteLine("not Test"); } } public void RecursivePattern_CustomStructNested_Decimal(object obj) { if (obj is S { S2: { D: 3.141m, Obj: null } }) { Console.WriteLine("Test " + obj); } else { Console.WriteLine("not Test"); } } #endif private bool F() { return true; } private object GetObject() { throw new NotImplementedException(); } private void Use(bool x) { } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/PatternMatching.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/PatternMatching.cs", "repo_id": "ILSpy", "token_count": 6462 }
190
// 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; using System.Collections.Generic; using System.Linq; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public class TupleTests { private abstract class OverloadResolution { public abstract void M1((long, long) a); public abstract void M1(object a); public void UseM1((int, int) a) { // M1(a); TODO: tuple conversion transform // Cast is required to avoid the overload usable via tuple conversion: M1((object)a); } } public struct GenericStruct<T> { public T Field; public T Property { get; set; } } public ValueTuple VT0; public ValueTuple<int> VT1; public ValueTuple<int, int, int, int, int, int, int, ValueTuple> VT7EmptyRest; public (int, uint) Unnamed2; public (int, int, int) Unnamed3; public (int, int, int, int) Unnamed4; public (int, int, int, int, int) Unnamed5; public (int, int, int, int, int, int) Unnamed6; public (int, int, int, int, int, int, int) Unnamed7; public (int, int, int, int, int, int, int, int) Unnamed8; public (int a, uint b) Named2; public (int a, uint b)[] Named2Array; public (int a, int b, int c, int d, int e, int f, int g, int h) Named8; public (int, int a, int, int b, int) PartiallyNamed; public ((int a, int b) x, (int, int) y, (int c, int d) z) Nested1; public ((object a, dynamic b), dynamic, (dynamic c, object d)) Nested2; public (ValueTuple a, (int x1, int x2), ValueTuple<int> b, (int y1, int y2), (int, int) c) Nested3; public (int a, int b, int c, int d, int e, int f, int g, int h, (int i, int j)) Nested4; public Dictionary<(int a, string b), (string c, int d)> TupleDict; public List<(int, string)> List; public bool HasItems => List.Any(((int, string) a) => a.Item1 > 0); public int VT1Member => VT1.Item1; public int AccessUnnamed8 => Unnamed8.Item8; public int AccessNamed8 => Named8.h; public int AccessPartiallyNamed => PartiallyNamed.a + PartiallyNamed.Item3; public ValueTuple<int> NewTuple1 => new ValueTuple<int>(1); public (int a, int b) NewTuple2 => (a: 1, b: 2); public object BoxedTuple10 => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); public (uint, int) SwapUnnamed => (Unnamed2.Item2, Unnamed2.Item1); public (uint, int) SwapNamed2 => (Named2.b, Named2.a); public int TupleHash => (1, 2, 3).GetHashCode(); public int TupleHash2 => Named2.GetHashCode(); public (int, int) AccessRest => (1, 2, 3, 4, 5, 6, 7, 8, 9).Rest; public (string, object, Action) TargetTyping => (null, 1, delegate { #pragma warning disable format }); #pragma warning restore format public object NotTargetTyping => ((string)null, (object)1, (Action)delegate { #pragma warning disable format }); #pragma warning restore format public void UnnamedTupleOut(out (int, string, Action, dynamic) tuple) { tuple = (42, "Hello", Console.WriteLine, null); } public void UnnamedTupleIn(in (int, string, Action, dynamic) tuple) { } public void UnnamedTupleRef(ref (int, string, Action, dynamic) tuple) { } public void NamedTupleOut(out (int A, string B, Action C, dynamic D) tuple) { tuple = (A: 42, B: "Hello", C: Console.WriteLine, D: null); } public void NamedTupleIn(in (int A, string B, Action C, dynamic D) tuple) { } public void NamedTupleRef(ref (int A, string B, Action C, dynamic D) tuple) { } public void UseDict() { if (TupleDict.Count > 10) { TupleDict.Clear(); } // TODO: it would be nice if we could infer the name 'c' for the local string item = TupleDict[(1, "abc")].c; Console.WriteLine(item); Console.WriteLine(item); Console.WriteLine(TupleDict.Values.ToList().First().d); } private static (string, string) Issue3014a(string[] args) { return (from v in args select (Name: v, Value: v) into kvp orderby kvp.Name select kvp).First(); } private static (string, string) Issue3014b(string[] args) { return (from v in args select ((string Name, string Value))GetTuple() into kvp orderby kvp.Name select kvp).First(); (string, string) GetTuple() { return (args[0], args[1]); } } public void Issue1174() { Console.WriteLine((1, 2, 3).GetHashCode()); } public void LocalVariables((int, int) a) { (int, int) tuple = (a.Item1 + a.Item2, a.Item1 * a.Item2); Console.WriteLine(tuple.ToString()); Console.WriteLine(tuple.GetType().FullName); } public void Foreach(IEnumerable<(int, string)> input) { foreach (var item in input) { Console.WriteLine($"{item.Item1}: {item.Item2}"); } } public void ForeachNamedElements(IEnumerable<(int Index, string Data)> input) { foreach (var item in input) { Console.WriteLine($"{item.Index}: {item.Data}"); } } public void NonGenericForeach(IEnumerable input) { foreach ((string, int) item in input) { Console.WriteLine($"{item.Item1}: {item.Item2}"); } } public void CallForeach() { Foreach(new List<(int, string)> { (1, "a"), (2, "b") }); } public void DynamicTuple((dynamic A, dynamic B) a) { a.A.DynamicCall(); a.B.Dynamic = 42; } public void GenericStructWithElementNames(GenericStruct<(int A, int B)> s) { Console.WriteLine(s.Field.A + s.Property.B); } public void RefCallSites(out (int, string, Action, dynamic) tuple) { UnnamedTupleOut(out tuple); UnnamedTupleIn(in tuple); UnnamedTupleRef(ref tuple); NamedTupleOut(out tuple); NamedTupleIn(in tuple); NamedTupleRef(ref tuple); } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/TupleTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/TupleTests.cs", "repo_id": "ILSpy", "token_count": 2565 }
191
// 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 tmp96F5 { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 02 00 00 00 00 00 ) .permissionset reqmin = {[mscorlib]System.Security.Permissions.SecurityPermissionAttribute = {property bool 'SkipVerification' = bool(true)}} .hash algorithm 0x00008004 .ver 0:0:0:0 } .module tmp96F5.tmp .custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = ( 01 00 00 00 ) .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass extends [mscorlib]System.Object { .field public class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program thisField .field public int32 field1 .field public string field2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method DisplayClass::.ctor } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass .class public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass extends [mscorlib]System.Object { .field public class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass field3 .field public int32 field1 .field public string field2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method NestedDisplayClass::.ctor } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass .class public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program extends [mscorlib]System.Object { .method public hidebysig instance int32 Rand() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: newobj instance void [mscorlib]System.NotImplementedException::.ctor() IL_0005: throw } // end of method Program::Rand .method public hidebysig instance void Test1() cil managed { // Code size 53 (0x35) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldc.i4.s 42 IL_0008: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000d: dup IL_000e: ldstr "Hello World!" IL_0013: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0018: stloc.0 IL_0019: ldstr "{0} {1}" IL_001e: ldloc.0 IL_001f: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0024: box [mscorlib]System.Int32 IL_0029: ldloc.0 IL_002a: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_002f: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0034: ret } // end of method Program::Test1 .method public hidebysig instance void Test2() cil managed { // Code size 58 (0x3a) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldc.i4.s 42 IL_0008: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000d: dup IL_000e: ldstr "Hello World!" IL_0013: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0018: stloc.0 IL_0019: ldstr "{0} {1}" IL_001e: ldloc.0 IL_001f: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0024: box [mscorlib]System.Int32 IL_0029: ldloc.0 IL_002a: callvirt instance int32 [mscorlib]System.Object::GetHashCode() IL_002f: box [mscorlib]System.Int32 IL_0034: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0039: ret } // end of method Program::Test2 .method public hidebysig instance void Test3() cil managed { // Code size 48 (0x30) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldc.i4.s 42 IL_0008: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000d: dup IL_000e: ldstr "Hello World!" IL_0013: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0018: stloc.0 IL_0019: ldstr "{0} {1}" IL_001e: ldloc.0 IL_001f: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0024: box [mscorlib]System.Int32 IL_0029: ldloc.0 IL_002a: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_002f: ret } // end of method Program::Test3 .method public hidebysig instance void Test4() cil managed { // Code size 104 (0x68) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass V_1) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::thisField IL_000c: dup IL_000d: ldc.i4.s 42 IL_000f: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0014: dup IL_0015: ldstr "Hello World!" IL_001a: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_001f: stloc.0 IL_0020: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::.ctor() IL_0025: dup IL_0026: ldc.i4 0x1267 IL_002b: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0030: dup IL_0031: ldstr "ILSpy" IL_0036: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_003b: stloc.1 IL_003c: ldloc.0 IL_003d: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0042: ldc.i4.s 100 IL_0044: ble.s IL_004f IL_0046: ldloc.1 IL_0047: ldloc.0 IL_0048: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_004d: br.s IL_0056 IL_004f: ldloc.1 IL_0050: ldnull IL_0051: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0056: ldstr "{0} {1}" IL_005b: ldloc.0 IL_005c: ldloc.1 IL_005d: ldfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0062: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0067: ret } // end of method Program::Test4 .method public hidebysig instance void Test5() cil managed { // Code size 125 (0x7d) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass V_1) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::thisField IL_000c: dup IL_000d: ldc.i4.s 42 IL_000f: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0014: dup IL_0015: ldstr "Hello World!" IL_001a: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_001f: stloc.0 IL_0020: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::.ctor() IL_0025: dup IL_0026: ldc.i4 0x1267 IL_002b: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0030: dup IL_0031: ldstr "ILSpy" IL_0036: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_003b: stloc.1 IL_003c: ldloc.0 IL_003d: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0042: ldc.i4.s 100 IL_0044: ble.s IL_004f IL_0046: ldloc.1 IL_0047: ldloc.0 IL_0048: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_004d: br.s IL_0056 IL_004f: ldloc.1 IL_0050: ldnull IL_0051: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0056: ldstr "{0} {1}" IL_005b: ldloc.1 IL_005c: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_0061: ldloc.1 IL_0062: ldflda int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0067: call instance string [mscorlib]System.Int32::ToString() IL_006c: call string [mscorlib]System.String::Concat(string, string) IL_0071: ldloc.1 IL_0072: ldfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0077: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_007c: ret } // end of method Program::Test5 .method public hidebysig instance void Issue1898(int32 i) cil managed { // Code size 135 (0x87) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass V_1, int32 V_2, int32 V_3) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::thisField IL_000c: dup IL_000d: ldarg.1 IL_000e: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0013: stloc.0 IL_0014: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::.ctor() IL_0019: stloc.1 IL_001a: ldarg.0 IL_001b: call instance int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program::Rand() IL_0020: stloc.2 IL_0021: ldloc.2 IL_0022: ldc.i4.1 IL_0023: sub IL_0024: switch ( IL_0037, IL_0045, IL_005b) IL_0035: br.s IL_0064 IL_0037: ldloc.1 IL_0038: ldarg.0 IL_0039: call instance int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program::Rand() IL_003e: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0043: br.s IL_001a IL_0045: ldloc.1 IL_0046: ldarg.0 IL_0047: call instance int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program::Rand() IL_004c: stloc.3 IL_004d: ldloca.s V_3 IL_004f: call instance string [mscorlib]System.Int32::ToString() IL_0054: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_0059: br.s IL_001a IL_005b: ldloc.1 IL_005c: ldloc.0 IL_005d: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0062: br.s IL_001a IL_0064: ldloc.1 IL_0065: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_006a: call void [mscorlib]System.Console::WriteLine(int32) IL_006f: ldloc.1 IL_0070: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_0075: call void [mscorlib]System.Console::WriteLine(string) IL_007a: ldloc.1 IL_007b: ldfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0080: call void [mscorlib]System.Console::WriteLine(object) IL_0085: br.s IL_001a } // end of method Program::Issue1898 .method public hidebysig instance void Test6(int32 i) cil managed { // Code size 60 (0x3c) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldarg.1 IL_0007: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000c: dup IL_000d: ldstr "Hello World!" IL_0012: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0017: stloc.0 IL_0018: ldarg.1 IL_0019: ldc.i4.0 IL_001a: bge.s IL_0020 IL_001c: ldarg.1 IL_001d: neg IL_001e: starg.s i IL_0020: ldstr "{0} {1}" IL_0025: ldloc.0 IL_0026: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_002b: box [mscorlib]System.Int32 IL_0030: ldloc.0 IL_0031: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0036: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_003b: ret } // end of method Program::Test6 .method public hidebysig instance void Test6b(int32 i) cil managed { // Code size 61 (0x3d) .maxstack 3 .locals init (int32 V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0007: dup IL_0008: ldloc.0 IL_0009: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000e: dup IL_000f: ldstr "Hello World!" IL_0014: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0019: stloc.1 IL_001a: ldloc.0 IL_001b: ldc.i4.0 IL_001c: bge.s IL_0021 IL_001e: ldloc.0 IL_001f: neg IL_0020: stloc.0 IL_0021: ldstr "{0} {1}" IL_0026: ldloc.1 IL_0027: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_002c: box [mscorlib]System.Int32 IL_0031: ldloc.1 IL_0032: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0037: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_003c: ret } // end of method Program::Test6b .method public hidebysig instance void Test7(int32 i) cil managed { // Code size 69 (0x45) .maxstack 4 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, int32 V_1) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldarg.1 IL_0007: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000c: dup IL_000d: ldstr "Hello World!" IL_0012: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0017: stloc.0 IL_0018: ldstr "{0} {1} {2}" IL_001d: ldloc.0 IL_001e: dup IL_001f: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: ldc.i4.1 IL_0027: add IL_0028: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_002d: ldloc.1 IL_002e: box [mscorlib]System.Int32 IL_0033: ldloc.0 IL_0034: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0039: ldarg.1 IL_003a: box [mscorlib]System.Int32 IL_003f: call void [mscorlib]System.Console::WriteLine(string, object, object, object) IL_0044: ret } // end of method Program::Test7 .method public hidebysig instance void Test8(int32 i) cil managed { // Code size 56 (0x38) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0005: dup IL_0006: ldarg.1 IL_0007: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000c: dup IL_000d: ldstr "Hello World!" IL_0012: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0017: stloc.0 IL_0018: ldc.i4.s 42 IL_001a: starg.s i IL_001c: ldstr "{0} {1}" IL_0021: ldloc.0 IL_0022: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0027: box [mscorlib]System.Int32 IL_002c: ldloc.0 IL_002d: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0032: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0037: ret } // end of method Program::Test8 .method public hidebysig instance void Test8b(int32 i) cil managed { // Code size 57 (0x39) .maxstack 3 .locals init (int32 V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0007: dup IL_0008: ldloc.0 IL_0009: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000e: dup IL_000f: ldstr "Hello World!" IL_0014: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0019: stloc.1 IL_001a: ldc.i4.s 42 IL_001c: stloc.0 IL_001d: ldstr "{0} {1}" IL_0022: ldloc.1 IL_0023: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0028: box [mscorlib]System.Int32 IL_002d: ldloc.1 IL_002e: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0033: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0038: ret } // end of method Program::Test8b .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program // ============================================================= // *********** DISASSEMBLY COMPLETE ***********************
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/AggressiveScalarReplacementOfAggregates.opt.net40.roslyn.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/AggressiveScalarReplacementOfAggregates.opt.net40.roslyn.il", "repo_id": "ILSpy", "token_count": 11508 }
192
using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Ugly { internal static class NoExtensionMethods { internal static Func<T> AsFunc<T>(this T value) where T : class { return new Func<T>(value.Return); } private static T Return<T>(this T value) { return value; } internal static Func<int, int> ExtensionMethodAsStaticFunc() { return Return; } internal static Func<object> ExtensionMethodBoundToNull() { return ((object)null).Return; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoExtensionMethods.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoExtensionMethods.cs", "repo_id": "ILSpy", "token_count": 193 }
193
// 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 tmpAE03 { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 02 00 00 00 00 00 ) .permissionset reqmin = {[mscorlib]System.Security.Permissions.SecurityPermissionAttribute = {property bool 'SkipVerification' = bool(true)}} .hash algorithm 0x00008004 .ver 0:0:0:0 } .module tmpAE03.tmp .custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = ( 01 00 00 00 ) .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi sealed beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle extends [mscorlib]System.Object { .field private initonly class [mscorlib]System.Func`1<int32> _func .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Func`1<int32> func) cil managed { // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class [mscorlib]System.Func`1<int32> ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle::_func IL_000d: ret } // end of method Handle::.ctor } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle .class public abstract auto ansi sealed beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions extends [mscorlib]System.Object { .class auto ansi sealed nested private beforefieldinit '<>c__DisplayClass1_0' extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .field public int32 x } // end of class '<>c__DisplayClass1_0' .class auto ansi sealed nested private beforefieldinit '<>c__DisplayClass2_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .field public int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass2_0'::.ctor .method assembly hidebysig instance int32 '<SimpleCaptureWithRef>g__F|0'() cil managed { // Code size 10 (0xa) .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ldarg.0 IL_0003: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0'::x IL_0008: add IL_0009: ret } // end of method '<>c__DisplayClass2_0'::'<SimpleCaptureWithRef>g__F|0' } // end of class '<>c__DisplayClass2_0' .method private hidebysig static void UseLocalFunctionReference() cil managed { // Code size 19 (0x13) .maxstack 8 IL_0000: ldnull IL_0001: ldftn int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions::'<UseLocalFunctionReference>g__F|0_0'() IL_0007: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_000c: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle::.ctor(class [mscorlib]System.Func`1<int32>) IL_0011: pop IL_0012: ret } // end of method NoLocalFunctions::UseLocalFunctionReference .method private hidebysig static void SimpleCapture() cil managed { // Code size 17 (0x11) .maxstack 2 .locals init (valuetype ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0' V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0'::x IL_0008: ldloca.s V_0 IL_000a: call int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions::'<SimpleCapture>g__F|1_0'(valuetype ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0'&) IL_000f: pop IL_0010: ret } // end of method NoLocalFunctions::SimpleCapture .method private hidebysig static void SimpleCaptureWithRef() cil managed { // Code size 30 (0x1e) .maxstack 8 IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0'::x IL_000c: ldftn instance int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0'::'<SimpleCaptureWithRef>g__F|0'() IL_0012: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_0017: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle::.ctor(class [mscorlib]System.Func`1<int32>) IL_001c: pop IL_001d: ret } // end of method NoLocalFunctions::SimpleCaptureWithRef .method assembly hidebysig static int32 '<UseLocalFunctionReference>g__F|0_0'() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ret } // end of method NoLocalFunctions::'<UseLocalFunctionReference>g__F|0_0' .method assembly hidebysig static int32 '<SimpleCapture>g__F|1_0'(valuetype ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0'& A_0) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ldarg.0 IL_0003: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0'::x IL_0008: add IL_0009: ret } // end of method NoLocalFunctions::'<SimpleCapture>g__F|1_0' } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions // ============================================================= // *********** DISASSEMBLY COMPLETE ***********************
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoLocalFunctions.opt.net40.roslyn.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoLocalFunctions.opt.net40.roslyn.il", "repo_id": "ILSpy", "token_count": 3292 }
194
using System; using System.Linq; using System.Runtime.CompilerServices; public class Issue2192 { public static void M() { string[] source = new string[3] { "abc", "defgh", "ijklm" }; string text = "test"; Console.WriteLine(source.Count([SpecialName] (string w) => w.Length > text.Length)); } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Issue2192.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Issue2192.cs", "repo_id": "ILSpy", "token_count": 110 }
195
// Copyright (c) 2010-2018 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.TypeSystem.Implementation; using ICSharpCode.Decompiler.Util; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests.TypeSystem { using AttributeArray = ImmutableArray<CustomAttributeTypedArgument<IType>>; [TestFixture] public class TypeSystemLoaderTests { static PEFile LoadAssembly(string filename) { return new PEFile(filename, new FileStream(filename, FileMode.Open, FileAccess.Read)); } static readonly Lazy<PEFile> mscorlib = new Lazy<PEFile>( delegate { return LoadAssembly(Path.Combine(Helpers.Tester.RefAsmPath, "mscorlib.dll")); }); static readonly Lazy<PEFile> systemCore = new Lazy<PEFile>( delegate { return LoadAssembly(Path.Combine(Helpers.Tester.RefAsmPath, "System.Core.dll")); }); static readonly Lazy<PEFile> testAssembly = new Lazy<PEFile>( delegate { return LoadAssembly(typeof(SimplePublicClass).Assembly.Location); }); public static PEFile Mscorlib { get { return mscorlib.Value; } } public static PEFile SystemCore { get { return systemCore.Value; } } public static PEFile TestAssembly { get { return testAssembly.Value; } } [OneTimeSetUp] public void FixtureSetUp() { compilation = new SimpleCompilation(TestAssembly, Mscorlib.WithOptions(TypeSystemOptions.Default | TypeSystemOptions.OnlyPublicAPI)); } protected ICompilation compilation; protected ITypeDefinition GetTypeDefinition(Type type) { return compilation.FindType(type).GetDefinition(); } [Test] public void SimplePublicClassTest() { ITypeDefinition c = GetTypeDefinition(typeof(SimplePublicClass)); Assert.That(c.Name, Is.EqualTo(typeof(SimplePublicClass).Name)); Assert.That(c.FullName, Is.EqualTo(typeof(SimplePublicClass).FullName)); Assert.That(c.Namespace, Is.EqualTo(typeof(SimplePublicClass).Namespace)); Assert.That(c.ReflectionName, Is.EqualTo(typeof(SimplePublicClass).FullName)); Assert.That(c.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(!c.IsAbstract); Assert.That(!c.IsSealed); Assert.That(!c.IsStatic); Assert.That(!c.HasAttribute(KnownAttribute.SpecialName)); } [Test] public void SimplePublicClassMethodTest() { ITypeDefinition c = GetTypeDefinition(typeof(SimplePublicClass)); IMethod method = c.Methods.Single(m => m.Name == "Method"); Assert.That(method.FullName, Is.EqualTo(typeof(SimplePublicClass).FullName + ".Method")); Assert.That(method.DeclaringType, Is.SameAs(c)); Assert.That(method.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(method.SymbolKind, Is.EqualTo(SymbolKind.Method)); Assert.That(!method.IsVirtual); Assert.That(!method.IsStatic); Assert.That(method.Parameters.Count, Is.EqualTo(0)); Assert.That(method.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(method.HasBody); Assert.That(method.AccessorOwner, Is.Null); Assert.That(!method.HasAttribute(KnownAttribute.SpecialName)); } [Test] public void SimplePublicClassCtorTest() { ITypeDefinition c = GetTypeDefinition(typeof(SimplePublicClass)); IMethod method = c.Methods.Single(m => m.IsConstructor); Assert.That(method.FullName, Is.EqualTo(typeof(SimplePublicClass).FullName + "..ctor")); Assert.That(method.DeclaringType, Is.SameAs(c)); Assert.That(method.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(method.SymbolKind, Is.EqualTo(SymbolKind.Constructor)); Assert.That(!method.IsVirtual); Assert.That(!method.IsStatic); Assert.That(method.Parameters.Count, Is.EqualTo(0)); Assert.That(method.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(method.HasBody); Assert.That(method.AccessorOwner, Is.Null); Assert.That(!method.HasAttribute(KnownAttribute.SpecialName)); } [Test] public void SimplePublicClassDtorTest() { ITypeDefinition c = GetTypeDefinition(typeof(SimplePublicClass)); IMethod method = c.Methods.Single(m => m.IsDestructor); Assert.That(method.FullName, Is.EqualTo(typeof(SimplePublicClass).FullName + ".Finalize")); Assert.That(method.DeclaringType, Is.SameAs(c)); Assert.That(method.Accessibility, Is.EqualTo(Accessibility.Protected)); Assert.That(method.SymbolKind, Is.EqualTo(SymbolKind.Destructor)); Assert.That(!method.IsVirtual); Assert.That(!method.IsStatic); Assert.That(method.Parameters.Count, Is.EqualTo(0)); Assert.That(method.GetAttributes().Count(), Is.EqualTo(1)); Assert.That(method.HasBody); Assert.That(method.AccessorOwner, Is.Null); Assert.That(!method.HasAttribute(KnownAttribute.SpecialName)); } [Test] public void DynamicType() { ITypeDefinition testClass = GetTypeDefinition(typeof(DynamicTest)); Assert.That(testClass.Fields.Single(f => f.Name == "DynamicField").ReturnType, Is.EqualTo(SpecialType.Dynamic)); Assert.That(testClass.Properties.Single().ReturnType, Is.EqualTo(SpecialType.Dynamic)); Assert.That(testClass.Properties.Single().GetAttributes().Count(), Is.EqualTo(0)); } [Test] public void DynamicTypeInGenerics() { ITypeDefinition testClass = GetTypeDefinition(typeof(DynamicTest)); IMethod m1 = testClass.Methods.Single(me => me.Name == "DynamicGenerics1"); Assert.That(m1.ReturnType.ReflectionName, Is.EqualTo("System.Collections.Generic.List`1[[dynamic]]")); Assert.That(m1.Parameters[0].Type.ReflectionName, Is.EqualTo("System.Action`3[[System.Object],[dynamic[]],[System.Object]]")); IMethod m2 = testClass.Methods.Single(me => me.Name == "DynamicGenerics2"); Assert.That(m2.Parameters[0].Type.ReflectionName, Is.EqualTo("System.Action`3[[System.Object],[dynamic],[System.Object]]")); IMethod m3 = testClass.Methods.Single(me => me.Name == "DynamicGenerics3"); Assert.That(m3.Parameters[0].Type.ReflectionName, Is.EqualTo("System.Action`3[[System.Int32],[dynamic],[System.Object]]")); IMethod m4 = testClass.Methods.Single(me => me.Name == "DynamicGenerics4"); Assert.That(m4.Parameters[0].Type.ReflectionName, Is.EqualTo("System.Action`3[[System.Int32[]],[dynamic],[System.Object]]")); IMethod m5 = testClass.Methods.Single(me => me.Name == "DynamicGenerics5"); Assert.That(m5.Parameters[0].Type.ReflectionName, Is.EqualTo("System.Action`3[[System.Int32*[]],[dynamic],[System.Object]]")); IMethod m6 = testClass.Methods.Single(me => me.Name == "DynamicGenerics6"); Assert.That(m6.Parameters[0].Type.ReflectionName, Is.EqualTo("System.Action`3[[System.Object],[dynamic],[System.Object]]&")); IMethod m7 = testClass.Methods.Single(me => me.Name == "DynamicGenerics7"); Assert.That(m7.Parameters[0].Type.ReflectionName, Is.EqualTo("System.Action`3[[System.Int32[][,]],[dynamic],[System.Object]]")); } [Test] public void DynamicParameterHasNoAttributes() { ITypeDefinition testClass = GetTypeDefinition(typeof(DynamicTest)); IMethod m1 = testClass.Methods.Single(me => me.Name == "DynamicGenerics1"); Assert.That(m1.Parameters[0].GetAttributes().Count(), Is.EqualTo(0)); } [Test] public void AssemblyAttribute() { var attributes = compilation.MainModule.GetAssemblyAttributes().ToList(); var typeTest = attributes.Single(a => a.AttributeType.FullName == typeof(TypeTestAttribute).FullName); Assert.That(typeTest.FixedArguments.Length, Is.EqualTo(3)); // first argument is (int)42 Assert.That((int)typeTest.FixedArguments[0].Value, Is.EqualTo(42)); // second argument is typeof(System.Action<>) var ty = (IType)typeTest.FixedArguments[1].Value; Assert.That(ty is ParameterizedType, Is.False); // rt must not be constructed - it's just an unbound type Assert.That(ty.FullName, Is.EqualTo("System.Action")); Assert.That(ty.TypeParameterCount, Is.EqualTo(1)); // third argument is typeof(IDictionary<string, IList<TestAttribute>>) var crt = (ParameterizedType)typeTest.FixedArguments[2].Value; Assert.That(crt.FullName, Is.EqualTo("System.Collections.Generic.IDictionary")); Assert.That(crt.TypeArguments[0].FullName, Is.EqualTo("System.String")); // we know the name for TestAttribute, but not necessarily the namespace, as NUnit is not in the compilation Assert.That(crt.TypeArguments[1].FullName, Is.EqualTo("System.Collections.Generic.IList")); var testAttributeType = ((ParameterizedType)crt.TypeArguments[1]).TypeArguments.Single(); Assert.That(testAttributeType.Name, Is.EqualTo("TestAttribute")); Assert.That(testAttributeType.Kind, Is.EqualTo(TypeKind.Unknown)); // (more accurately, we know the namespace and reflection name if the type was loaded by cecil, // but not if we parsed it from C#) } [Test] public void TypeForwardedTo_Attribute() { var attributes = compilation.MainModule.GetAssemblyAttributes().ToList(); var forwardAttribute = attributes.Single(a => a.AttributeType.FullName == typeof(TypeForwardedToAttribute).FullName); Assert.That(forwardAttribute.FixedArguments.Length, Is.EqualTo(1)); var rt = (IType)forwardAttribute.FixedArguments[0].Value; Assert.That(rt.ReflectionName, Is.EqualTo("System.Func`2")); } [Test] public void TestClassTypeParameters() { var testClass = GetTypeDefinition(typeof(GenericClass<,>)); Assert.That(testClass.TypeParameters[0].OwnerType, Is.EqualTo(SymbolKind.TypeDefinition)); Assert.That(testClass.TypeParameters[1].OwnerType, Is.EqualTo(SymbolKind.TypeDefinition)); Assert.That(testClass.TypeParameters[0].DirectBaseTypes.First(), Is.SameAs(testClass.TypeParameters[1])); } [Test] public void TestMethod() { var testClass = GetTypeDefinition(typeof(GenericClass<,>)); IMethod m = testClass.Methods.Single(me => me.Name == "TestMethod"); Assert.That(m.TypeParameters[0].Name, Is.EqualTo("K")); Assert.That(m.TypeParameters[1].Name, Is.EqualTo("V")); Assert.That(m.TypeParameters[0].OwnerType, Is.EqualTo(SymbolKind.Method)); Assert.That(m.TypeParameters[1].OwnerType, Is.EqualTo(SymbolKind.Method)); Assert.That(m.TypeParameters[0].DirectBaseTypes.First().ReflectionName, Is.EqualTo("System.IComparable`1[[``1]]")); Assert.That(m.TypeParameters[1].DirectBaseTypes.First(), Is.SameAs(m.TypeParameters[0])); } [Test] public void GetIndex() { var testClass = GetTypeDefinition(typeof(GenericClass<,>)); IMethod m = testClass.Methods.Single(me => me.Name == "GetIndex"); Assert.That(m.TypeParameters[0].Name, Is.EqualTo("T")); Assert.That(m.TypeParameters[0].OwnerType, Is.EqualTo(SymbolKind.Method)); Assert.That(m.TypeParameters[0].Owner, Is.SameAs(m)); ParameterizedType constraint = (ParameterizedType)m.TypeParameters[0].DirectBaseTypes.First(); Assert.That(constraint.Name, Is.EqualTo("IEquatable")); Assert.That(constraint.TypeParameterCount, Is.EqualTo(1)); Assert.That(constraint.TypeArguments.Count, Is.EqualTo(1)); Assert.That(constraint.TypeArguments[0], Is.SameAs(m.TypeParameters[0])); Assert.That(m.Parameters[0].Type, Is.SameAs(m.TypeParameters[0])); } [Test] public void GetIndexSpecializedTypeParameter() { var testClass = GetTypeDefinition(typeof(GenericClass<,>)); var methodDef = testClass.Methods.Single(me => me.Name == "GetIndex"); var m = methodDef.Specialize(new TypeParameterSubstitution( new[] { compilation.FindType(KnownTypeCode.Int16), compilation.FindType(KnownTypeCode.Int32) }, null )); Assert.That(m.TypeParameters[0].Name, Is.EqualTo("T")); Assert.That(m.TypeParameters[0].OwnerType, Is.EqualTo(SymbolKind.Method)); Assert.That(m.TypeParameters[0].Owner, Is.SameAs(m)); ParameterizedType constraint = (ParameterizedType)m.TypeParameters[0].DirectBaseTypes.First(); Assert.That(constraint.Name, Is.EqualTo("IEquatable")); Assert.That(constraint.TypeParameterCount, Is.EqualTo(1)); Assert.That(constraint.TypeArguments.Count, Is.EqualTo(1)); Assert.That(constraint.TypeArguments[0], Is.SameAs(m.TypeParameters[0])); Assert.That(m.Parameters[0].Type, Is.SameAs(m.TypeParameters[0])); } [Test] public void GetIndexDoubleSpecialization() { var testClass = GetTypeDefinition(typeof(GenericClass<,>)); // GenericClass<A, B>.GetIndex<T> var methodDef = testClass.Methods.Single(me => me.Name == "GetIndex"); // GenericClass<B, A>.GetIndex<A> var m1 = methodDef.Specialize(new TypeParameterSubstitution( new[] { testClass.TypeParameters[1], testClass.TypeParameters[0] }, new[] { testClass.TypeParameters[0] } )); // GenericClass<string, int>.GetIndex<int> var m2 = m1.Specialize(new TypeParameterSubstitution( new[] { compilation.FindType(KnownTypeCode.Int32), compilation.FindType(KnownTypeCode.String) }, null )); // GenericClass<string, int>.GetIndex<int> var m12 = methodDef.Specialize(new TypeParameterSubstitution( new[] { compilation.FindType(KnownTypeCode.String), compilation.FindType(KnownTypeCode.Int32) }, new[] { compilation.FindType(KnownTypeCode.Int32) } )); Assert.That(m2, Is.EqualTo(m12)); } [Test] public void SpecializedMethod_AccessorOwner() { // NRefactory bug #143 - Accessor Owner throws null reference exception in some cases now var method = compilation.FindType(typeof(GenericClass<string, object>)).GetMethods(m => m.Name == "GetIndex").Single(); Assert.That(method.AccessorOwner, Is.Null); } [Test] public void Specialized_GetIndex_ToMemberReference() { var method = compilation.FindType(typeof(GenericClass<string, object>)).GetMethods(m => m.Name == "GetIndex").Single(); Assert.That(method.Parameters[0].Type, Is.SameAs(method.TypeParameters[0])); Assert.That(method.TypeParameters[0].Owner, Is.SameAs(method)); Assert.That(method, Is.InstanceOf<SpecializedMethod>()); //Assert.That(!method.IsParameterized); // the method itself is not specialized Assert.That(method.TypeArguments, Is.EqualTo(method.TypeParameters)); } [Test] public void Specialized_GetIndex_SpecializeWithIdentityHasNoEffect() { var genericClass = compilation.FindType(typeof(GenericClass<string, object>)); IType[] methodTypeArguments = { DummyTypeParameter.GetMethodTypeParameter(0) }; var method = genericClass.GetMethods(methodTypeArguments, m => m.Name == "GetIndex").Single(); // GenericClass<string,object>.GetIndex<!!0>() Assert.That(method.TypeParameters[0].Owner, Is.SameAs(method)); Assert.That(method.TypeArguments[0], Is.Not.EqualTo(method.TypeParameters[0])); Assert.That(((ITypeParameter)method.TypeArguments[0]).Owner, Is.Null); // Now apply identity substitution: var method2 = method.Specialize(TypeParameterSubstitution.Identity); Assert.That(method2.TypeParameters[0].Owner, Is.SameAs(method2)); Assert.That(method2.TypeArguments[0], Is.Not.EqualTo(method2.TypeParameters[0])); Assert.That(((ITypeParameter)method2.TypeArguments[0]).Owner, Is.Null); Assert.That(method2, Is.EqualTo(method)); } [Test] public void GenericEnum() { var testClass = GetTypeDefinition(typeof(GenericClass<,>.NestedEnum)); Assert.That(testClass.TypeParameterCount, Is.EqualTo(2)); } [Test] public void FieldInGenericClassWithNestedEnumType() { var testClass = GetTypeDefinition(typeof(GenericClass<,>)); var enumClass = GetTypeDefinition(typeof(GenericClass<,>.NestedEnum)); var field = testClass.Fields.Single(f => f.Name == "EnumField"); Assert.That(field.ReturnType, Is.EqualTo(new ParameterizedType(enumClass, testClass.TypeParameters))); } [Test] public void GenericEnumMemberReturnType() { var enumClass = GetTypeDefinition(typeof(GenericClass<,>.NestedEnum)); var field = enumClass.Fields.Single(f => f.Name == "EnumMember"); Assert.That(field.ReturnType, Is.EqualTo(new ParameterizedType(enumClass, enumClass.TypeParameters))); } [Test] public void PropertyWithProtectedSetter() { var testClass = GetTypeDefinition(typeof(PropertyTest)); IProperty p = testClass.Properties.Single(pr => pr.Name == "PropertyWithProtectedSetter"); Assert.That(p.CanGet); Assert.That(p.CanSet); Assert.That(p.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Setter.Accessibility, Is.EqualTo(Accessibility.Protected)); } [Test] public void PropertyWithPrivateSetter() { var testClass = GetTypeDefinition(typeof(PropertyTest)); IProperty p = testClass.Properties.Single(pr => pr.Name == "PropertyWithPrivateSetter"); Assert.That(p.CanGet); Assert.That(p.CanSet); Assert.That(p.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Setter.Accessibility, Is.EqualTo(Accessibility.Private)); Assert.That(p.Getter.HasBody); Assert.That(!p.HasAttribute(KnownAttribute.SpecialName)); Assert.That(!p.Getter.HasAttribute(KnownAttribute.SpecialName)); Assert.That(!p.Setter.HasAttribute(KnownAttribute.SpecialName)); } [Test] public void PropertyWithPrivateGetter() { var testClass = GetTypeDefinition(typeof(PropertyTest)); IProperty p = testClass.Properties.Single(pr => pr.Name == "PropertyWithPrivateGetter"); Assert.That(p.CanGet); Assert.That(p.CanSet); Assert.That(p.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.Accessibility, Is.EqualTo(Accessibility.Private)); Assert.That(p.Setter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.HasBody); } [Test] public void PropertyWithoutSetter() { var testClass = GetTypeDefinition(typeof(PropertyTest)); IProperty p = testClass.Properties.Single(pr => pr.Name == "PropertyWithoutSetter"); Assert.That(p.CanGet); Assert.That(!p.CanSet); Assert.That(p.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Setter, Is.Null); } [Test] public void Indexer() { var testClass = GetTypeDefinition(typeof(PropertyTest)); IProperty p = testClass.Properties.Single(pr => pr.IsIndexer); Assert.That(p.Name, Is.EqualTo("Item")); Assert.That(p.Parameters.Select(x => x.Name).ToArray(), Is.EqualTo(new[] { "index" })); } [Test] public void IndexerGetter() { var testClass = GetTypeDefinition(typeof(PropertyTest)); IProperty p = testClass.Properties.Single(pr => pr.IsIndexer); Assert.That(p.CanGet); Assert.That(p.Getter.SymbolKind, Is.EqualTo(SymbolKind.Accessor)); Assert.That(p.Getter.Name, Is.EqualTo("get_Item")); Assert.That(p.Getter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.Parameters.Select(x => x.Name).ToArray(), Is.EqualTo(new[] { "index" })); Assert.That(p.Getter.ReturnType.ReflectionName, Is.EqualTo("System.String")); Assert.That(p.Getter.AccessorOwner, Is.EqualTo(p)); } [Test] public void IndexerSetter() { var testClass = GetTypeDefinition(typeof(PropertyTest)); IProperty p = testClass.Properties.Single(pr => pr.IsIndexer); Assert.That(p.CanSet); Assert.That(p.Setter.SymbolKind, Is.EqualTo(SymbolKind.Accessor)); Assert.That(p.Setter.Name, Is.EqualTo("set_Item")); Assert.That(p.Setter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Setter.Parameters.Select(x => x.Name).ToArray(), Is.EqualTo(new[] { "index", "value" })); Assert.That(p.Setter.ReturnType.Kind, Is.EqualTo(TypeKind.Void)); } [Test] public void GenericPropertyGetter() { var type = compilation.FindType(typeof(GenericClass<string, object>)); var prop = type.GetProperties(p => p.Name == "Property").Single(); Assert.That(prop.Getter.ReturnType.ReflectionName, Is.EqualTo("System.String")); Assert.That(prop.Getter.IsAccessor); Assert.That(prop.Getter.AccessorOwner, Is.EqualTo(prop)); } [Test] public void EnumTest() { var e = GetTypeDefinition(typeof(MyEnum)); Assert.That(e.Kind, Is.EqualTo(TypeKind.Enum)); Assert.That(e.IsReferenceType, Is.EqualTo(false)); Assert.That(e.EnumUnderlyingType.ReflectionName, Is.EqualTo("System.Int16")); Assert.That(e.DirectBaseTypes.Select(t => t.ReflectionName).ToArray(), Is.EqualTo(new[] { "System.Enum" })); } [Test] public void EnumFieldsTest() { var e = GetTypeDefinition(typeof(MyEnum)); IField valueField = e.Fields.First(); IField[] fields = e.Fields.Skip(1).ToArray(); Assert.That(fields.Length, Is.EqualTo(5)); Assert.That(valueField.Name, Is.EqualTo("value__")); Assert.That(valueField.Type, Is.EqualTo(GetTypeDefinition(typeof(short)))); Assert.That(valueField.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(valueField.GetConstantValue(), Is.EqualTo(null)); Assert.That(!valueField.IsConst); Assert.That(!valueField.IsStatic); foreach (IField f in fields) { Assert.That(f.IsStatic); Assert.That(f.IsConst); Assert.That(f.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(f.Type, Is.SameAs(e)); Assert.That(f.GetConstantValue().GetType(), Is.EqualTo(typeof(short))); } Assert.That(fields[0].Name, Is.EqualTo("First")); Assert.That(fields[0].GetConstantValue(), Is.EqualTo(0)); Assert.That(fields[1].Name, Is.EqualTo("Second")); Assert.That(fields[1].Type, Is.SameAs(e)); Assert.That(fields[1].GetConstantValue(), Is.EqualTo(1)); Assert.That(fields[2].Name, Is.EqualTo("Flag1")); Assert.That(fields[2].GetConstantValue(), Is.EqualTo(0x10)); Assert.That(fields[3].Name, Is.EqualTo("Flag2")); Assert.That(fields[3].GetConstantValue(), Is.EqualTo(0x20)); Assert.That(fields[4].Name, Is.EqualTo("CombinedFlags")); Assert.That(fields[4].GetConstantValue(), Is.EqualTo(0x30)); } [Test] public void GetNestedTypesFromBaseClassTest() { ITypeDefinition d = GetTypeDefinition(typeof(Derived<,>)); IType pBase = d.DirectBaseTypes.Single(); Assert.That(pBase.ReflectionName, Is.EqualTo(typeof(Base<>).FullName + "[[`1]]")); // Base[`1].GetNestedTypes() = { Base`1+Nested`1[`1, unbound] } Assert.That(pBase.GetNestedTypes().Select(n => n.ReflectionName).ToArray(), Is.EqualTo(new[] { typeof(Base<>.Nested<>).FullName + "[[`1],[]]" })); // Derived.GetNestedTypes() = { Base`1+Nested`1[`1, unbound] } Assert.That(d.GetNestedTypes().Select(n => n.ReflectionName).ToArray(), Is.EqualTo(new[] { typeof(Base<>.Nested<>).FullName + "[[`1],[]]" })); // This is 'leaking' the type parameter from B as is usual when retrieving any members from an unbound type. } [Test] public void ParameterizedTypeGetNestedTypesFromBaseClassTest() { // Derived[string,int].GetNestedTypes() = { Base`1+Nested`1[int, unbound] } var d = compilation.FindType(typeof(Derived<string, int>)); Assert.That(d.GetNestedTypes().Select(n => n.ReflectionName).ToArray(), Is.EqualTo(new[] { typeof(Base<>.Nested<>).FullName + "[[System.Int32],[]]" })); } [Test] public void ConstraintsOnOverrideAreInherited() { ITypeDefinition d = GetTypeDefinition(typeof(Derived<,>)); ITypeParameter tp = d.Methods.Single(m => m.Name == "GenericMethodWithConstraints").TypeParameters.Single(); Assert.That(tp.Name, Is.EqualTo("Y")); Assert.That(!tp.HasValueTypeConstraint); Assert.That(!tp.HasReferenceTypeConstraint); Assert.That(tp.HasDefaultConstructorConstraint); Assert.That(tp.DirectBaseTypes.Select(t => t.ReflectionName).ToArray(), Is.EqualTo(new string[] { "System.Collections.Generic.IComparer`1[[`1]]", "System.Object" })); } [Test] public void DtorInDerivedClass() { ITypeDefinition c = GetTypeDefinition(typeof(Derived<,>)); IMethod method = c.Methods.Single(m => m.IsDestructor); Assert.That(method.FullName, Is.EqualTo(c.FullName + ".Finalize")); Assert.That(method.DeclaringType, Is.SameAs(c)); Assert.That(method.Accessibility, Is.EqualTo(Accessibility.Protected)); Assert.That(method.SymbolKind, Is.EqualTo(SymbolKind.Destructor)); Assert.That(!method.IsVirtual); Assert.That(!method.IsStatic); Assert.That(method.Parameters.Count, Is.EqualTo(0)); Assert.That(method.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(method.HasBody); Assert.That(method.AccessorOwner, Is.Null); } [Test] public void PrivateFinalizeMethodIsNotADtor() { ITypeDefinition c = GetTypeDefinition(typeof(TypeTestAttribute)); IMethod method = c.Methods.Single(m => m.Name == "Finalize"); Assert.That(method.FullName, Is.EqualTo(c.FullName + ".Finalize")); Assert.That(method.DeclaringType, Is.SameAs(c)); Assert.That(method.Accessibility, Is.EqualTo(Accessibility.Private)); Assert.That(method.SymbolKind, Is.EqualTo(SymbolKind.Method)); Assert.That(!method.IsVirtual); Assert.That(!method.IsStatic); Assert.That(method.Parameters.Count, Is.EqualTo(0)); Assert.That(method.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(method.HasBody); Assert.That(method.AccessorOwner, Is.Null); } [Test] public void DefaultConstructorAddedToStruct() { var ctors = compilation.FindType(typeof(MyStructWithCtor)).GetConstructors(); Assert.That(ctors.Count(), Is.EqualTo(2)); Assert.That(!ctors.Any(c => c.IsStatic)); Assert.That(ctors.All(c => c.ReturnType.Kind == TypeKind.Void)); Assert.That(ctors.All(c => c.Accessibility == Accessibility.Public)); } [Test] public void NoDefaultConstructorAddedToStruct() { var ctors = compilation.FindType(typeof(MyStructWithDefaultCtor)).GetConstructors(); Assert.That(ctors.Count(), Is.EqualTo(1)); Assert.That(!ctors.Any(c => c.IsStatic)); Assert.That(ctors.All(c => c.ReturnType.Kind == TypeKind.Void)); Assert.That(ctors.All(c => c.Accessibility == Accessibility.Public)); } [Test] public void NoDefaultConstructorAddedToClass() { var ctors = compilation.FindType(typeof(MyClassWithCtor)).GetConstructors(); Assert.That(ctors.Single().Accessibility, Is.EqualTo(Accessibility.Private)); Assert.That(ctors.Single().Parameters.Count, Is.EqualTo(1)); } [Test] public void DefaultConstructorOnAbstractClassIsProtected() { var ctors = compilation.FindType(typeof(AbstractClass)).GetConstructors(); Assert.That(ctors.Single().Parameters.Count, Is.EqualTo(0)); Assert.That(ctors.Single().Accessibility, Is.EqualTo(Accessibility.Protected)); } [Test] public void SerializableAttribute() { IAttribute attr = GetTypeDefinition(typeof(NonCustomAttributes)).GetAttributes().Single(); Assert.That(attr.AttributeType.FullName, Is.EqualTo("System.SerializableAttribute")); } [Test] public void NonSerializedAttribute() { IField field = GetTypeDefinition(typeof(NonCustomAttributes)).Fields.Single(f => f.Name == "NonSerializedField"); Assert.That(field.GetAttributes().Single().AttributeType.FullName, Is.EqualTo("System.NonSerializedAttribute")); } [Test] public void ExplicitStructLayoutAttribute() { IAttribute attr = GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).GetAttributes().Single(); Assert.That(attr.AttributeType.FullName, Is.EqualTo("System.Runtime.InteropServices.StructLayoutAttribute")); var arg1 = attr.FixedArguments.Single(); Assert.That(arg1.Type.FullName, Is.EqualTo("System.Runtime.InteropServices.LayoutKind")); Assert.That(arg1.Value, Is.EqualTo((int)LayoutKind.Explicit)); var arg2 = attr.NamedArguments[0]; Assert.That(arg2.Name, Is.EqualTo("CharSet")); Assert.That(arg2.Type.FullName, Is.EqualTo("System.Runtime.InteropServices.CharSet")); Assert.That(arg2.Value, Is.EqualTo((int)CharSet.Unicode)); var arg3 = attr.NamedArguments[1]; Assert.That(arg3.Name, Is.EqualTo("Pack")); Assert.That(arg3.Type.FullName, Is.EqualTo("System.Int32")); Assert.That(arg3.Value, Is.EqualTo(8)); } [Test] public void FieldOffsetAttribute() { IField field = GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).Fields.Single(f => f.Name == "Field0"); Assert.That(field.GetAttributes().Single().AttributeType.FullName, Is.EqualTo("System.Runtime.InteropServices.FieldOffsetAttribute")); var arg = field.GetAttributes().Single().FixedArguments.Single(); Assert.That(arg.Type.FullName, Is.EqualTo("System.Int32")); Assert.That(arg.Value, Is.EqualTo(0)); field = GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).Fields.Single(f => f.Name == "Field100"); Assert.That(field.GetAttributes().Single().AttributeType.FullName, Is.EqualTo("System.Runtime.InteropServices.FieldOffsetAttribute")); arg = field.GetAttributes().Single().FixedArguments.Single(); Assert.That(arg.Type.FullName, Is.EqualTo("System.Int32")); Assert.That(arg.Value, Is.EqualTo(100)); } [Test] public void DllImportAttribute() { IMethod method = GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod"); IAttribute dllImport = method.GetAttributes().Single(); Assert.That(dllImport.AttributeType.FullName, Is.EqualTo("System.Runtime.InteropServices.DllImportAttribute")); Assert.That(dllImport.FixedArguments[0].Value, Is.EqualTo("unmanaged.dll")); Assert.That(dllImport.NamedArguments.Single().Value, Is.EqualTo((int)CharSet.Unicode)); } [Test] public void DllImportAttributeWithPreserveSigFalse() { IMethod method = GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DoNotPreserveSig"); IAttribute dllImport = method.GetAttributes().Single(); Assert.That(dllImport.AttributeType.FullName, Is.EqualTo("System.Runtime.InteropServices.DllImportAttribute")); Assert.That(dllImport.FixedArguments[0].Value, Is.EqualTo("unmanaged.dll")); Assert.That(dllImport.NamedArguments.Single().Value, Is.EqualTo(false)); } [Test] public void PreserveSigAttribute() { IMethod method = GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "PreserveSigAsAttribute"); IAttribute preserveSig = method.GetAttributes().Single(); Assert.That(preserveSig.AttributeType.FullName, Is.EqualTo("System.Runtime.InteropServices.PreserveSigAttribute")); Assert.That(preserveSig.FixedArguments.Length == 0); Assert.That(preserveSig.NamedArguments.Length == 0); } [Test] public void InOutParametersOnRefMethod() { IParameter p = GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod").Parameters.Single(); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.Ref)); var attr = p.GetAttributes().ToList(); Assert.That(attr.Count, Is.EqualTo(2)); Assert.That(attr[0].AttributeType.FullName, Is.EqualTo("System.Runtime.InteropServices.InAttribute")); Assert.That(attr[1].AttributeType.FullName, Is.EqualTo("System.Runtime.InteropServices.OutAttribute")); } [Test] public void MarshalAsAttributeOnMethod() { IMethod method = GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod"); IAttribute marshalAs = method.GetReturnTypeAttributes().Single(); Assert.That(marshalAs.FixedArguments.Single().Value, Is.EqualTo((int)UnmanagedType.Bool)); } [Test] public void MethodWithOutParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithOutParameter").Parameters.Single(); Assert.That(!p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.Out)); Assert.That(p.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(p.Type.Kind == TypeKind.ByReference); } [Test] public void MethodWithRefParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithRefParameter").Parameters.Single(); Assert.That(!p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.Ref)); Assert.That(p.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(p.Type.Kind == TypeKind.ByReference); } [Test] public void MethodWithInParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithInParameter").Parameters.Single(); Assert.That(!p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.In)); Assert.That(p.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(p.Type.Kind == TypeKind.ByReference); } [Test] public void MethodWithParamsArray() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithParamsArray").Parameters.Single(); Assert.That(!p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(p.IsParams); Assert.That(p.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(p.Type.Kind == TypeKind.Array); } [Test] public void MethodWithOptionalParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithOptionalParameter").Parameters.Single(); Assert.That(p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(p.HasConstantValueInSignature); Assert.That(p.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(p.GetConstantValue(), Is.EqualTo(4)); } [Test] public void MethodWithExplicitOptionalParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithExplicitOptionalParameter").Parameters.Single(); Assert.That(p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(!p.HasConstantValueInSignature); // explicit optional parameter appears in type system if it's read from C#, but not when read from IL //Assert.AreEqual(1, p.GetAttributes().Count()); } [Test] public void MethodWithEnumOptionalParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithEnumOptionalParameter").Parameters.Single(); Assert.That(p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(p.HasConstantValueInSignature); Assert.That(p.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(p.GetConstantValue(), Is.EqualTo((int)StringComparison.OrdinalIgnoreCase)); } [Test] public void MethodWithOptionalNullableParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithOptionalNullableParameter").Parameters.Single(); Assert.That(p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(p.HasConstantValueInSignature); Assert.That(p.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(p.GetConstantValue(), Is.Null); } [Test] public void MethodWithOptionalLongParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithOptionalLongParameter").Parameters.Single(); Assert.That(p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(p.HasConstantValueInSignature); Assert.That(p.GetConstantValue(), Is.EqualTo(1L)); Assert.That(p.GetConstantValue().GetType(), Is.EqualTo(typeof(long))); } [Test] public void MethodWithOptionalNullableLongParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithOptionalNullableLongParameter").Parameters.Single(); Assert.That(p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(p.HasConstantValueInSignature); Assert.That(p.GetConstantValue(), Is.EqualTo(1L)); Assert.That(p.GetConstantValue().GetType(), Is.EqualTo(typeof(long))); } [Test] public void MethodWithOptionalDecimalParameter() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithOptionalDecimalParameter").Parameters.Single(); Assert.That(p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(p.HasConstantValueInSignature); Assert.That(p.GetConstantValue(), Is.EqualTo(1M)); Assert.That(p.GetConstantValue().GetType(), Is.EqualTo(typeof(decimal))); } [Test] public void VarArgsMethod() { IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "VarArgsMethod").Parameters.Single(); Assert.That(!p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(p.Type.Kind, Is.EqualTo(TypeKind.ArgList)); Assert.That(p.Name, Is.EqualTo("")); } [Test] public void VarArgsCtor() { IParameter p = GetTypeDefinition(typeof(VarArgsCtor)).Methods.Single(m => m.IsConstructor).Parameters.Single(); Assert.That(!p.IsOptional); Assert.That(p.ReferenceKind, Is.EqualTo(ReferenceKind.None)); Assert.That(!p.IsParams); Assert.That(p.Type.Kind, Is.EqualTo(TypeKind.ArgList)); Assert.That(p.Name, Is.EqualTo("")); } [Test] public void GenericDelegate_Variance() { ITypeDefinition type = GetTypeDefinition(typeof(GenericDelegate<,>)); Assert.That(type.TypeParameters[0].Variance, Is.EqualTo(VarianceModifier.Contravariant)); Assert.That(type.TypeParameters[1].Variance, Is.EqualTo(VarianceModifier.Covariant)); Assert.That(type.TypeParameters[0].DirectBaseTypes.FirstOrDefault(), Is.SameAs(type.TypeParameters[1])); } [Test] public void GenericDelegate_ReferenceTypeConstraints() { ITypeDefinition type = GetTypeDefinition(typeof(GenericDelegate<,>)); Assert.That(!type.TypeParameters[0].HasReferenceTypeConstraint); Assert.That(type.TypeParameters[1].HasReferenceTypeConstraint); Assert.That(type.TypeParameters[0].IsReferenceType, Is.Null); Assert.That(type.TypeParameters[1].IsReferenceType, Is.EqualTo(true)); } [Test] public void GenericDelegate_GetInvokeMethod() { IType type = compilation.FindType(typeof(GenericDelegate<string, object>)); IMethod m = type.GetDelegateInvokeMethod(); Assert.That(m.Name, Is.EqualTo("Invoke")); Assert.That(m.ReturnType.FullName, Is.EqualTo("System.Object")); Assert.That(m.Parameters[0].Type.FullName, Is.EqualTo("System.String")); } [Test] public void ComInterfaceTest() { ITypeDefinition type = GetTypeDefinition(typeof(IAssemblyEnum)); // [ComImport] Assert.That(type.GetAttributes().Count(a => a.AttributeType.FullName == typeof(ComImportAttribute).FullName), Is.EqualTo(1)); IMethod m = type.Methods.Single(); Assert.That(m.Name, Is.EqualTo("GetNextAssembly")); Assert.That(m.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(m.IsAbstract); Assert.That(!m.IsVirtual); Assert.That(!m.IsSealed); } [Test] public void InnerClassInGenericClassIsReferencedUsingParameterizedType() { ITypeDefinition type = GetTypeDefinition(typeof(OuterGeneric<>)); IField field1 = type.Fields.Single(f => f.Name == "Field1"); IField field2 = type.Fields.Single(f => f.Name == "Field2"); IField field3 = type.Fields.Single(f => f.Name == "Field3"); // types must be self-parameterized Assert.That(field1.Type.ReflectionName, Is.EqualTo("ICSharpCode.Decompiler.Tests.TypeSystem.OuterGeneric`1+Inner[[`0]]")); Assert.That(field2.Type.ReflectionName, Is.EqualTo("ICSharpCode.Decompiler.Tests.TypeSystem.OuterGeneric`1+Inner[[`0]]")); Assert.That(field3.Type.ReflectionName, Is.EqualTo("ICSharpCode.Decompiler.Tests.TypeSystem.OuterGeneric`1+Inner[[ICSharpCode.Decompiler.Tests.TypeSystem.OuterGeneric`1+Inner[[`0]]]]")); } [Test] public void FlagsOnInterfaceMembersAreCorrect() { ITypeDefinition type = GetTypeDefinition(typeof(IInterfaceWithProperty)); var p = type.Properties.Single(); Assert.That(p.IsIndexer, Is.EqualTo(false)); Assert.That(p.IsAbstract, Is.EqualTo(true)); Assert.That(p.IsOverridable, Is.EqualTo(true)); Assert.That(p.IsOverride, Is.EqualTo(false)); Assert.That(p.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.IsAbstract, Is.EqualTo(true)); Assert.That(p.Getter.IsOverridable, Is.EqualTo(true)); Assert.That(p.Getter.IsOverride, Is.EqualTo(false)); Assert.That(p.Getter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.HasBody, Is.EqualTo(false)); Assert.That(p.Setter.IsAbstract, Is.EqualTo(true)); Assert.That(p.Setter.IsOverridable, Is.EqualTo(true)); Assert.That(p.Setter.IsOverride, Is.EqualTo(false)); Assert.That(p.Setter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Setter.HasBody, Is.EqualTo(false)); type = GetTypeDefinition(typeof(IInterfaceWithIndexers)); p = type.Properties.Single(x => x.Parameters.Count == 2); Assert.That(p.IsIndexer, Is.EqualTo(true)); Assert.That(p.IsAbstract, Is.EqualTo(true)); Assert.That(p.IsOverridable, Is.EqualTo(true)); Assert.That(p.IsOverride, Is.EqualTo(false)); Assert.That(p.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Getter.IsAbstract, Is.EqualTo(true)); Assert.That(p.Getter.IsOverridable, Is.EqualTo(true)); Assert.That(p.Getter.IsOverride, Is.EqualTo(false)); Assert.That(p.Getter.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(p.Setter.IsAbstract, Is.EqualTo(true)); Assert.That(p.Setter.IsOverridable, Is.EqualTo(true)); Assert.That(p.Setter.IsOverride, Is.EqualTo(false)); Assert.That(p.Setter.Accessibility, Is.EqualTo(Accessibility.Public)); type = GetTypeDefinition(typeof(IHasEvent)); var e = type.Events.Single(); Assert.That(e.IsAbstract, Is.EqualTo(true)); Assert.That(e.IsOverridable, Is.EqualTo(true)); Assert.That(e.IsOverride, Is.EqualTo(false)); Assert.That(e.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(e.AddAccessor.IsAbstract, Is.EqualTo(true)); Assert.That(e.AddAccessor.IsOverridable, Is.EqualTo(true)); Assert.That(e.AddAccessor.IsOverride, Is.EqualTo(false)); Assert.That(e.AddAccessor.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(e.RemoveAccessor.IsAbstract, Is.EqualTo(true)); Assert.That(e.RemoveAccessor.IsOverridable, Is.EqualTo(true)); Assert.That(e.RemoveAccessor.IsOverride, Is.EqualTo(false)); Assert.That(e.RemoveAccessor.Accessibility, Is.EqualTo(Accessibility.Public)); type = GetTypeDefinition(typeof(IDisposable)); var m = type.Methods.Single(); Assert.That(m.IsAbstract, Is.EqualTo(true)); Assert.That(m.IsOverridable, Is.EqualTo(true)); Assert.That(m.IsOverride, Is.EqualTo(false)); Assert.That(m.Accessibility, Is.EqualTo(Accessibility.Public)); } [Test] public void InnerClassInGenericClass_TypeParameterOwner() { ITypeDefinition type = GetTypeDefinition(typeof(OuterGeneric<>.Inner)); Assert.That(type.TypeParameters[0], Is.SameAs(type.DeclaringTypeDefinition.TypeParameters[0])); Assert.That(type.TypeParameters[0].Owner, Is.SameAs(type.DeclaringTypeDefinition)); } [Test] public void InnerClassInGenericClass_ReferencesTheOuterClass_Field() { ITypeDefinition type = GetTypeDefinition(typeof(OuterGeneric<>.Inner)); IField f = type.Fields.Single(); Assert.That(f.Type.ReflectionName, Is.EqualTo("ICSharpCode.Decompiler.Tests.TypeSystem.OuterGeneric`1[[`0]]")); } [Test] public void InnerClassInGenericClass_ReferencesTheOuterClass_Parameter() { ITypeDefinition type = GetTypeDefinition(typeof(OuterGeneric<>.Inner)); IParameter p = type.Methods.Single(m => m.IsConstructor).Parameters.Single(); Assert.That(p.Type.ReflectionName, Is.EqualTo("ICSharpCode.Decompiler.Tests.TypeSystem.OuterGeneric`1[[`0]]")); } CustomAttributeTypedArgument<IType> GetParamsAttributeArgument(int index) { ITypeDefinition type = GetTypeDefinition(typeof(ParamsAttribute)); var arr = (AttributeArray)type.GetAttributes().Single().FixedArguments.Single().Value; Assert.That(arr.Length, Is.EqualTo(5)); return arr[index]; } [Test] public void ParamsAttribute_Integer() { var arg = GetParamsAttributeArgument(0); Assert.That(arg.Type.FullName, Is.EqualTo("System.Int32")); Assert.That(arg.Value, Is.EqualTo(1)); } [Test] public void ParamsAttribute_Enum() { var arg = GetParamsAttributeArgument(1); Assert.That(arg.Type.FullName, Is.EqualTo("System.StringComparison")); Assert.That(arg.Value, Is.EqualTo((int)StringComparison.CurrentCulture)); } [Test] public void ParamsAttribute_NullReference() { var arg = GetParamsAttributeArgument(2); //Assert.AreEqual("System.Object", arg.Type.FullName); Assert.That(arg.Value, Is.Null); } [Test] public void ParamsAttribute_Double() { var arg = GetParamsAttributeArgument(3); Assert.That(arg.Type.FullName, Is.EqualTo("System.Double")); Assert.That(arg.Value, Is.EqualTo(4.0)); } [Test] public void ParamsAttribute_String() { var arg = GetParamsAttributeArgument(4); Assert.That(arg.Type.FullName, Is.EqualTo("System.String")); Assert.That(arg.Value, Is.EqualTo("Test")); } [Test] public void ParamsAttribute_Property() { ITypeDefinition type = GetTypeDefinition(typeof(ParamsAttribute)); IProperty prop = type.Properties.Single(p => p.Name == "Property"); var attr = prop.GetAttributes().Single(); Assert.That(attr.AttributeType, Is.EqualTo(type)); var elements = (AttributeArray)attr.FixedArguments.Single().Value; Assert.That(elements.Length, Is.EqualTo(0)); var namedArg = attr.NamedArguments.Single(); Assert.That(namedArg.Name, Is.EqualTo(prop.Name)); var arrayElements = (AttributeArray)namedArg.Value; Assert.That(arrayElements.Length, Is.EqualTo(2)); } [Test] public void ParamsAttribute_Getter_ReturnType() { ITypeDefinition type = GetTypeDefinition(typeof(ParamsAttribute)); IProperty prop = type.Properties.Single(p => p.Name == "Property"); Assert.That(prop.Getter.GetAttributes().Count(), Is.EqualTo(0)); Assert.That(prop.Getter.GetReturnTypeAttributes().Count(), Is.EqualTo(1)); } [Test] public void DoubleAttribute_ImplicitNumericConversion() { ITypeDefinition type = GetTypeDefinition(typeof(DoubleAttribute)); var arg = type.GetAttributes().Single().FixedArguments.Single(); Assert.That(arg.Type.ReflectionName, Is.EqualTo("System.Double")); Assert.That(arg.Value, Is.EqualTo(1.0)); } /* TS no longer provides implicitly implemented interface members. [Test] public void ImplicitImplementationOfUnifiedMethods() { ITypeDefinition type = GetTypeDefinition(typeof(ImplementationOfUnifiedMethods)); IMethod test = type.Methods.Single(m => m.Name == "Test"); Assert.AreEqual(2, test.ImplementedInterfaceMembers.Count); Assert.AreEqual("Int32", ((IMethod)test.ImplementedInterfaceMembers[0]).Parameters.Single().Type.Name); Assert.AreEqual("Int32", ((IMethod)test.ImplementedInterfaceMembers[1]).Parameters.Single().Type.Name); Assert.AreEqual("T", ((IMethod)test.ImplementedInterfaceMembers[0].MemberDefinition).Parameters.Single().Type.Name); Assert.AreEqual("S", ((IMethod)test.ImplementedInterfaceMembers[1].MemberDefinition).Parameters.Single().Type.Name); } */ [Test] public void StaticityOfEventAccessors() { // https://github.com/icsharpcode/NRefactory/issues/20 ITypeDefinition type = GetTypeDefinition(typeof(ClassWithStaticAndNonStaticMembers)); var evt1 = type.Events.Single(e => e.Name == "Event1"); Assert.That(evt1.IsStatic); Assert.That(evt1.AddAccessor.IsStatic); Assert.That(evt1.RemoveAccessor.IsStatic); var evt2 = type.Events.Single(e => e.Name == "Event2"); Assert.That(!evt2.IsStatic); Assert.That(!evt2.AddAccessor.IsStatic); Assert.That(!evt2.RemoveAccessor.IsStatic); var evt3 = type.Events.Single(e => e.Name == "Event3"); Assert.That(evt3.IsStatic); Assert.That(evt3.AddAccessor.IsStatic); Assert.That(evt3.RemoveAccessor.IsStatic); var evt4 = type.Events.Single(e => e.Name == "Event4"); Assert.That(!evt4.IsStatic); Assert.That(!evt4.AddAccessor.IsStatic); Assert.That(!evt4.RemoveAccessor.IsStatic); } [Test] public void StaticityOfPropertyAccessors() { // https://github.com/icsharpcode/NRefactory/issues/20 ITypeDefinition type = GetTypeDefinition(typeof(ClassWithStaticAndNonStaticMembers)); var prop1 = type.Properties.Single(e => e.Name == "Prop1"); Assert.That(prop1.IsStatic); Assert.That(prop1.Getter.IsStatic); Assert.That(prop1.Setter.IsStatic); var prop2 = type.Properties.Single(e => e.Name == "Prop2"); Assert.That(!prop2.IsStatic); Assert.That(!prop2.Getter.IsStatic); Assert.That(!prop2.Setter.IsStatic); var prop3 = type.Properties.Single(e => e.Name == "Prop3"); Assert.That(prop3.IsStatic); Assert.That(prop3.Getter.IsStatic); Assert.That(prop3.Setter.IsStatic); var prop4 = type.Properties.Single(e => e.Name == "Prop4"); Assert.That(!prop4.IsStatic); Assert.That(!prop4.Getter.IsStatic); Assert.That(!prop4.Setter.IsStatic); } [Test] public void PropertyAccessorsHaveBody() { ITypeDefinition type = GetTypeDefinition(typeof(ClassWithStaticAndNonStaticMembers)); foreach (var prop in type.Properties) { Assert.That(prop.Getter.HasBody, prop.Getter.Name); Assert.That(prop.Setter.HasBody, prop.Setter.Name); } } [Test] public void EventAccessorNames() { ITypeDefinition type = GetTypeDefinition(typeof(ClassWithStaticAndNonStaticMembers)); var customEvent = type.Events.Single(e => e.Name == "Event1"); Assert.That(customEvent.AddAccessor.Name, Is.EqualTo("add_Event1")); Assert.That(customEvent.RemoveAccessor.Name, Is.EqualTo("remove_Event1")); var normalEvent = type.Events.Single(e => e.Name == "Event3"); Assert.That(normalEvent.AddAccessor.Name, Is.EqualTo("add_Event3")); Assert.That(normalEvent.RemoveAccessor.Name, Is.EqualTo("remove_Event3")); } [Test] public void EventAccessorHaveBody() { ITypeDefinition type = GetTypeDefinition(typeof(ClassWithStaticAndNonStaticMembers)); foreach (var ev in type.Events) { Assert.That(ev.AddAccessor.HasBody, ev.AddAccessor.Name); Assert.That(ev.RemoveAccessor.HasBody, ev.RemoveAccessor.Name); } } [Test] public void InterfacePropertyAccessorsShouldNotBeOverrides() { ITypeDefinition type = GetTypeDefinition(typeof(IInterfaceWithProperty)); var prop = type.Properties.Single(p => p.Name == "Prop"); Assert.That(prop.Getter.IsOverride, Is.False); Assert.That(prop.Getter.IsOverridable, Is.True); Assert.That(prop.Setter.IsOverride, Is.False); Assert.That(prop.Setter.IsOverridable, Is.True); } [Test] public void InterfaceShouldDeriveFromObject() { ITypeDefinition type = GetTypeDefinition(typeof(IInterfaceWithProperty)); Assert.That(type.DirectBaseTypes.Count() == 1, "Should have exactly one direct base type"); Assert.That(type.DirectBaseTypes.First().IsKnownType(KnownTypeCode.Object), "Base type should be object"); } [Test] public void InterfaceShouldDeriveFromObject2() { ITypeDefinition type = GetTypeDefinition(typeof(IShadowTestDerived)); Assert.That(type.DirectBaseTypes.Count() == 2, "Should have exactly two direct base types"); Assert.That(type.DirectBaseTypes.Skip(1).First() == GetTypeDefinition(typeof(IShadowTestBase)), "Base type should be IShadowTestBase"); Assert.That(type.DirectBaseTypes.First().IsKnownType(KnownTypeCode.Object), "Base type should be object"); } [Test] public void CheckInterfaceDirectBaseTypes() { ITypeDefinition type = GetTypeDefinition(typeof(IDerived)); Assert.That(type.DirectBaseTypes.Count() == 3, "Should have exactly three direct base types"); Assert.That(type.DirectBaseTypes.First().IsKnownType(KnownTypeCode.Object), "Base type should be object"); Assert.That(type.DirectBaseTypes.Skip(1).First() == GetTypeDefinition(typeof(IBase1)), "Base type should be IBase1"); Assert.That(type.DirectBaseTypes.Skip(2).First() == GetTypeDefinition(typeof(IBase2)), "Base type should be IBase2"); } [Test] public void VirtualPropertyAccessorsShouldNotBeOverrides() { ITypeDefinition type = GetTypeDefinition(typeof(ClassWithVirtualProperty)); var prop = type.Properties.Single(p => p.Name == "Prop"); Assert.That(prop.Getter.IsOverride, Is.False); Assert.That(prop.Getter.IsOverridable, Is.True); Assert.That(prop.Setter.IsOverride, Is.False); Assert.That(prop.Setter.IsOverridable, Is.True); } [Test] public void ClassThatOverridesGetterOnly() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatOverridesGetterOnly)); var prop = type.Properties.Single(p => p.Name == "Prop"); Assert.That(prop.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(prop.Getter.Accessibility, Is.EqualTo(Accessibility.Public)); } [Test] public void ClassThatOverridesSetterOnly() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatOverridesSetterOnly)); var prop = type.Properties.Single(p => p.Name == "Prop"); Assert.That(prop.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(prop.Setter.Accessibility, Is.EqualTo(Accessibility.Protected)); } /* TS no longer provides implicit interface impls [Test] public void PropertyAccessorsShouldBeReportedAsImplementingInterfaceAccessors() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsProperty)); var prop = type.Properties.Single(p => p.Name == "Prop"); Assert.That(prop.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithProperty.Prop" })); Assert.That(prop.Getter.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithProperty.get_Prop" })); Assert.That(prop.Setter.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithProperty.set_Prop" })); } */ [Test] public void PropertyThatImplementsInterfaceIsNotVirtual() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsProperty)); var prop = type.Properties.Single(p => p.Name == "Prop"); Assert.That(!prop.IsVirtual); Assert.That(!prop.IsOverridable); Assert.That(!prop.IsSealed); } [Test] public void Property_SealedOverride() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatOverridesAndSealsVirtualProperty)); var prop = type.Properties.Single(p => p.Name == "Prop"); Assert.That(!prop.IsVirtual); Assert.That(prop.IsOverride); Assert.That(prop.IsSealed); Assert.That(!prop.IsOverridable); } /* The TS no longer provides implicit interface impls. [Test] public void IndexerAccessorsShouldBeReportedAsImplementingTheCorrectInterfaceAccessors() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsIndexers)); var ix1 = type.Properties.Single(p => p.Parameters.Count == 1 && p.Parameters[0].Type.GetDefinition().KnownTypeCode == KnownTypeCode.Int32); var ix2 = type.Properties.Single(p => p.Parameters.Count == 1 && p.Parameters[0].Type.GetDefinition().KnownTypeCode == KnownTypeCode.String); var ix3 = type.Properties.Single(p => p.Parameters.Count == 2); Assert.That(ix1.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EquivalentTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.Item", "ICSharpCode.Decompiler.Tests.TypeSystem.IGenericInterfaceWithIndexer`1.Item" })); Assert.That(ix1.ImplementedInterfaceMembers.All(p => ((IProperty)p).Parameters.Select(x => x.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.Int32 }))); Assert.That(ix1.Getter.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EquivalentTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.get_Item", "ICSharpCode.Decompiler.Tests.TypeSystem.IGenericInterfaceWithIndexer`1.get_Item" })); Assert.That(ix1.Getter.ImplementedInterfaceMembers.All(m => ((IMethod)m).Parameters.Select(p => p.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.Int32 }))); Assert.That(ix1.Setter.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EquivalentTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.set_Item", "ICSharpCode.Decompiler.Tests.TypeSystem.IGenericInterfaceWithIndexer`1.set_Item" })); Assert.That(ix1.Setter.ImplementedInterfaceMembers.All(m => ((IMethod)m).Parameters.Select(p => p.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.Int32, KnownTypeCode.Int32 }))); Assert.That(ix2.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.Item" })); Assert.That(ix2.ImplementedInterfaceMembers.All(p => ((IProperty)p).Parameters.Select(x => x.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.String }))); Assert.That(ix2.Getter.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.get_Item" })); Assert.That(ix2.Getter.ImplementedInterfaceMembers.All(m => ((IMethod)m).Parameters.Select(p => p.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.String }))); Assert.That(ix2.Setter.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.set_Item" })); Assert.That(ix2.Setter.ImplementedInterfaceMembers.All(m => ((IMethod)m).Parameters.Select(p => p.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.String, KnownTypeCode.Int32 }))); Assert.That(ix3.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.Item" })); Assert.That(ix3.ImplementedInterfaceMembers.All(p => ((IProperty)p).Parameters.Select(x => x.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.Int32, KnownTypeCode.Int32 }))); Assert.That(ix3.Getter.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.get_Item" })); Assert.That(ix3.Getter.ImplementedInterfaceMembers.All(m => ((IMethod)m).Parameters.Select(p => p.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.Int32, KnownTypeCode.Int32 }))); Assert.That(ix3.Setter.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithIndexers.set_Item" })); Assert.That(ix3.Setter.ImplementedInterfaceMembers.All(m => ((IMethod)m).Parameters.Select(p => p.Type.GetDefinition().KnownTypeCode).SequenceEqual(new[] { KnownTypeCode.Int32, KnownTypeCode.Int32, KnownTypeCode.Int32 }))); } */ [Test] public void ExplicitIndexerImplementationReturnsTheCorrectMembers() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsIndexersExplicitly)); Assert.That(type.Properties.All(p => p.SymbolKind == SymbolKind.Indexer)); Assert.That(type.Properties.All(p => p.ExplicitlyImplementedInterfaceMembers.Count() == 1)); Assert.That(type.Properties.All(p => p.Getter.ExplicitlyImplementedInterfaceMembers.Count() == 1)); Assert.That(type.Properties.All(p => p.Setter.ExplicitlyImplementedInterfaceMembers.Count() == 1)); } [Test] public void ExplicitDisposableImplementation() { ITypeDefinition disposable = GetTypeDefinition(typeof(ExplicitDisposableImplementation)); IMethod method = disposable.Methods.Single(m => !m.IsConstructor); Assert.That(method.IsExplicitInterfaceImplementation); Assert.That(method.ExplicitlyImplementedInterfaceMembers.Single().FullName, Is.EqualTo("System.IDisposable.Dispose")); } [Test] public void ExplicitImplementationOfUnifiedMethods() { IType type = compilation.FindType(typeof(ExplicitGenericInterfaceImplementationWithUnifiableMethods<int, int>)); Assert.That(type.GetMethods(m => m.IsExplicitInterfaceImplementation).Count(), Is.EqualTo(2)); foreach (IMethod method in type.GetMethods(m => m.IsExplicitInterfaceImplementation)) { Assert.That(method.ExplicitlyImplementedInterfaceMembers.Count(), Is.EqualTo(1), method.ToString()); Assert.That(method.Parameters.Single().Type.ReflectionName, Is.EqualTo("System.Int32")); IMethod interfaceMethod = (IMethod)method.ExplicitlyImplementedInterfaceMembers.Single(); Assert.That(interfaceMethod.Parameters.Single().Type.ReflectionName, Is.EqualTo("System.Int32")); var genericParamType = ((IMethod)method.MemberDefinition).Parameters.Single().Type; var interfaceGenericParamType = ((IMethod)interfaceMethod.MemberDefinition).Parameters.Single().Type; Assert.That(genericParamType.Kind, Is.EqualTo(TypeKind.TypeParameter)); Assert.That(interfaceGenericParamType.Kind, Is.EqualTo(TypeKind.TypeParameter)); Assert.That(interfaceGenericParamType.ReflectionName, Is.EqualTo(genericParamType.ReflectionName)); } } [Test] public void ExplicitGenericInterfaceImplementation() { ITypeDefinition impl = GetTypeDefinition(typeof(ExplicitGenericInterfaceImplementation)); IType genericInterfaceOfString = compilation.FindType(typeof(IGenericInterface<string>)); IMethod implMethod1 = impl.Methods.Single(m => !m.IsConstructor && !m.Parameters[1].IsRef); IMethod implMethod2 = impl.Methods.Single(m => !m.IsConstructor && m.Parameters[1].IsRef); Assert.That(implMethod1.IsExplicitInterfaceImplementation); Assert.That(implMethod2.IsExplicitInterfaceImplementation); IMethod interfaceMethod1 = (IMethod)implMethod1.ExplicitlyImplementedInterfaceMembers.Single(); Assert.That(interfaceMethod1.DeclaringType, Is.EqualTo(genericInterfaceOfString)); Assert.That(!interfaceMethod1.Parameters[1].IsRef); IMethod interfaceMethod2 = (IMethod)implMethod2.ExplicitlyImplementedInterfaceMembers.Single(); Assert.That(interfaceMethod2.DeclaringType, Is.EqualTo(genericInterfaceOfString)); Assert.That(interfaceMethod2.Parameters[1].IsRef); } [Test] public void ExplicitlyImplementedPropertiesShouldBeReportedAsBeingImplemented() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsPropertyExplicitly)); var prop = type.Properties.Single(); Assert.That(prop.ExplicitlyImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithProperty.Prop" })); Assert.That(prop.Getter.ExplicitlyImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithProperty.get_Prop" })); Assert.That(prop.Setter.ExplicitlyImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IInterfaceWithProperty.set_Prop" })); } [Test] public void ExplicitlyImplementedPropertiesShouldHaveExplicitlyImplementedAccessors() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsPropertyExplicitly)); var prop = type.Properties.Single(); Assert.That(prop.IsExplicitInterfaceImplementation); Assert.That(prop.Getter.IsExplicitInterfaceImplementation); Assert.That(prop.Setter.IsExplicitInterfaceImplementation); } /* The TS no longer provides implicit interface impls. [Test] public void EventAccessorsShouldBeReportedAsImplementingInterfaceAccessors() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsEvent)); var evt = type.Events.Single(p => p.Name == "Event"); Assert.That(evt.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.Event" })); Assert.That(evt.AddAccessor.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.add_Event" })); Assert.That(evt.RemoveAccessor.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.remove_Event" })); } [Test] public void EventAccessorsShouldBeReportedAsImplementingInterfaceAccessorsWhenCustomAccessorMethodsAreUsed() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsEventWithCustomAccessors)); var evt = type.Events.Single(p => p.Name == "Event"); Assert.That(evt.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.Event" })); Assert.That(evt.AddAccessor.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.add_Event" })); Assert.That(evt.RemoveAccessor.ImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.remove_Event" })); } */ [Test] public void ExplicitlyImplementedEventsShouldBeReportedAsBeingImplemented() { ITypeDefinition type = GetTypeDefinition(typeof(ClassThatImplementsEventExplicitly)); var evt = type.Events.Single(); Assert.That(evt.ExplicitlyImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.Event" })); Assert.That(evt.AddAccessor.ExplicitlyImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.add_Event" })); Assert.That(evt.RemoveAccessor.ExplicitlyImplementedInterfaceMembers.Select(p => p.ReflectionName).ToList(), Is.EqualTo(new[] { "ICSharpCode.Decompiler.Tests.TypeSystem.IHasEvent.remove_Event" })); } [Test] public void MembersDeclaredInDerivedInterfacesDoNotImplementBaseMembers() { ITypeDefinition type = GetTypeDefinition(typeof(IShadowTestDerived)); var method = type.Methods.Single(m => m.Name == "Method"); var indexer = type.Properties.Single(p => p.IsIndexer); var prop = type.Properties.Single(p => p.Name == "Prop"); var evt = type.Events.Single(e => e.Name == "Evt"); Assert.That(method.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(indexer.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(indexer.Getter.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(indexer.Setter.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(prop.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(prop.Getter.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(prop.Setter.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(evt.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(evt.AddAccessor.ExplicitlyImplementedInterfaceMembers, Is.Empty); Assert.That(evt.RemoveAccessor.ExplicitlyImplementedInterfaceMembers, Is.Empty); } [Test] public void StaticClassTest() { ITypeDefinition type = GetTypeDefinition(typeof(StaticClass)); Assert.That(type.IsAbstract); Assert.That(type.IsSealed); Assert.That(type.IsStatic); } [Test] public void ExtensionMethodTest() { ITypeDefinition type = GetTypeDefinition(typeof(StaticClass)); var method = type.Methods.Single(m => m.Name == "Extension"); Assert.That(method.IsStatic); Assert.That(method.IsExtensionMethod); Assert.That(method.ReducedFrom, Is.Null); Assert.That(type.HasExtensionMethods); } [Test] public void NoDefaultConstructorOnStaticClassTest() { ITypeDefinition type = GetTypeDefinition(typeof(StaticClass)); Assert.That(type.GetConstructors().Count(), Is.EqualTo(0)); } [Test] public void IndexerNonDefaultName() { ITypeDefinition type = GetTypeDefinition(typeof(IndexerNonDefaultName)); var indexer = type.GetProperties(p => p.IsIndexer).Single(); Assert.That(indexer.Name, Is.EqualTo("Foo")); } [Test] public void TestNullableDefaultParameter() { ITypeDefinition type = GetTypeDefinition(typeof(ClassWithMethodThatHasNullableDefaultParameter)); var method = type.GetMethods().Single(m => m.Name == "Foo"); Assert.That(method.Parameters.Single().GetConstantValue(), Is.EqualTo(42)); } [Test] public void AccessibilityTests() { ITypeDefinition type = GetTypeDefinition(typeof(AccessibilityTest)); Assert.That(type.Methods.Single(m => m.Name == "Public").Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(type.Methods.Single(m => m.Name == "Internal").Accessibility, Is.EqualTo(Accessibility.Internal)); Assert.That(type.Methods.Single(m => m.Name == "ProtectedInternal").Accessibility, Is.EqualTo(Accessibility.ProtectedOrInternal)); Assert.That(type.Methods.Single(m => m.Name == "InternalProtected").Accessibility, Is.EqualTo(Accessibility.ProtectedOrInternal)); Assert.That(type.Methods.Single(m => m.Name == "Protected").Accessibility, Is.EqualTo(Accessibility.Protected)); Assert.That(type.Methods.Single(m => m.Name == "Private").Accessibility, Is.EqualTo(Accessibility.Private)); Assert.That(type.Methods.Single(m => m.Name == "None").Accessibility, Is.EqualTo(Accessibility.Private)); } private void AssertConstantField<T>(ITypeDefinition type, string name, T expected) { var f = type.GetFields().Single(x => x.Name == name); Assert.That(f.IsConst); Assert.That(f.GetConstantValue(), Is.EqualTo(expected)); Assert.That(f.GetAttributes().Count(), Is.EqualTo(0)); } [Test] public unsafe void ConstantFieldsCreatedWithNew() { ITypeDefinition type = GetTypeDefinition(typeof(ConstantFieldTest)); AssertConstantField<byte>(type, "CNewb", new byte()); AssertConstantField<sbyte>(type, "CNewsb", new sbyte()); AssertConstantField<char>(type, "CNewc", new char()); AssertConstantField<short>(type, "CNews", new short()); AssertConstantField<ushort>(type, "CNewus", new ushort()); AssertConstantField<int>(type, "CNewi", new int()); AssertConstantField<uint>(type, "CNewui", new uint()); AssertConstantField<long>(type, "CNewl", new long()); AssertConstantField<ulong>(type, "CNewul", new ulong()); AssertConstantField<double>(type, "CNewd", new double()); AssertConstantField<float>(type, "CNewf", new float()); AssertConstantField<decimal>(type, "CNewm", new decimal()); } [Test] public void ConstantFieldsSizeOf() { ITypeDefinition type = GetTypeDefinition(typeof(ConstantFieldTest)); AssertConstantField<int>(type, "SOsb", sizeof(sbyte)); AssertConstantField<int>(type, "SOb", sizeof(byte)); AssertConstantField<int>(type, "SOs", sizeof(short)); AssertConstantField<int>(type, "SOus", sizeof(ushort)); AssertConstantField<int>(type, "SOi", sizeof(int)); AssertConstantField<int>(type, "SOui", sizeof(uint)); AssertConstantField<int>(type, "SOl", sizeof(long)); AssertConstantField<int>(type, "SOul", sizeof(ulong)); AssertConstantField<int>(type, "SOc", sizeof(char)); AssertConstantField<int>(type, "SOf", sizeof(float)); AssertConstantField<int>(type, "SOd", sizeof(double)); AssertConstantField<int>(type, "SObl", sizeof(bool)); AssertConstantField<int>(type, "SOe", sizeof(MyEnum)); } [Test] public void ConstantEnumFromThisAssembly() { ITypeDefinition type = GetTypeDefinition(typeof(ConstantFieldTest)); IField field = type.Fields.Single(f => f.Name == "EnumFromThisAssembly"); Assert.That(field.IsConst); Assert.That(field.GetConstantValue(), Is.EqualTo((short)MyEnum.Second)); } [Test] public void ConstantEnumFromAnotherAssembly() { ITypeDefinition type = GetTypeDefinition(typeof(ConstantFieldTest)); IField field = type.Fields.Single(f => f.Name == "EnumFromAnotherAssembly"); Assert.That(field.IsConst); Assert.That(field.GetConstantValue(), Is.EqualTo((int)StringComparison.OrdinalIgnoreCase)); } [Test] public void DefaultOfEnum() { ITypeDefinition type = GetTypeDefinition(typeof(ConstantFieldTest)); IField field = type.Fields.Single(f => f.Name == "DefaultOfEnum"); Assert.That(field.IsConst); Assert.That(field.GetConstantValue(), Is.EqualTo((short)default(MyEnum))); } [Test] public void ExplicitImplementation() { var type = GetTypeDefinition(typeof(ExplicitImplementationTests)); var itype = GetTypeDefinition(typeof(IExplicitImplementationTests)); var methods = type.GetMethods(m => m.Name == "M" || m.Name.EndsWith(".M")).ToList(); var imethod = itype.GetMethods(m => m.Name == "M").Single(); Assert.That(methods.Select(m => m.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(imethod, Is.EqualTo(methods.SelectMany(m => m.ExplicitlyImplementedInterfaceMembers).Single())); var properties = type.GetProperties(p => p.Name == "P" || p.Name.EndsWith(".P")).ToList(); var iproperty = itype.GetProperties(m => m.Name == "P").Single(); Assert.That(properties.Select(p => p.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(iproperty, Is.EqualTo(properties.SelectMany(p => p.ExplicitlyImplementedInterfaceMembers).Single())); Assert.That(properties.Select(p => p.Getter.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(iproperty.Getter, Is.EqualTo(properties.SelectMany(p => p.Getter.ExplicitlyImplementedInterfaceMembers).Single())); Assert.That(properties.Select(p => p.Setter.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(iproperty.Setter, Is.EqualTo(properties.SelectMany(p => p.Setter.ExplicitlyImplementedInterfaceMembers).Single())); var indexers = type.GetProperties(p => p.Name == "Item" || p.Name.EndsWith(".Item")).ToList(); var iindexer = itype.GetProperties(m => m.Name == "Item").Single(); Assert.That(indexers.Select(p => p.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(iindexer, Is.EqualTo(indexers.SelectMany(p => p.ExplicitlyImplementedInterfaceMembers).Single())); Assert.That(indexers.Select(p => p.Getter.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(iindexer.Getter, Is.EqualTo(indexers.SelectMany(p => p.Getter.ExplicitlyImplementedInterfaceMembers).Single())); Assert.That(indexers.Select(p => p.Setter.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(iindexer.Setter, Is.EqualTo(indexers.SelectMany(p => p.Setter.ExplicitlyImplementedInterfaceMembers).Single())); var events = type.GetEvents(e => e.Name == "E" || e.Name.EndsWith(".E")).ToList(); var ievent = itype.GetEvents(m => m.Name == "E").Single(); Assert.That(events.Select(e => e.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(ievent, Is.EqualTo(events.SelectMany(e => e.ExplicitlyImplementedInterfaceMembers).Single())); Assert.That(events.Select(e => e.AddAccessor.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(ievent.AddAccessor, Is.EqualTo(events.SelectMany(e => e.AddAccessor.ExplicitlyImplementedInterfaceMembers).Single())); Assert.That(events.Select(e => e.RemoveAccessor.ExplicitlyImplementedInterfaceMembers.Count()).ToList(), Is.EquivalentTo(new[] { 0, 1 })); Assert.That(ievent.RemoveAccessor, Is.EqualTo(events.SelectMany(e => e.RemoveAccessor.ExplicitlyImplementedInterfaceMembers).Single())); } [Test] public void MarshalTests() { ITypeDefinition c = compilation.FindType(typeof(IMarshalAsTests)).GetDefinition(); Assert.That(c.GetMethods(m => m.Name == "GetCollectionByQuery2").Count(), Is.EqualTo(1)); } [Test] public void AttributesUsingNestedMembers() { var type = GetTypeDefinition(typeof(ClassWithAttributesUsingNestedMembers)); var inner = type.GetNestedTypes().Single(t => t.Name == "Inner"); var myAttribute = type.GetNestedTypes().Single(t => t.Name == "MyAttribute"); var typeTypeTestAttr = type.GetAttributes().Single(a => a.AttributeType.Name == "TypeTestAttribute"); Assert.That(typeTypeTestAttr.FixedArguments[0].Value, Is.EqualTo(42)); Assert.That(typeTypeTestAttr.FixedArguments[1].Value, Is.EqualTo(inner)); var typeMyAttr = type.GetAttributes().Single(a => a.AttributeType.Name == "MyAttribute"); Assert.That(typeMyAttr.AttributeType, Is.EqualTo(myAttribute)); var prop = type.GetProperties().Single(p => p.Name == "P"); var propTypeTestAttr = prop.GetAttributes().Single(a => a.AttributeType.Name == "TypeTestAttribute"); Assert.That(propTypeTestAttr.FixedArguments[0].Value, Is.EqualTo(42)); Assert.That(propTypeTestAttr.FixedArguments[1].Value, Is.EqualTo(inner)); var propMyAttr = prop.GetAttributes().Single(a => a.AttributeType.Name == "MyAttribute"); Assert.That(propMyAttr.AttributeType, Is.EqualTo(myAttribute)); var attributedInner = (ITypeDefinition)type.GetNestedTypes().Single(t => t.Name == "AttributedInner"); var innerTypeTestAttr = attributedInner.GetAttributes().Single(a => a.AttributeType.Name == "TypeTestAttribute"); Assert.That(innerTypeTestAttr.FixedArguments[0].Value, Is.EqualTo(42)); Assert.That(innerTypeTestAttr.FixedArguments[1].Value, Is.EqualTo(inner)); var innerMyAttr = attributedInner.GetAttributes().Single(a => a.AttributeType.Name == "MyAttribute"); Assert.That(innerMyAttr.AttributeType, Is.EqualTo(myAttribute)); var attributedInner2 = (ITypeDefinition)type.GetNestedTypes().Single(t => t.Name == "AttributedInner2"); var inner2 = attributedInner2.GetNestedTypes().Single(t => t.Name == "Inner"); var myAttribute2 = attributedInner2.GetNestedTypes().Single(t => t.Name == "MyAttribute"); var inner2TypeTestAttr = attributedInner2.GetAttributes().Single(a => a.AttributeType.Name == "TypeTestAttribute"); Assert.That(inner2TypeTestAttr.FixedArguments[0].Value, Is.EqualTo(43)); Assert.That(inner2TypeTestAttr.FixedArguments[1].Value, Is.EqualTo(inner2)); var inner2MyAttr = attributedInner2.GetAttributes().Single(a => a.AttributeType.Name == "MyAttribute"); Assert.That(inner2MyAttr.AttributeType, Is.EqualTo(myAttribute2)); } [Test] public void ClassWithAttributeOnTypeParameter() { var tp = GetTypeDefinition(typeof(ClassWithAttributeOnTypeParameter<>)).TypeParameters.Single(); var attr = tp.GetAttributes().Single(); Assert.That(attr.AttributeType.Name, Is.EqualTo("DoubleAttribute")); } [Test] public void InheritanceTest() { ITypeDefinition c = compilation.FindType(typeof(SystemException)).GetDefinition(); ITypeDefinition c2 = compilation.FindType(typeof(Exception)).GetDefinition(); Assert.That(c, Is.Not.Null, "c is null"); Assert.That(c2, Is.Not.Null, "c2 is null"); //Assert.AreEqual(3, c.BaseTypes.Count); // Inherited interfaces are not reported by Cecil // which matches the behaviour of our C#/VB parsers Assert.That(c.DirectBaseTypes.First().FullName, Is.EqualTo("System.Exception")); Assert.That(c.DirectBaseTypes.First(), Is.SameAs(c2)); string[] superTypes = c.GetAllBaseTypes().Select(t => t.ReflectionName).ToArray(); Assert.That(superTypes, Is.EqualTo(new string[] { "System.Object", "System.Runtime.Serialization.ISerializable", "System.Runtime.InteropServices._Exception", "System.Exception", "System.SystemException" })); } [Test] public void GenericPropertyTest() { ITypeDefinition c = compilation.FindType(typeof(Comparer<>)).GetDefinition(); IProperty def = c.Properties.Single(p => p.Name == "Default"); ParameterizedType pt = (ParameterizedType)def.ReturnType; Assert.That(pt.FullName, Is.EqualTo("System.Collections.Generic.Comparer")); Assert.That(pt.TypeArguments[0], Is.EqualTo(c.TypeParameters[0])); } [Test] public void PointerTypeTest() { ITypeDefinition c = compilation.FindType(typeof(IntPtr)).GetDefinition(); IMethod toPointer = c.Methods.Single(p => p.Name == "ToPointer"); Assert.That(toPointer.ReturnType.ReflectionName, Is.EqualTo("System.Void*")); Assert.That(toPointer.ReturnType is PointerType); Assert.That(((PointerType)toPointer.ReturnType).ElementType.FullName, Is.EqualTo("System.Void")); } [Test] public void DateTimeDefaultConstructor() { ITypeDefinition c = compilation.FindType(typeof(DateTime)).GetDefinition(); Assert.That(c.Methods.Count(m => m.IsConstructor && !m.IsStatic && m.Parameters.Count == 0), Is.EqualTo(1)); Assert.That(c.GetConstructors().Count(m => m.Parameters.Count == 0), Is.EqualTo(1)); } [Test] public void NoEncodingInfoDefaultConstructor() { ITypeDefinition c = compilation.FindType(typeof(EncodingInfo)).GetDefinition(); // EncodingInfo only has an internal constructor Assert.That(!c.Methods.Any(m => m.IsConstructor)); // and no implicit ctor should be added: Assert.That(c.GetConstructors().Count(), Is.EqualTo(0)); } [Test] public void StaticModifierTest() { ITypeDefinition c = compilation.FindType(typeof(Environment)).GetDefinition(); Assert.That(c, Is.Not.Null, "System.Environment not found"); Assert.That(c.IsAbstract, "class should be abstract"); Assert.That(c.IsSealed, "class should be sealed"); Assert.That(c.IsStatic, "class should be static"); } [Test] public void InnerClassReferenceTest() { ITypeDefinition c = compilation.FindType(typeof(Environment)).GetDefinition(); Assert.That(c, Is.Not.Null, "System.Environment not found"); IType rt = c.Methods.First(m => m.Name == "GetFolderPath").Parameters[0].Type; Assert.That(rt, Is.SameAs(c.NestedTypes.Single(ic => ic.Name == "SpecialFolder"))); } [Test] public void NestedTypesTest() { ITypeDefinition c = compilation.FindType(typeof(Environment.SpecialFolder)).GetDefinition(); Assert.That(c, Is.Not.Null, "c is null"); Assert.That(c.FullName, Is.EqualTo("System.Environment.SpecialFolder")); Assert.That(c.ReflectionName, Is.EqualTo("System.Environment+SpecialFolder")); } [Test] public void VoidHasNoMembers() { ITypeDefinition c = compilation.FindType(typeof(void)).GetDefinition(); Assert.That(c, Is.Not.Null, "System.Void not found"); Assert.That(c.Kind, Is.EqualTo(TypeKind.Void)); Assert.That(c.GetMethods().Count(), Is.EqualTo(0)); Assert.That(c.GetProperties().Count(), Is.EqualTo(0)); Assert.That(c.GetEvents().Count(), Is.EqualTo(0)); Assert.That(c.GetFields().Count(), Is.EqualTo(0)); } [Test] public void Void_SerializableAttribute() { ITypeDefinition c = compilation.FindType(typeof(void)).GetDefinition(); var attr = c.GetAttributes().Single(a => a.AttributeType.FullName == "System.SerializableAttribute"); Assert.That(attr.Constructor.Parameters.Count, Is.EqualTo(0)); Assert.That(attr.FixedArguments.Length, Is.EqualTo(0)); Assert.That(attr.NamedArguments.Length, Is.EqualTo(0)); } [Test] public void Void_StructLayoutAttribute() { ITypeDefinition c = compilation.FindType(typeof(void)).GetDefinition(); var attr = c.GetAttributes().Single(a => a.AttributeType.FullName == "System.Runtime.InteropServices.StructLayoutAttribute"); Assert.That(attr.Constructor.Parameters.Count, Is.EqualTo(1)); Assert.That(attr.FixedArguments.Length, Is.EqualTo(1)); Assert.That(attr.FixedArguments[0].Value, Is.EqualTo(0)); Assert.That(attr.NamedArguments.Length, Is.EqualTo(1)); Assert.That(attr.NamedArguments[0].Name, Is.EqualTo("Size")); Assert.That(attr.NamedArguments[0].Value, Is.EqualTo(1)); } [Test] public void Void_ComVisibleAttribute() { ITypeDefinition c = compilation.FindType(typeof(void)).GetDefinition(); var attr = c.GetAttributes().Single(a => a.AttributeType.FullName == "System.Runtime.InteropServices.ComVisibleAttribute"); Assert.That(attr.Constructor.Parameters.Count, Is.EqualTo(1)); Assert.That(attr.FixedArguments.Length, Is.EqualTo(1)); Assert.That(attr.FixedArguments[0].Value, Is.EqualTo(true)); Assert.That(attr.NamedArguments.Length, Is.EqualTo(0)); } [Test] public void NestedClassInGenericClassTest() { ITypeDefinition dictionary = compilation.FindType(typeof(Dictionary<,>)).GetDefinition(); Assert.That(dictionary, Is.Not.Null); ITypeDefinition valueCollection = compilation.FindType(typeof(Dictionary<,>.ValueCollection)).GetDefinition(); Assert.That(valueCollection, Is.Not.Null); var dictionaryRT = new ParameterizedType(dictionary, new[] { compilation.FindType(typeof(string)).GetDefinition(), compilation.FindType(typeof(int)).GetDefinition() }); IProperty valueProperty = dictionaryRT.GetProperties(p => p.Name == "Values").Single(); IType parameterizedValueCollection = valueProperty.ReturnType; Assert.That(parameterizedValueCollection.ReflectionName, Is.EqualTo("System.Collections.Generic.Dictionary`2+ValueCollection[[System.String],[System.Int32]]")); Assert.That(parameterizedValueCollection.GetDefinition(), Is.SameAs(valueCollection)); } [Test] public void ValueCollectionCountModifiers() { ITypeDefinition valueCollection = compilation.FindType(typeof(Dictionary<,>.ValueCollection)).GetDefinition(); Assert.That(valueCollection.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(valueCollection.IsSealed); Assert.That(!valueCollection.IsAbstract); Assert.That(!valueCollection.IsStatic); IProperty count = valueCollection.Properties.Single(p => p.Name == "Count"); Assert.That(count.Accessibility, Is.EqualTo(Accessibility.Public)); // It's sealed on the IL level; but in C# it's just a normal non-virtual method that happens to implement an interface Assert.That(!count.IsSealed); Assert.That(!count.IsVirtual); Assert.That(!count.IsAbstract); } [Test] public void MathAcosModifiers() { ITypeDefinition math = compilation.FindType(typeof(Math)).GetDefinition(); Assert.That(math.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(math.IsSealed); Assert.That(math.IsAbstract); Assert.That(math.IsStatic); IMethod acos = math.Methods.Single(p => p.Name == "Acos"); Assert.That(acos.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(acos.IsStatic); Assert.That(!acos.IsAbstract); Assert.That(!acos.IsSealed); Assert.That(!acos.IsVirtual); Assert.That(!acos.IsOverride); } [Test] public void EncodingModifiers() { ITypeDefinition encoding = compilation.FindType(typeof(Encoding)).GetDefinition(); Assert.That(encoding.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(!encoding.IsSealed); Assert.That(encoding.IsAbstract); IMethod getDecoder = encoding.Methods.Single(p => p.Name == "GetDecoder"); Assert.That(getDecoder.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(!getDecoder.IsStatic); Assert.That(!getDecoder.IsAbstract); Assert.That(!getDecoder.IsSealed); Assert.That(getDecoder.IsVirtual); Assert.That(!getDecoder.IsOverride); IMethod getMaxByteCount = encoding.Methods.Single(p => p.Name == "GetMaxByteCount"); Assert.That(getMaxByteCount.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(!getMaxByteCount.IsStatic); Assert.That(getMaxByteCount.IsAbstract); Assert.That(!getMaxByteCount.IsSealed); Assert.That(!getMaxByteCount.IsVirtual); Assert.That(!getMaxByteCount.IsOverride); IProperty encoderFallback = encoding.Properties.Single(p => p.Name == "EncoderFallback"); Assert.That(encoderFallback.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(!encoderFallback.IsStatic); Assert.That(!encoderFallback.IsAbstract); Assert.That(!encoderFallback.IsSealed); Assert.That(!encoderFallback.IsVirtual); Assert.That(!encoderFallback.IsOverride); } [Test] public void UnicodeEncodingModifiers() { ITypeDefinition encoding = compilation.FindType(typeof(UnicodeEncoding)).GetDefinition(); Assert.That(encoding.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(!encoding.IsSealed); Assert.That(!encoding.IsAbstract); IMethod getDecoder = encoding.Methods.Single(p => p.Name == "GetDecoder"); Assert.That(getDecoder.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(!getDecoder.IsStatic); Assert.That(!getDecoder.IsAbstract); Assert.That(!getDecoder.IsSealed); Assert.That(!getDecoder.IsVirtual); Assert.That(getDecoder.IsOverride); } [Test] public void UTF32EncodingModifiers() { ITypeDefinition encoding = compilation.FindType(typeof(UTF32Encoding)).GetDefinition(); Assert.That(encoding.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(encoding.IsSealed); Assert.That(!encoding.IsAbstract); IMethod getDecoder = encoding.Methods.Single(p => p.Name == "GetDecoder"); Assert.That(getDecoder.Accessibility, Is.EqualTo(Accessibility.Public)); Assert.That(!getDecoder.IsStatic); Assert.That(!getDecoder.IsAbstract); Assert.That(!getDecoder.IsSealed); Assert.That(!getDecoder.IsVirtual); Assert.That(getDecoder.IsOverride); } [Test] public void FindRedirectedType() { var compilationWithSystemCore = new SimpleCompilation(SystemCore, Mscorlib); var typeRef = ReflectionHelper.ParseReflectionName("System.Func`2, System.Core"); ITypeDefinition c = typeRef.Resolve(new SimpleTypeResolveContext(compilationWithSystemCore)).GetDefinition(); Assert.That(c, Is.Not.Null, "System.Func<,> not found"); Assert.That(c.ParentModule.AssemblyName, Is.EqualTo("mscorlib")); } public void DelegateIsClass() { var @delegate = compilation.FindType(KnownTypeCode.Delegate).GetDefinition(); Assert.That(@delegate, Is.EqualTo(TypeKind.Class)); Assert.That(!@delegate.IsSealed); } public void MulticastDelegateIsClass() { var multicastDelegate = compilation.FindType(KnownTypeCode.MulticastDelegate).GetDefinition(); Assert.That(multicastDelegate, Is.EqualTo(TypeKind.Class)); Assert.That(!multicastDelegate.IsSealed); } [Test] public void HasSpecialName() { var nonCustomAttributes = compilation.FindType(typeof(NonCustomAttributes)).GetDefinition(); var method = nonCustomAttributes.GetMethods(m => m.Name == "SpecialNameMethod").Single(); var property = nonCustomAttributes.GetProperties(p => p.Name == "SpecialNameProperty").Single(); var @event = nonCustomAttributes.GetEvents(e => e.Name == "SpecialNameEvent").Single(); var field = nonCustomAttributes.GetFields(f => f.Name == "SpecialNameField").Single(); var @class = nonCustomAttributes.GetNestedTypes(t => t.Name == "SpecialNameClass").Single().GetDefinition(); var @struct = nonCustomAttributes.GetNestedTypes(t => t.Name == "SpecialNameStruct").Single().GetDefinition(); Assert.That(method.HasAttribute(KnownAttribute.SpecialName)); Assert.That(property.HasAttribute(KnownAttribute.SpecialName)); Assert.That(@event.HasAttribute(KnownAttribute.SpecialName)); Assert.That(field.HasAttribute(KnownAttribute.SpecialName)); Assert.That(@class.HasAttribute(KnownAttribute.SpecialName)); Assert.That(@struct.HasAttribute(KnownAttribute.SpecialName)); } } }
ILSpy/ICSharpCode.Decompiler.Tests/TypeSystem/TypeSystemLoaderTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TypeSystem/TypeSystemLoaderTests.cs", "repo_id": "ILSpy", "token_count": 34369 }
196
// // CSharpFormattingOptions.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.ComponentModel; namespace ICSharpCode.Decompiler.CSharp.OutputVisitor { public enum BraceStyle { EndOfLine, EndOfLineWithoutSpace, NextLine, NextLineShifted, NextLineShifted2, BannerStyle } public enum PropertyFormatting { SingleLine, MultipleLines } public enum Wrapping { DoNotWrap, WrapAlways, WrapIfTooLong } public enum NewLinePlacement { DoNotCare, NewLine, SameLine } public enum UsingPlacement { TopOfFile, InsideNamespace } public enum EmptyLineFormatting { DoNotChange, Indent, DoNotIndent } [TypeConverter(typeof(ExpandableObjectConverter))] public class CSharpFormattingOptions { public string Name { get; set; } public bool IsBuiltIn { get; set; } public CSharpFormattingOptions Clone() { return (CSharpFormattingOptions)MemberwiseClone(); } #region Indentation public string IndentationString { get; set; } = "\t"; public bool IndentNamespaceBody { // tested get; set; } public bool IndentClassBody { // tested get; set; } public bool IndentInterfaceBody { // tested get; set; } public bool IndentStructBody { // tested get; set; } public bool IndentEnumBody { // tested get; set; } public bool IndentMethodBody { // tested get; set; } public bool IndentPropertyBody { // tested get; set; } public bool IndentEventBody { // tested get; set; } public bool IndentBlocks { // tested get; set; } public bool IndentSwitchBody { // tested get; set; } public bool IndentCaseBody { // tested get; set; } public bool IndentBreakStatements { // tested get; set; } public bool AlignEmbeddedStatements { // tested get; set; } public bool AlignElseInIfStatements { get; set; } public PropertyFormatting AutoPropertyFormatting { get; set; } public PropertyFormatting SimplePropertyFormatting { // tested get; set; } public EmptyLineFormatting EmptyLineFormatting { get; set; } public bool IndentPreprocessorDirectives { // tested get; set; } public bool AlignToMemberReferenceDot { // TODO! get; set; } public bool IndentBlocksInsideExpressions { get; set; } #endregion #region Braces public BraceStyle NamespaceBraceStyle { // tested get; set; } public BraceStyle ClassBraceStyle { // tested get; set; } public BraceStyle InterfaceBraceStyle { // tested get; set; } public BraceStyle StructBraceStyle { // tested get; set; } public BraceStyle EnumBraceStyle { // tested get; set; } public BraceStyle MethodBraceStyle { // tested get; set; } public BraceStyle AnonymousMethodBraceStyle { get; set; } public BraceStyle ConstructorBraceStyle { // tested get; set; } public BraceStyle DestructorBraceStyle { // tested get; set; } public BraceStyle PropertyBraceStyle { // tested get; set; } public BraceStyle PropertyGetBraceStyle { // tested get; set; } public BraceStyle PropertySetBraceStyle { // tested get; set; } public PropertyFormatting SimpleGetBlockFormatting { // tested get; set; } public PropertyFormatting SimpleSetBlockFormatting { // tested get; set; } public BraceStyle EventBraceStyle { // tested get; set; } public BraceStyle EventAddBraceStyle { // tested get; set; } public BraceStyle EventRemoveBraceStyle { // tested get; set; } public bool AllowEventAddBlockInline { // tested get; set; } public bool AllowEventRemoveBlockInline { // tested get; set; } public BraceStyle StatementBraceStyle { // tested get; set; } public bool AllowIfBlockInline { get; set; } bool allowOneLinedArrayInitialziers = true; public bool AllowOneLinedArrayInitialziers { get { return allowOneLinedArrayInitialziers; } set { allowOneLinedArrayInitialziers = value; } } #endregion #region NewLines public NewLinePlacement ElseNewLinePlacement { // tested get; set; } public NewLinePlacement ElseIfNewLinePlacement { // tested get; set; } public NewLinePlacement CatchNewLinePlacement { // tested get; set; } public NewLinePlacement FinallyNewLinePlacement { // tested get; set; } public NewLinePlacement WhileNewLinePlacement { // tested get; set; } NewLinePlacement embeddedStatementPlacement = NewLinePlacement.NewLine; public NewLinePlacement EmbeddedStatementPlacement { get { return embeddedStatementPlacement; } set { embeddedStatementPlacement = value; } } #endregion #region Spaces public bool SpaceBetweenParameterAttributeSections { get; set; } // Methods public bool SpaceBeforeMethodDeclarationParentheses { // tested get; set; } public bool SpaceBetweenEmptyMethodDeclarationParentheses { get; set; } public bool SpaceBeforeMethodDeclarationParameterComma { // tested get; set; } public bool SpaceAfterMethodDeclarationParameterComma { // tested get; set; } public bool SpaceWithinMethodDeclarationParentheses { // tested get; set; } // Method calls public bool SpaceBeforeMethodCallParentheses { // tested get; set; } public bool SpaceBetweenEmptyMethodCallParentheses { // tested get; set; } public bool SpaceBeforeMethodCallParameterComma { // tested get; set; } public bool SpaceAfterMethodCallParameterComma { // tested get; set; } public bool SpaceWithinMethodCallParentheses { // tested get; set; } // fields public bool SpaceBeforeFieldDeclarationComma { // tested get; set; } public bool SpaceAfterFieldDeclarationComma { // tested get; set; } // local variables public bool SpaceBeforeLocalVariableDeclarationComma { // tested get; set; } public bool SpaceAfterLocalVariableDeclarationComma { // tested get; set; } // constructors public bool SpaceBeforeConstructorDeclarationParentheses { // tested get; set; } public bool SpaceBetweenEmptyConstructorDeclarationParentheses { // tested get; set; } public bool SpaceBeforeConstructorDeclarationParameterComma { // tested get; set; } public bool SpaceAfterConstructorDeclarationParameterComma { // tested get; set; } public bool SpaceWithinConstructorDeclarationParentheses { // tested get; set; } public NewLinePlacement NewLineBeforeConstructorInitializerColon { get; set; } public NewLinePlacement NewLineAfterConstructorInitializerColon { get; set; } // indexer public bool SpaceBeforeIndexerDeclarationBracket { // tested get; set; } public bool SpaceWithinIndexerDeclarationBracket { // tested get; set; } public bool SpaceBeforeIndexerDeclarationParameterComma { get; set; } public bool SpaceAfterIndexerDeclarationParameterComma { get; set; } // delegates public bool SpaceBeforeDelegateDeclarationParentheses { get; set; } public bool SpaceBetweenEmptyDelegateDeclarationParentheses { get; set; } public bool SpaceBeforeDelegateDeclarationParameterComma { get; set; } public bool SpaceAfterDelegateDeclarationParameterComma { get; set; } public bool SpaceWithinDelegateDeclarationParentheses { get; set; } public bool SpaceBeforeNewParentheses { // tested get; set; } public bool SpaceBeforeIfParentheses { // tested get; set; } public bool SpaceBeforeWhileParentheses { // tested get; set; } public bool SpaceBeforeForParentheses { // tested get; set; } public bool SpaceBeforeForeachParentheses { // tested get; set; } public bool SpaceBeforeCatchParentheses { // tested get; set; } public bool SpaceBeforeSwitchParentheses { // tested get; set; } public bool SpaceBeforeLockParentheses { // tested get; set; } public bool SpaceBeforeUsingParentheses { // tested get; set; } public bool SpaceAroundAssignment { // tested get; set; } public bool SpaceAroundLogicalOperator { // tested get; set; } public bool SpaceAroundEqualityOperator { // tested get; set; } public bool SpaceAroundRelationalOperator { // tested get; set; } public bool SpaceAroundBitwiseOperator { // tested get; set; } public bool SpaceAroundAdditiveOperator { // tested get; set; } public bool SpaceAroundMultiplicativeOperator { // tested get; set; } public bool SpaceAroundShiftOperator { // tested get; set; } public bool SpaceAroundNullCoalescingOperator { // Tested get; set; } public bool SpaceAfterUnsafeAddressOfOperator { // Tested get; set; } public bool SpaceAfterUnsafeAsteriskOfOperator { // Tested get; set; } public bool SpaceAroundUnsafeArrowOperator { // Tested get; set; } public bool SpacesWithinParentheses { // tested get; set; } public bool SpacesWithinIfParentheses { // tested get; set; } public bool SpacesWithinWhileParentheses { // tested get; set; } public bool SpacesWithinForParentheses { // tested get; set; } public bool SpacesWithinForeachParentheses { // tested get; set; } public bool SpacesWithinCatchParentheses { // tested get; set; } public bool SpacesWithinSwitchParentheses { // tested get; set; } public bool SpacesWithinLockParentheses { // tested get; set; } public bool SpacesWithinUsingParentheses { // tested get; set; } public bool SpacesWithinCastParentheses { // tested get; set; } public bool SpacesWithinSizeOfParentheses { // tested get; set; } public bool SpaceBeforeSizeOfParentheses { // tested get; set; } public bool SpacesWithinTypeOfParentheses { // tested get; set; } public bool SpacesWithinNewParentheses { // tested get; set; } public bool SpacesBetweenEmptyNewParentheses { // tested get; set; } public bool SpaceBeforeNewParameterComma { // tested get; set; } public bool SpaceAfterNewParameterComma { // tested get; set; } public bool SpaceBeforeTypeOfParentheses { // tested get; set; } public bool SpacesWithinCheckedExpressionParantheses { // tested get; set; } public bool SpaceBeforeConditionalOperatorCondition { // tested get; set; } public bool SpaceAfterConditionalOperatorCondition { // tested get; set; } public bool SpaceBeforeConditionalOperatorSeparator { // tested get; set; } public bool SpaceAfterConditionalOperatorSeparator { // tested get; set; } public bool SpaceBeforeAnonymousMethodParentheses { get; set; } public bool SpaceWithinAnonymousMethodParentheses { get; set; } // brackets public bool SpacesWithinBrackets { // tested get; set; } public bool SpacesBeforeBrackets { // tested get; set; } public bool SpaceBeforeBracketComma { // tested get; set; } public bool SpaceAfterBracketComma { // tested get; set; } public bool SpaceBeforeForSemicolon { // tested get; set; } public bool SpaceAfterForSemicolon { // tested get; set; } public bool SpaceAfterTypecast { // tested get; set; } public bool SpaceBeforeArrayDeclarationBrackets { // tested get; set; } public bool SpaceInNamedArgumentAfterDoubleColon { get; set; } public bool RemoveEndOfLineWhiteSpace { get; set; } public bool SpaceBeforeSemicolon { get; set; } #endregion #region Blank Lines public int MinimumBlankLinesBeforeUsings { get; set; } public int MinimumBlankLinesAfterUsings { get; set; } public int MinimumBlankLinesBeforeFirstDeclaration { get; set; } public int MinimumBlankLinesBetweenTypes { get; set; } public int MinimumBlankLinesBetweenFields { get; set; } public int MinimumBlankLinesBetweenEventFields { get; set; } public int MinimumBlankLinesBetweenMembers { get; set; } public int MinimumBlankLinesAroundRegion { get; set; } public int MinimumBlankLinesInsideRegion { get; set; } #endregion #region Keep formatting public bool KeepCommentsAtFirstColumn { get; set; } #endregion #region Wrapping public Wrapping ArrayInitializerWrapping { get; set; } public BraceStyle ArrayInitializerBraceStyle { get; set; } public Wrapping ChainedMethodCallWrapping { get; set; } public Wrapping MethodCallArgumentWrapping { get; set; } public NewLinePlacement NewLineAferMethodCallOpenParentheses { get; set; } public NewLinePlacement MethodCallClosingParenthesesOnNewLine { get; set; } public Wrapping IndexerArgumentWrapping { get; set; } public NewLinePlacement NewLineAferIndexerOpenBracket { get; set; } public NewLinePlacement IndexerClosingBracketOnNewLine { get; set; } public Wrapping MethodDeclarationParameterWrapping { get; set; } public NewLinePlacement NewLineAferMethodDeclarationOpenParentheses { get; set; } public NewLinePlacement MethodDeclarationClosingParenthesesOnNewLine { get; set; } public Wrapping IndexerDeclarationParameterWrapping { get; set; } public NewLinePlacement NewLineAferIndexerDeclarationOpenBracket { get; set; } public NewLinePlacement IndexerDeclarationClosingBracketOnNewLine { get; set; } public bool AlignToFirstIndexerArgument { get; set; } public bool AlignToFirstIndexerDeclarationParameter { get; set; } public bool AlignToFirstMethodCallArgument { get; set; } public bool AlignToFirstMethodDeclarationParameter { get; set; } public NewLinePlacement NewLineBeforeNewQueryClause { get; set; } #endregion #region Using Declarations public UsingPlacement UsingPlacement { get; set; } #endregion internal CSharpFormattingOptions() { } /*public static CSharpFormattingOptions Load (FilePath selectedFile) { using (var stream = System.IO.File.OpenRead (selectedFile)) { return Load (stream); } } public static CSharpFormattingOptions Load (System.IO.Stream input) { CSharpFormattingOptions result = FormattingOptionsFactory.CreateMonoOptions (); result.Name = "noname"; using (XmlTextReader reader = new XmlTextReader (input)) { while (reader.Read ()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.LocalName == "Property") { var info = typeof(CSharpFormattingOptions).GetProperty (reader.GetAttribute ("name")); string valString = reader.GetAttribute ("value"); object value; if (info.PropertyType == typeof(bool)) { value = Boolean.Parse (valString); } else if (info.PropertyType == typeof(int)) { value = Int32.Parse (valString); } else { value = Enum.Parse (info.PropertyType, valString); } info.SetValue (result, value, null); } else if (reader.LocalName == "FormattingProfile") { result.Name = reader.GetAttribute ("name"); } } else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "FormattingProfile") { //Console.WriteLine ("result:" + result.Name); return result; } } } return result; } public void Save (string fileName) { using (var writer = new XmlTextWriter (fileName, Encoding.Default)) { writer.Formatting = System.Xml.Formatting.Indented; writer.Indentation = 1; writer.IndentChar = '\t'; writer.WriteStartElement ("FormattingProfile"); writer.WriteAttributeString ("name", Name); foreach (PropertyInfo info in typeof (CSharpFormattingOptions).GetProperties ()) { if (info.GetCustomAttributes (false).Any (o => o.GetType () == typeof(ItemPropertyAttribute))) { writer.WriteStartElement ("Property"); writer.WriteAttributeString ("name", info.Name); writer.WriteAttributeString ("value", info.GetValue (this, null).ToString ()); writer.WriteEndElement (); } } writer.WriteEndElement (); } } public bool Equals (CSharpFormattingOptions other) { foreach (PropertyInfo info in typeof (CSharpFormattingOptions).GetProperties ()) { if (info.GetCustomAttributes (false).Any (o => o.GetType () == typeof(ItemPropertyAttribute))) { object val = info.GetValue (this, null); object otherVal = info.GetValue (other, null); if (val == null) { if (otherVal == null) continue; return false; } if (!val.Equals (otherVal)) { //Console.WriteLine ("!equal"); return false; } } } //Console.WriteLine ("== equal"); return true; }*/ } }
ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpFormattingOptions.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpFormattingOptions.cs", "repo_id": "ILSpy", "token_count": 7144 }
197
// Copyright (c) 2016 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.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using ICSharpCode.Decompiler.CSharp.OutputVisitor; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.CSharp.Transforms; using ICSharpCode.Decompiler.DebugInfo; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.Semantics; using ICSharpCode.Decompiler.Solution; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; using Microsoft.Win32; using static ICSharpCode.Decompiler.Metadata.MetadataExtensions; namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler { /// <summary> /// Decompiles an assembly into a visual studio project file. /// </summary> public class WholeProjectDecompiler : IProjectInfoProvider { const int maxSegmentLength = 255; #region Settings /// <summary> /// Gets the setting this instance uses for decompiling. /// </summary> public DecompilerSettings Settings { get; } LanguageVersion? languageVersion; public LanguageVersion LanguageVersion { get { return languageVersion ?? Settings.GetMinimumRequiredVersion(); } set { var minVersion = Settings.GetMinimumRequiredVersion(); if (value < minVersion) throw new InvalidOperationException($"The chosen settings require at least {minVersion}." + $" Please change the DecompilerSettings accordingly."); languageVersion = value; } } public IAssemblyResolver AssemblyResolver { get; } public AssemblyReferenceClassifier AssemblyReferenceClassifier { get; } public IDebugInfoProvider DebugInfoProvider { get; } /// <summary> /// The MSBuild ProjectGuid to use for the new project. /// </summary> public Guid ProjectGuid { get; } /// <summary> /// The target directory that the decompiled files are written to. /// </summary> /// <remarks> /// This property is set by DecompileProject() and protected so that overridden protected members /// can access it. /// </remarks> public string TargetDirectory { get; protected set; } /// <summary> /// Path to the snk file to use for signing. /// <c>null</c> to not sign. /// </summary> public string StrongNameKeyFile { get; set; } public int MaxDegreeOfParallelism { get; set; } = Environment.ProcessorCount; public IProgress<DecompilationProgress> ProgressIndicator { get; set; } #endregion public WholeProjectDecompiler(IAssemblyResolver assemblyResolver) : this(new DecompilerSettings(), assemblyResolver, assemblyReferenceClassifier: null, debugInfoProvider: null) { } public WholeProjectDecompiler( DecompilerSettings settings, IAssemblyResolver assemblyResolver, AssemblyReferenceClassifier assemblyReferenceClassifier, IDebugInfoProvider debugInfoProvider) : this(settings, Guid.NewGuid(), assemblyResolver, assemblyReferenceClassifier, debugInfoProvider) { } protected WholeProjectDecompiler( DecompilerSettings settings, Guid projectGuid, IAssemblyResolver assemblyResolver, AssemblyReferenceClassifier assemblyReferenceClassifier, IDebugInfoProvider debugInfoProvider) { Settings = settings ?? throw new ArgumentNullException(nameof(settings)); ProjectGuid = projectGuid; AssemblyResolver = assemblyResolver ?? throw new ArgumentNullException(nameof(assemblyResolver)); AssemblyReferenceClassifier = assemblyReferenceClassifier ?? new AssemblyReferenceClassifier(); DebugInfoProvider = debugInfoProvider; projectWriter = Settings.UseSdkStyleProjectFormat ? ProjectFileWriterSdkStyle.Create() : ProjectFileWriterDefault.Create(); } // per-run members HashSet<string> directories = new HashSet<string>(Platform.FileNameComparer); readonly IProjectFileWriter projectWriter; public void DecompileProject(PEFile moduleDefinition, string targetDirectory, CancellationToken cancellationToken = default(CancellationToken)) { string projectFileName = Path.Combine(targetDirectory, CleanUpFileName(moduleDefinition.Name) + ".csproj"); using (var writer = new StreamWriter(projectFileName)) { DecompileProject(moduleDefinition, targetDirectory, writer, cancellationToken); } } public ProjectId DecompileProject(PEFile moduleDefinition, string targetDirectory, TextWriter projectFileWriter, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(targetDirectory)) { throw new InvalidOperationException("Must set TargetDirectory"); } TargetDirectory = targetDirectory; directories.Clear(); var resources = WriteResourceFilesInProject(moduleDefinition).ToList(); var files = WriteCodeFilesInProject(moduleDefinition, resources.SelectMany(r => r.PartialTypes ?? Enumerable.Empty<PartialTypeInfo>()).ToList(), cancellationToken).ToList(); files.AddRange(resources); files.AddRange(WriteMiscellaneousFilesInProject(moduleDefinition)); if (StrongNameKeyFile != null) { File.Copy(StrongNameKeyFile, Path.Combine(targetDirectory, Path.GetFileName(StrongNameKeyFile)), overwrite: true); } projectWriter.Write(projectFileWriter, this, files, moduleDefinition); string platformName = TargetServices.GetPlatformName(moduleDefinition); return new ProjectId(platformName, ProjectGuid, ProjectTypeGuids.CSharpWindows); } #region WriteCodeFilesInProject protected virtual bool IncludeTypeWhenDecompilingProject(PEFile module, TypeDefinitionHandle type) { var metadata = module.Metadata; var typeDef = metadata.GetTypeDefinition(type); string name = metadata.GetString(typeDef.Name); string ns = metadata.GetString(typeDef.Namespace); if (name == "<Module>" || CSharpDecompiler.MemberIsHidden(module, type, Settings)) return false; if (ns == "XamlGeneratedNamespace" && name == "GeneratedInternalTypeHelper") return false; if (!typeDef.IsNested && RemoveEmbeddedAttributes.attributeNames.Contains(ns + "." + name)) return false; return true; } CSharpDecompiler CreateDecompiler(DecompilerTypeSystem ts) { var decompiler = new CSharpDecompiler(ts, Settings); decompiler.DebugInfoProvider = DebugInfoProvider; decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers()); decompiler.AstTransforms.Add(new RemoveCLSCompliantAttribute()); return decompiler; } IEnumerable<ProjectItemInfo> WriteAssemblyInfo(DecompilerTypeSystem ts, CancellationToken cancellationToken) { var decompiler = CreateDecompiler(ts); decompiler.CancellationToken = cancellationToken; decompiler.AstTransforms.Add(new RemoveCompilerGeneratedAssemblyAttributes()); SyntaxTree syntaxTree = decompiler.DecompileModuleAndAssemblyAttributes(); const string prop = "Properties"; if (directories.Add(prop)) Directory.CreateDirectory(Path.Combine(TargetDirectory, prop)); string assemblyInfo = Path.Combine(prop, "AssemblyInfo.cs"); using (StreamWriter w = new StreamWriter(Path.Combine(TargetDirectory, assemblyInfo))) { syntaxTree.AcceptVisitor(new CSharpOutputVisitor(w, Settings.CSharpFormattingOptions)); } return new[] { new ProjectItemInfo("Compile", assemblyInfo) }; } IEnumerable<ProjectItemInfo> WriteCodeFilesInProject(Metadata.PEFile module, IList<PartialTypeInfo> partialTypes, CancellationToken cancellationToken) { var metadata = module.Metadata; var files = module.Metadata.GetTopLevelTypeDefinitions().Where(td => IncludeTypeWhenDecompilingProject(module, td)) .GroupBy(GetFileFileNameForHandle, StringComparer.OrdinalIgnoreCase).ToList(); var progressReporter = ProgressIndicator; var progress = new DecompilationProgress { TotalUnits = files.Count, Title = "Exporting project..." }; DecompilerTypeSystem ts = new DecompilerTypeSystem(module, AssemblyResolver, Settings); var workList = new HashSet<TypeDefinitionHandle>(); var processedTypes = new HashSet<TypeDefinitionHandle>(); ProcessFiles(files); while (workList.Count > 0) { var additionalFiles = workList .GroupBy(GetFileFileNameForHandle, StringComparer.OrdinalIgnoreCase).ToList(); workList.Clear(); ProcessFiles(additionalFiles); files.AddRange(additionalFiles); progress.TotalUnits = files.Count; } return files.Select(f => new ProjectItemInfo("Compile", f.Key)).Concat(WriteAssemblyInfo(ts, cancellationToken)); string GetFileFileNameForHandle(TypeDefinitionHandle h) { var type = metadata.GetTypeDefinition(h); string file = SanitizeFileName(metadata.GetString(type.Name) + ".cs"); string ns = metadata.GetString(type.Namespace); if (string.IsNullOrEmpty(ns)) { return file; } else { string dir = Settings.UseNestedDirectoriesForNamespaces ? CleanUpPath(ns) : CleanUpDirectoryName(ns); if (directories.Add(dir)) Directory.CreateDirectory(Path.Combine(TargetDirectory, dir)); return Path.Combine(dir, file); } } void ProcessFiles(List<IGrouping<string, TypeDefinitionHandle>> files) { processedTypes.AddRange(files.SelectMany(f => f)); Parallel.ForEach( Partitioner.Create(files, loadBalance: true), new ParallelOptions { MaxDegreeOfParallelism = this.MaxDegreeOfParallelism, CancellationToken = cancellationToken }, delegate (IGrouping<string, TypeDefinitionHandle> file) { try { using StreamWriter w = new StreamWriter(Path.Combine(TargetDirectory, file.Key)); CSharpDecompiler decompiler = CreateDecompiler(ts); foreach (var partialType in partialTypes) { decompiler.AddPartialTypeDefinition(partialType); } decompiler.CancellationToken = cancellationToken; var declaredTypes = file.ToArray(); var syntaxTree = decompiler.DecompileTypes(declaredTypes); foreach (var node in syntaxTree.Descendants) { var td = (node.GetResolveResult() as TypeResolveResult)?.Type.GetDefinition(); if (td?.ParentModule != ts.MainModule) continue; while (td?.DeclaringTypeDefinition != null) { td = td.DeclaringTypeDefinition; } if (td != null && td.MetadataToken is { IsNil: false } token && !processedTypes.Contains((TypeDefinitionHandle)token)) { lock (workList) { workList.Add((TypeDefinitionHandle)token); } } } syntaxTree.AcceptVisitor(new CSharpOutputVisitor(w, Settings.CSharpFormattingOptions)); } catch (Exception innerException) when (!(innerException is OperationCanceledException || innerException is DecompilerException)) { throw new DecompilerException(module, $"Error decompiling for '{file.Key}'", innerException); } progress.Status = file.Key; Interlocked.Increment(ref progress.UnitsCompleted); progressReporter?.Report(progress); }); } } #endregion #region WriteResourceFilesInProject protected virtual IEnumerable<ProjectItemInfo> WriteResourceFilesInProject(Metadata.PEFile module) { foreach (var r in module.Resources.Where(r => r.ResourceType == ResourceType.Embedded)) { Stream stream = r.TryOpenStream(); stream.Position = 0; if (r.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) { bool decodedIntoIndividualFiles; var individualResources = new List<ProjectItemInfo>(); try { var resourcesFile = new ResourcesFile(stream); if (resourcesFile.AllEntriesAreStreams()) { foreach (var (name, value) in resourcesFile) { string fileName = SanitizeFileName(name) .Replace('/', Path.DirectorySeparatorChar); string dirName = Path.GetDirectoryName(fileName); if (!string.IsNullOrEmpty(dirName) && directories.Add(dirName)) { Directory.CreateDirectory(Path.Combine(TargetDirectory, dirName)); } Stream entryStream = (Stream)value; entryStream.Position = 0; individualResources.AddRange( WriteResourceToFile(fileName, name, entryStream)); } decodedIntoIndividualFiles = true; } else { decodedIntoIndividualFiles = false; } } catch (BadImageFormatException) { decodedIntoIndividualFiles = false; } catch (EndOfStreamException) { decodedIntoIndividualFiles = false; } if (decodedIntoIndividualFiles) { foreach (var entry in individualResources) { yield return entry; } } else { stream.Position = 0; string fileName = GetFileNameForResource(r.Name); foreach (var entry in WriteResourceToFile(fileName, r.Name, stream)) { yield return entry; } } } else { string fileName = GetFileNameForResource(r.Name); using (FileStream fs = new FileStream(Path.Combine(TargetDirectory, fileName), FileMode.Create, FileAccess.Write)) { stream.Position = 0; stream.CopyTo(fs); } yield return new ProjectItemInfo("EmbeddedResource", fileName).With("LogicalName", r.Name); } } } protected virtual IEnumerable<ProjectItemInfo> WriteResourceToFile(string fileName, string resourceName, Stream entryStream) { if (fileName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) { string resx = Path.ChangeExtension(fileName, ".resx"); try { using (FileStream fs = new FileStream(Path.Combine(TargetDirectory, resx), FileMode.Create, FileAccess.Write)) using (ResXResourceWriter writer = new ResXResourceWriter(fs)) { foreach (var entry in new ResourcesFile(entryStream)) { writer.AddResource(entry.Key, entry.Value); } } return new[] { new ProjectItemInfo("EmbeddedResource", resx).With("LogicalName", resourceName) }; } catch (BadImageFormatException) { // if the .resources can't be decoded, just save them as-is } catch (EndOfStreamException) { // if the .resources can't be decoded, just save them as-is } } using (FileStream fs = new FileStream(Path.Combine(TargetDirectory, fileName), FileMode.Create, FileAccess.Write)) { entryStream.CopyTo(fs); } return new[] { new ProjectItemInfo("EmbeddedResource", fileName).With("LogicalName", resourceName) }; } string GetFileNameForResource(string fullName) { // Clean up the name first and ensure the length does not exceed the maximum length // supported by the OS. fullName = SanitizeFileName(fullName); // The purpose of the below algorithm is to "maximize" the directory name and "minimize" the file name. // That is, a full name of the form "Namespace1.Namespace2{...}.NamespaceN.ResourceName" is split such that // the directory part Namespace1\Namespace2\... reuses as many existing directories as // possible, and only the remaining name parts are used as prefix for the filename. // This is not affected by the UseNestedDirectoriesForNamespaces setting. string[] splitName = fullName.Split('\\', '/'); string fileName = string.Join(".", splitName); string separator = Path.DirectorySeparatorChar.ToString(); for (int i = splitName.Length - 1; i > 0; i--) { string ns = string.Join(separator, splitName, 0, i); if (directories.Contains(ns)) { string name = string.Join(".", splitName, i, splitName.Length - i); fileName = Path.Combine(ns, name); break; } } return fileName; } #endregion #region WriteMiscellaneousFilesInProject protected virtual IEnumerable<ProjectItemInfo> WriteMiscellaneousFilesInProject(PEFile module) { var resources = module.Reader.ReadWin32Resources(); if (resources == null) yield break; byte[] appIcon = CreateApplicationIcon(resources); if (appIcon != null) { File.WriteAllBytes(Path.Combine(TargetDirectory, "app.ico"), appIcon); yield return new ProjectItemInfo("ApplicationIcon", "app.ico"); } byte[] appManifest = CreateApplicationManifest(resources); if (appManifest != null && !IsDefaultApplicationManifest(appManifest)) { File.WriteAllBytes(Path.Combine(TargetDirectory, "app.manifest"), appManifest); yield return new ProjectItemInfo("ApplicationManifest", "app.manifest"); } var appConfig = module.FileName + ".config"; if (File.Exists(appConfig)) { File.Copy(appConfig, Path.Combine(TargetDirectory, "app.config"), overwrite: true); yield return new ProjectItemInfo("ApplicationConfig", Path.GetFileName(appConfig)); } } const int RT_ICON = 3; const int RT_GROUP_ICON = 14; unsafe static byte[] CreateApplicationIcon(Win32ResourceDirectory resources) { var iconGroup = resources.Find(new Win32ResourceName(RT_GROUP_ICON))?.FirstDirectory()?.FirstData()?.Data; if (iconGroup == null) return null; var iconDir = resources.Find(new Win32ResourceName(RT_ICON)); if (iconDir == null) return null; using var outStream = new MemoryStream(); using var writer = new BinaryWriter(outStream); fixed (byte* pIconGroupData = iconGroup) { var pIconGroup = (GRPICONDIR*)pIconGroupData; writer.Write(pIconGroup->idReserved); writer.Write(pIconGroup->idType); writer.Write(pIconGroup->idCount); int iconCount = pIconGroup->idCount; uint offset = (2 * 3) + ((uint)iconCount * 0x10); for (int i = 0; i < iconCount; i++) { var pIconEntry = pIconGroup->idEntries + i; writer.Write(pIconEntry->bWidth); writer.Write(pIconEntry->bHeight); writer.Write(pIconEntry->bColorCount); writer.Write(pIconEntry->bReserved); writer.Write(pIconEntry->wPlanes); writer.Write(pIconEntry->wBitCount); writer.Write(pIconEntry->dwBytesInRes); writer.Write(offset); offset += pIconEntry->dwBytesInRes; } for (int i = 0; i < iconCount; i++) { var icon = iconDir.FindDirectory(new Win32ResourceName(pIconGroup->idEntries[i].nID))?.FirstData()?.Data; if (icon == null) return null; writer.Write(icon); } } return outStream.ToArray(); } [StructLayout(LayoutKind.Sequential, Pack = 2)] unsafe struct GRPICONDIR { public ushort idReserved; public ushort idType; public ushort idCount; private fixed byte _idEntries[1]; [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")] public GRPICONDIRENTRY* idEntries { get { fixed (byte* p = _idEntries) return (GRPICONDIRENTRY*)p; } } }; [StructLayout(LayoutKind.Sequential, Pack = 2)] struct GRPICONDIRENTRY { public byte bWidth; public byte bHeight; public byte bColorCount; public byte bReserved; public ushort wPlanes; public ushort wBitCount; public uint dwBytesInRes; public short nID; }; const int RT_MANIFEST = 24; unsafe static byte[] CreateApplicationManifest(Win32ResourceDirectory resources) { return resources.Find(new Win32ResourceName(RT_MANIFEST))?.FirstDirectory()?.FirstData()?.Data; } static bool IsDefaultApplicationManifest(byte[] appManifest) { const string DEFAULT_APPMANIFEST = "<?xmlversion=\"1.0\"encoding=\"UTF-8\"standalone=\"yes\"?><assemblyxmlns=\"urn:schemas-microsoft-com" + ":asm.v1\"manifestVersion=\"1.0\"><assemblyIdentityversion=\"1.0.0.0\"name=\"MyApplication.app\"/><tr" + "ustInfoxmlns=\"urn:schemas-microsoft-com:asm.v2\"><security><requestedPrivilegesxmlns=\"urn:schemas-" + "microsoft-com:asm.v3\"><requestedExecutionLevellevel=\"asInvoker\"uiAccess=\"false\"/></requestedPri" + "vileges></security></trustInfo></assembly>"; string s = CleanUpApplicationManifest(appManifest); return s == DEFAULT_APPMANIFEST; } static string CleanUpApplicationManifest(byte[] appManifest) { bool bom = appManifest.Length >= 3 && appManifest[0] == 0xEF && appManifest[1] == 0xBB && appManifest[2] == 0xBF; string s = Encoding.UTF8.GetString(appManifest, bom ? 3 : 0, appManifest.Length - (bom ? 3 : 0)); var sb = new StringBuilder(s.Length); for (int i = 0; i < s.Length; i++) { char c = s[i]; switch (c) { case '\t': case '\n': case '\r': case ' ': continue; } sb.Append(c); } return sb.ToString(); } #endregion /// <summary> /// Cleans up a node name for use as a file name. /// </summary> public static string CleanUpFileName(string text) { return CleanUpName(text, separateAtDots: false, treatAsFileName: false); } /// <summary> /// Removes invalid characters from file names and reduces their length, /// but keeps file extensions and path structure intact. /// </summary> public static string SanitizeFileName(string fileName) { return CleanUpName(fileName, separateAtDots: false, treatAsFileName: true); } /// <summary> /// Cleans up a node name for use as a file system name. If <paramref name="separateAtDots"/> is active, /// dots are seen as segment separators. Each segment is limited to maxSegmentLength characters. /// If <paramref name="treatAsFileName"/> is active, we check for file a extension and try to preserve it, /// if it's valid. /// </summary> static string CleanUpName(string text, bool separateAtDots, bool treatAsFileName) { // Remove anything that could be confused with a rooted path. int pos = text.IndexOf(':'); if (pos > 0) text = text.Substring(0, pos); text = text.Trim(); string extension = null; int currentSegmentLength = 0; if (treatAsFileName) { // Check if input is a file name, i.e., has a valid extension // If yes, preserve extension and append it at the end. // But only, if the extension length does not exceed maxSegmentLength, // if that's the case we just give up and treat the extension no different // from the file name. int lastDot = text.LastIndexOf('.'); if (lastDot >= 0 && text.Length - lastDot < maxSegmentLength) { string originalText = text; extension = text.Substring(lastDot); text = text.Remove(lastDot); foreach (var c in extension) { if (!(char.IsLetterOrDigit(c) || c == '-' || c == '_' || c == '.')) { // extension contains an invalid character, therefore cannot be a valid extension. extension = null; text = originalText; break; } } } } // Remove generics pos = text.IndexOf('`'); if (pos > 0) { text = text.Substring(0, pos).Trim(); } // Whitelist allowed characters, replace everything else: StringBuilder b = new StringBuilder(text.Length + (extension?.Length ?? 0)); foreach (var c in text) { currentSegmentLength++; if (char.IsLetterOrDigit(c) || c == '-' || c == '_') { // if the current segment exceeds maxSegmentLength characters, // skip until the end of the segment. if (currentSegmentLength <= maxSegmentLength) b.Append(c); } else if (c == '.' && b.Length > 0 && b[b.Length - 1] != '.') { // if the current segment exceeds maxSegmentLength characters, // skip until the end of the segment. if (separateAtDots || currentSegmentLength <= maxSegmentLength) b.Append('.'); // allow dot, but never two in a row // Reset length at end of segment. if (separateAtDots) currentSegmentLength = 0; } else if (treatAsFileName && (c == '/' || c == '\\') && currentSegmentLength > 0) { // if we treat this as a file name, we've started a new segment b.Append(c); currentSegmentLength = 0; } else { // if the current segment exceeds maxSegmentLength characters, // skip until the end of the segment. if (currentSegmentLength <= maxSegmentLength) b.Append('-'); } } if (b.Length == 0) b.Append('-'); string name = b.ToString(); if (extension != null) { // make sure that adding the extension to the filename // does not exceed maxSegmentLength. // trim the name, if necessary. if (name.Length + extension.Length > maxSegmentLength) name = name.Remove(name.Length - extension.Length); name += extension; } if (IsReservedFileSystemName(name)) return name + "_"; else if (name == ".") return "_"; else return name; } /// <summary> /// Cleans up a node name for use as a directory name. /// </summary> public static string CleanUpDirectoryName(string text) { return CleanUpName(text, separateAtDots: false, treatAsFileName: false); } public static string CleanUpPath(string text) { return CleanUpName(text, separateAtDots: true, treatAsFileName: false) .Replace('.', Path.DirectorySeparatorChar); } static bool IsReservedFileSystemName(string name) { switch (name.ToUpperInvariant()) { case "AUX": case "COM1": case "COM2": case "COM3": case "COM4": case "COM5": case "COM6": case "COM7": case "COM8": case "COM9": case "CON": case "LPT1": case "LPT2": case "LPT3": case "LPT4": case "LPT5": case "LPT6": case "LPT7": case "LPT8": case "LPT9": case "NUL": case "PRN": return true; default: return false; } } public static bool CanUseSdkStyleProjectFormat(PEFile module) { return TargetServices.DetectTargetFramework(module).Moniker != null; } } public record struct ProjectItemInfo(string ItemType, string FileName) { public List<PartialTypeInfo> PartialTypes { get; set; } = null; public Dictionary<string, string> AdditionalProperties { get; set; } = null; public ProjectItemInfo With(string name, string value) { AdditionalProperties ??= new Dictionary<string, string>(); AdditionalProperties.Add(name, value); return this; } public ProjectItemInfo With(IEnumerable<KeyValuePair<string, string>> pairs) { AdditionalProperties ??= new Dictionary<string, string>(); AdditionalProperties.AddRange(pairs); return this; } } }
ILSpy/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs", "repo_id": "ILSpy", "token_count": 9951 }
198
using System; using System.Collections.Generic; using System.Text; using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching; namespace ICSharpCode.Decompiler.CSharp.Syntax { public class InterpolatedStringExpression : Expression { public static readonly TokenRole OpenQuote = new TokenRole("$\""); public static readonly TokenRole CloseQuote = new TokenRole("\""); public AstNodeCollection<InterpolatedStringContent> Content { get { return GetChildrenByRole(InterpolatedStringContent.Role); } } public InterpolatedStringExpression() { } public InterpolatedStringExpression(IList<InterpolatedStringContent> content) { Content.AddRange(content); } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitInterpolatedStringExpression(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitInterpolatedStringExpression(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitInterpolatedStringExpression(this, data); } protected internal override bool DoMatch(AstNode other, Match match) { InterpolatedStringExpression o = other as InterpolatedStringExpression; return o != null && !o.IsNull && this.Content.DoMatch(o.Content, match); } } public abstract class InterpolatedStringContent : AstNode { #region Null public new static readonly InterpolatedStringContent Null = new NullInterpolatedStringContent(); sealed class NullInterpolatedStringContent : InterpolatedStringContent { public override bool IsNull { get { return true; } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitNullNode(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitNullNode(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitNullNode(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { return other == null || other.IsNull; } } #endregion public new static readonly Role<InterpolatedStringContent> Role = new Role<InterpolatedStringContent>("InterpolatedStringContent", Syntax.InterpolatedStringContent.Null); public override NodeType NodeType => NodeType.Unknown; } /// <summary> /// { Expression , Alignment : Suffix } /// </summary> public class Interpolation : InterpolatedStringContent { public static readonly TokenRole LBrace = new TokenRole("{"); public static readonly TokenRole RBrace = new TokenRole("}"); public CSharpTokenNode LBraceToken { get { return GetChildByRole(LBrace); } } public Expression Expression { get { return GetChildByRole(Roles.Expression); } set { SetChildByRole(Roles.Expression, value); } } public int Alignment { get; } public string Suffix { get; } public CSharpTokenNode RBraceToken { get { return GetChildByRole(RBrace); } } public Interpolation() { } public Interpolation(Expression expression, int alignment = 0, string suffix = null) { Expression = expression; Alignment = alignment; Suffix = suffix; } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitInterpolation(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitInterpolation(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitInterpolation(this, data); } protected internal override bool DoMatch(AstNode other, Match match) { Interpolation o = other as Interpolation; return o != null && this.Expression.DoMatch(o.Expression, match); } } public class InterpolatedStringText : InterpolatedStringContent { public string Text { get; set; } public InterpolatedStringText() { } public InterpolatedStringText(string text) { Text = text; } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitInterpolatedStringText(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitInterpolatedStringText(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitInterpolatedStringText(this, data); } protected internal override bool DoMatch(AstNode other, Match match) { InterpolatedStringText o = other as InterpolatedStringText; return o != null && o.Text == this.Text; } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs", "repo_id": "ILSpy", "token_count": 1574 }
199
// // StackAllocExpression.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> /// stackalloc Type[Count] /// </summary> public class StackAllocExpression : Expression { public readonly static TokenRole StackallocKeywordRole = new TokenRole("stackalloc"); public readonly static Role<ArrayInitializerExpression> InitializerRole = new Role<ArrayInitializerExpression>("Initializer", ArrayInitializerExpression.Null); public CSharpTokenNode StackAllocToken { get { return GetChildByRole(StackallocKeywordRole); } } public AstType Type { get { return GetChildByRole(Roles.Type); } set { SetChildByRole(Roles.Type, value); } } public CSharpTokenNode LBracketToken { get { return GetChildByRole(Roles.LBracket); } } public Expression CountExpression { get { return GetChildByRole(Roles.Expression); } set { SetChildByRole(Roles.Expression, value); } } public CSharpTokenNode RBracketToken { get { return GetChildByRole(Roles.RBracket); } } public ArrayInitializerExpression Initializer { get { return GetChildByRole(InitializerRole); } set { SetChildByRole(InitializerRole, value); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitStackAllocExpression(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitStackAllocExpression(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitStackAllocExpression(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { StackAllocExpression o = other as StackAllocExpression; return o != null && this.Type.DoMatch(o.Type, match) && this.CountExpression.DoMatch(o.CountExpression, match) && this.Initializer.DoMatch(o.Initializer, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs", "repo_id": "ILSpy", "token_count": 983 }
200
// // DelegateDeclaration.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 ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.CSharp.Syntax { /// <summary> /// delegate ReturnType Name&lt;TypeParameters&gt;(Parameters) where Constraints; /// </summary> public class DelegateDeclaration : EntityDeclaration { public override NodeType NodeType { get { return NodeType.TypeDeclaration; } } public override SymbolKind SymbolKind { get { return SymbolKind.TypeDefinition; } } public CSharpTokenNode DelegateToken { get { return GetChildByRole(Roles.DelegateKeyword); } } public AstNodeCollection<TypeParameterDeclaration> TypeParameters { get { return GetChildrenByRole(Roles.TypeParameter); } } 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 AstNodeCollection<Constraint> Constraints { get { return GetChildrenByRole(Roles.Constraint); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitDelegateDeclaration(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitDelegateDeclaration(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitDelegateDeclaration(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { DelegateDeclaration o = other as DelegateDeclaration; return o != null && MatchString(this.Name, o.Name) && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.TypeParameters.DoMatch(o.TypeParameters, match) && this.Parameters.DoMatch(o.Parameters, match) && this.Constraints.DoMatch(o.Constraints, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs", "repo_id": "ILSpy", "token_count": 1005 }
201
// // SwitchStatement.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> /// switch (Expression) { SwitchSections } /// </summary> public class SwitchStatement : Statement { public static readonly TokenRole SwitchKeywordRole = new TokenRole("switch"); public static readonly Role<SwitchSection> SwitchSectionRole = new Role<SwitchSection>("SwitchSection", null); public CSharpTokenNode SwitchToken { get { return GetChildByRole(SwitchKeywordRole); } } public CSharpTokenNode LParToken { get { return GetChildByRole(Roles.LPar); } } public Expression Expression { get { return GetChildByRole(Roles.Expression); } set { SetChildByRole(Roles.Expression, value); } } public CSharpTokenNode RParToken { get { return GetChildByRole(Roles.RPar); } } public CSharpTokenNode LBraceToken { get { return GetChildByRole(Roles.LBrace); } } public AstNodeCollection<SwitchSection> SwitchSections { get { return GetChildrenByRole(SwitchSectionRole); } } public CSharpTokenNode RBraceToken { get { return GetChildByRole(Roles.RBrace); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitSwitchStatement(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitSwitchStatement(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitSwitchStatement(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { SwitchStatement o = other as SwitchStatement; return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match); } } public class SwitchSection : AstNode { #region PatternPlaceholder public static implicit operator SwitchSection(PatternMatching.Pattern pattern) { return pattern != null ? new PatternPlaceholder(pattern) : null; } sealed class PatternPlaceholder : SwitchSection, PatternMatching.INode { readonly PatternMatching.Pattern child; public PatternPlaceholder(PatternMatching.Pattern child) { this.child = child; } public override NodeType NodeType { get { return NodeType.Pattern; } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitPatternPlaceholder(this, child); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitPatternPlaceholder(this, child); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitPatternPlaceholder(this, child, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { return child.DoMatch(other, match); } bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo) { return child.DoMatchCollection(role, pos, match, backtrackingInfo); } } #endregion public static readonly Role<CaseLabel> CaseLabelRole = new Role<CaseLabel>("CaseLabel", null); public override NodeType NodeType { get { return NodeType.Unknown; } } public AstNodeCollection<CaseLabel> CaseLabels { get { return GetChildrenByRole(CaseLabelRole); } } public AstNodeCollection<Statement> Statements { get { return GetChildrenByRole(Roles.EmbeddedStatement); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitSwitchSection(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitSwitchSection(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitSwitchSection(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { SwitchSection o = other as SwitchSection; return o != null && this.CaseLabels.DoMatch(o.CaseLabels, match) && this.Statements.DoMatch(o.Statements, match); } } public class CaseLabel : AstNode { public static readonly TokenRole CaseKeywordRole = new TokenRole("case"); public static readonly TokenRole DefaultKeywordRole = new TokenRole("default"); public override NodeType NodeType { get { return NodeType.Unknown; } } /// <summary> /// Gets or sets the expression. The expression can be null - if the expression is null, it's the default switch section. /// </summary> public Expression Expression { get { return GetChildByRole(Roles.Expression); } set { SetChildByRole(Roles.Expression, value); } } public CSharpTokenNode ColonToken { get { return GetChildByRole(Roles.Colon); } } public CaseLabel() { } public CaseLabel(Expression expression) { this.Expression = expression; } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitCaseLabel(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitCaseLabel(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitCaseLabel(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { CaseLabel o = other as CaseLabel; return o != null && this.Expression.DoMatch(o.Expression, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs", "repo_id": "ILSpy", "token_count": 2195 }
202
// // ConstructorDeclaration.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 ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.CSharp.Syntax { public class ConstructorDeclaration : EntityDeclaration { public static readonly Role<ConstructorInitializer> InitializerRole = new Role<ConstructorInitializer>("Initializer", ConstructorInitializer.Null); public override SymbolKind SymbolKind { get { return SymbolKind.Constructor; } } 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 ColonToken { get { return GetChildByRole(Roles.Colon); } } public ConstructorInitializer Initializer { get { return GetChildByRole(InitializerRole); } set { SetChildByRole(InitializerRole, value); } } public BlockStatement Body { get { return GetChildByRole(Roles.Body); } set { SetChildByRole(Roles.Body, value); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitConstructorDeclaration(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitConstructorDeclaration(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitConstructorDeclaration(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { ConstructorDeclaration o = other as ConstructorDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.Parameters.DoMatch(o.Parameters, match) && this.Initializer.DoMatch(o.Initializer, match) && this.Body.DoMatch(o.Body, match); } } public enum ConstructorInitializerType { Any, Base, This } public class ConstructorInitializer : AstNode { public static readonly TokenRole BaseKeywordRole = new TokenRole("base"); public static readonly TokenRole ThisKeywordRole = new TokenRole("this"); public static readonly new ConstructorInitializer Null = new NullConstructorInitializer(); class NullConstructorInitializer : ConstructorInitializer { public override NodeType NodeType { get { return NodeType.Unknown; } } public override bool IsNull { get { return true; } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitNullNode(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitNullNode(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitNullNode(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { return other == null || other.IsNull; } } public override NodeType NodeType { get { return NodeType.Unknown; } } public ConstructorInitializerType ConstructorInitializerType { get; set; } public CSharpTokenNode Keyword { get { if (ConstructorInitializerType == ConstructorInitializerType.Base) return GetChildByRole(BaseKeywordRole); else return GetChildByRole(ThisKeywordRole); } } public CSharpTokenNode LParToken { get { return GetChildByRole(Roles.LPar); } } public AstNodeCollection<Expression> Arguments { get { return GetChildrenByRole(Roles.Argument); } } public CSharpTokenNode RParToken { get { return GetChildByRole(Roles.RPar); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitConstructorInitializer(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitConstructorInitializer(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitConstructorInitializer(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { ConstructorInitializer o = other as ConstructorInitializer; return o != null && !o.IsNull && (this.ConstructorInitializerType == ConstructorInitializerType.Any || this.ConstructorInitializerType == o.ConstructorInitializerType) && this.Arguments.DoMatch(o.Arguments, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs", "repo_id": "ILSpy", "token_count": 1866 }
203
// 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 ICSharpCode.Decompiler.CSharp.Syntax; namespace ICSharpCode.Decompiler.CSharp.Transforms { /// <summary> /// Add checked/unchecked blocks. /// </summary> public class AddCheckedBlocks : IAstTransform { #region Annotation sealed class CheckedUncheckedAnnotation { /// <summary> /// true=checked, false=unchecked /// </summary> public bool IsChecked; /// <summary> /// Require an explicit unchecked block (can't rely on the project-level unchecked context) /// </summary> public bool IsExplicit; } public static readonly object CheckedAnnotation = new CheckedUncheckedAnnotation { IsChecked = true }; public static readonly object UncheckedAnnotation = new CheckedUncheckedAnnotation { IsChecked = false }; public static readonly object ExplicitUncheckedAnnotation = new CheckedUncheckedAnnotation { IsChecked = false, IsExplicit = true }; #endregion /* We treat placing checked/unchecked blocks as an optimization problem, with the following goals: 1. Use minimum number of checked blocks+expressions 2. Prefer checked expressions over checked blocks 3. Make the scope of checked expressions as small as possible 4. Open checked blocks as late as possible, and close checked blocks as late as possible (where goal 1 has the highest priority) Goal 4a (open checked blocks as late as possible) is necessary so that we don't move variable declarations into checked blocks, as the variable might still be used after the checked block. (this could cause DeclareVariables to omit the variable declaration, producing incorrect code) Goal 4b (close checked blocks as late as possible) makes the code look nicer in this case: checked { int c = a + b; int r = a + c; return r; } If the checked block was closed as early as possible, the variable r would have to be declared outside (this would work, but look badly) */ #region struct Cost struct Cost { // highest possible cost so that the Blocks+Expressions addition doesn't overflow public static readonly Cost Infinite = new Cost(0x3fffffff, 0x3fffffff); public readonly int Blocks; public readonly int Expressions; public Cost(int blocks, int expressions) { this.Blocks = blocks; this.Expressions = expressions; } public static bool operator <(Cost a, Cost b) { return a.Blocks + a.Expressions < b.Blocks + b.Expressions || a.Blocks + a.Expressions == b.Blocks + b.Expressions && a.Blocks < b.Blocks; } public static bool operator >(Cost a, Cost b) { return a.Blocks + a.Expressions > b.Blocks + b.Expressions || a.Blocks + a.Expressions == b.Blocks + b.Expressions && a.Blocks > b.Blocks; } public static bool operator <=(Cost a, Cost b) { return a.Blocks + a.Expressions < b.Blocks + b.Expressions || a.Blocks + a.Expressions == b.Blocks + b.Expressions && a.Blocks <= b.Blocks; } public static bool operator >=(Cost a, Cost b) { return a.Blocks + a.Expressions > b.Blocks + b.Expressions || a.Blocks + a.Expressions == b.Blocks + b.Expressions && a.Blocks >= b.Blocks; } public static Cost operator +(Cost a, Cost b) { return new Cost(a.Blocks + b.Blocks, a.Expressions + b.Expressions); } public override string ToString() { return string.Format("[{0} + {1}]", Blocks, Expressions); } /// <summary> /// Gets the new cost if an expression with this cost is wrapped in a checked/unchecked expression. /// </summary> internal Cost WrapInCheckedExpr() { if (Expressions == 0) { return new Cost(Blocks, 1); } else { // hack: penalize multiple layers of nested expressions // This doesn't really fit into the original idea of minimizing the number of block+expressions; // but tends to produce better-looking results due to less nesting. return new Cost(Blocks, Expressions + 2); } } } #endregion #region class InsertedNode /// <summary> /// Holds the blocks and expressions that should be inserted /// </summary> abstract class InsertedNode { public static InsertedNode operator +(InsertedNode a, InsertedNode b) { if (a == null) return b; if (b == null) return a; return new InsertedNodeList(a, b); } public abstract void Insert(); } class InsertedNodeList : InsertedNode { readonly InsertedNode child1, child2; public InsertedNodeList(AddCheckedBlocks.InsertedNode child1, AddCheckedBlocks.InsertedNode child2) { this.child1 = child1; this.child2 = child2; } public override void Insert() { child1.Insert(); child2.Insert(); } } class InsertedExpression : InsertedNode { readonly Expression expression; readonly bool isChecked; public InsertedExpression(Expression expression, bool isChecked) { this.expression = expression; this.isChecked = isChecked; } public override void Insert() { if (isChecked) expression.ReplaceWith(e => new CheckedExpression { Expression = e }); else expression.ReplaceWith(e => new UncheckedExpression { Expression = e }); } } class InsertedBlock : InsertedNode { readonly Statement firstStatement; // inclusive readonly Statement lastStatement; // exclusive readonly bool isChecked; public InsertedBlock(Statement firstStatement, Statement lastStatement, bool isChecked) { this.firstStatement = firstStatement; this.lastStatement = lastStatement; this.isChecked = isChecked; } public override void Insert() { BlockStatement newBlock = new BlockStatement(); // Move all statements except for the first Statement next; for (Statement stmt = firstStatement.GetNextStatement(); stmt != lastStatement; stmt = next) { next = stmt.GetNextStatement(); newBlock.Add(stmt.Detach()); } // Replace the first statement with the new (un)checked block if (isChecked) firstStatement.ReplaceWith(new CheckedStatement { Body = newBlock }); else firstStatement.ReplaceWith(new UncheckedStatement { Body = newBlock }); // now also move the first node into the new block newBlock.Statements.InsertAfter(null, firstStatement); } } #endregion #region class Result /// <summary> /// Holds the result of an insertion operation. /// </summary> class Result { public Cost CostInCheckedContext; public InsertedNode NodesToInsertInCheckedContext; public Cost CostInUncheckedContext; public InsertedNode NodesToInsertInUncheckedContext; } #endregion public void Run(AstNode node, TransformContext context) { BlockStatement block = node as BlockStatement; if (block == null) { for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) { Run(child, context); } } else { Result r = GetResultFromBlock(block); if (r.NodesToInsertInUncheckedContext != null) r.NodesToInsertInUncheckedContext.Insert(); } } Result GetResultFromBlock(BlockStatement block) { // For a block, we are tracking 4 possibilities: // a) context is checked, no unchecked block open Cost costCheckedContext = new Cost(0, 0); InsertedNode nodesCheckedContext = null; // b) context is checked, an unchecked block is open Cost costCheckedContextUncheckedBlockOpen = Cost.Infinite; InsertedNode nodesCheckedContextUncheckedBlockOpen = null; Statement uncheckedBlockStart = null; // c) context is unchecked, no checked block open Cost costUncheckedContext = new Cost(0, 0); InsertedNode nodesUncheckedContext = null; // d) context is unchecked, a checked block is open Cost costUncheckedContextCheckedBlockOpen = Cost.Infinite; InsertedNode nodesUncheckedContextCheckedBlockOpen = null; Statement checkedBlockStart = null; Statement statement = block.Statements.FirstOrDefault(); while (true) { // Blocks can be closed 'for free'. We use '<=' so that blocks are closed as late as possible (goal 4b) if (costCheckedContextUncheckedBlockOpen <= costCheckedContext) { costCheckedContext = costCheckedContextUncheckedBlockOpen; nodesCheckedContext = nodesCheckedContextUncheckedBlockOpen + new InsertedBlock(uncheckedBlockStart, statement, false); } if (costUncheckedContextCheckedBlockOpen <= costUncheckedContext) { costUncheckedContext = costUncheckedContextCheckedBlockOpen; nodesUncheckedContext = nodesUncheckedContextCheckedBlockOpen + new InsertedBlock(checkedBlockStart, statement, true); } if (statement == null) break; // Now try opening blocks. We use '<=' so that blocks are opened as late as possible. (goal 4a) if (costCheckedContext + new Cost(1, 0) <= costCheckedContextUncheckedBlockOpen) { costCheckedContextUncheckedBlockOpen = costCheckedContext + new Cost(1, 0); nodesCheckedContextUncheckedBlockOpen = nodesCheckedContext; uncheckedBlockStart = statement; } if (costUncheckedContext + new Cost(1, 0) <= costUncheckedContextCheckedBlockOpen) { costUncheckedContextCheckedBlockOpen = costUncheckedContext + new Cost(1, 0); nodesUncheckedContextCheckedBlockOpen = nodesUncheckedContext; checkedBlockStart = statement; } // Now handle the statement Result stmtResult = GetResult(statement); costCheckedContext += stmtResult.CostInCheckedContext; nodesCheckedContext += stmtResult.NodesToInsertInCheckedContext; costCheckedContextUncheckedBlockOpen += stmtResult.CostInUncheckedContext; nodesCheckedContextUncheckedBlockOpen += stmtResult.NodesToInsertInUncheckedContext; costUncheckedContext += stmtResult.CostInUncheckedContext; nodesUncheckedContext += stmtResult.NodesToInsertInUncheckedContext; costUncheckedContextCheckedBlockOpen += stmtResult.CostInCheckedContext; nodesUncheckedContextCheckedBlockOpen += stmtResult.NodesToInsertInCheckedContext; if (statement is LabelStatement || statement is LocalFunctionDeclarationStatement) { // We can't move labels into blocks because that might cause goto-statements // to be unable to jump to the labels. // Also, we can't move local functions into blocks, because that might cause // them to become out of scope from the call-sites. costCheckedContextUncheckedBlockOpen = Cost.Infinite; costUncheckedContextCheckedBlockOpen = Cost.Infinite; } statement = statement.GetNextStatement(); } return new Result { CostInCheckedContext = costCheckedContext, NodesToInsertInCheckedContext = nodesCheckedContext, CostInUncheckedContext = costUncheckedContext, NodesToInsertInUncheckedContext = nodesUncheckedContext }; } Result GetResult(AstNode node) { if (node is BlockStatement) return GetResultFromBlock((BlockStatement)node); Result result = new Result(); for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) { Result childResult = GetResult(child); result.CostInCheckedContext += childResult.CostInCheckedContext; result.NodesToInsertInCheckedContext += childResult.NodesToInsertInCheckedContext; result.CostInUncheckedContext += childResult.CostInUncheckedContext; result.NodesToInsertInUncheckedContext += childResult.NodesToInsertInUncheckedContext; } Expression expr = node as Expression; if (expr != null) { CheckedUncheckedAnnotation annotation = expr.Annotation<CheckedUncheckedAnnotation>(); if (annotation != null) { if (annotation.IsExplicit) { // We don't yet support distinguishing CostInUncheckedContext vs. CostInExplicitUncheckedContext, // so we always force an unchecked() expression here. if (annotation.IsChecked) throw new NotImplementedException("explicit checked"); // should not be needed result.CostInCheckedContext = result.CostInUncheckedContext.WrapInCheckedExpr(); result.CostInUncheckedContext = result.CostInUncheckedContext.WrapInCheckedExpr(); result.NodesToInsertInUncheckedContext += new InsertedExpression(expr, annotation.IsChecked); result.NodesToInsertInCheckedContext = result.NodesToInsertInUncheckedContext; } else { // If the annotation requires this node to be in a specific context, add a huge cost to the other context // That huge cost gives us the option to ignore a required checked/unchecked expression when there wouldn't be any // solution otherwise. (e.g. "for (checked(M().x += 1); true; unchecked(M().x += 2)) {}") if (annotation.IsChecked) result.CostInUncheckedContext += new Cost(10000, 0); else result.CostInCheckedContext += new Cost(10000, 0); } } // Embed this node in an checked/unchecked expression: if (expr.Parent is ExpressionStatement) { // We cannot use checked/unchecked for top-level-expressions. } else if (expr.Role.IsValid(Expression.Null)) { // We use '<' so that expressions are introduced on the deepest level possible (goal 3) var costIfWrapWithChecked = result.CostInCheckedContext.WrapInCheckedExpr(); var costIfWrapWithUnchecked = result.CostInUncheckedContext.WrapInCheckedExpr(); if (costIfWrapWithChecked < result.CostInUncheckedContext) { result.CostInUncheckedContext = costIfWrapWithChecked; result.NodesToInsertInUncheckedContext = result.NodesToInsertInCheckedContext + new InsertedExpression(expr, true); } else if (costIfWrapWithUnchecked < result.CostInCheckedContext) { result.CostInCheckedContext = costIfWrapWithUnchecked; result.NodesToInsertInCheckedContext = result.NodesToInsertInUncheckedContext + new InsertedExpression(expr, false); } } } return result; } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs", "repo_id": "ILSpy", "token_count": 5117 }
204
// 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.Diagnostics; using System.Linq; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching; using ICSharpCode.Decompiler.Semantics; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.CSharp.Transforms { /// <summary> /// Finds the expanded form of using statements using pattern matching and replaces it with a UsingStatement. /// </summary> public sealed class PatternStatementTransform : ContextTrackingVisitor<AstNode>, IAstTransform { readonly DeclareVariables declareVariables = new DeclareVariables(); TransformContext context; public void Run(AstNode rootNode, TransformContext context) { if (this.context != null) throw new InvalidOperationException("Reentrancy in PatternStatementTransform.Run?"); try { this.context = context; base.Initialize(context); declareVariables.Analyze(rootNode); rootNode.AcceptVisitor(this); } finally { this.context = null; base.Uninitialize(); declareVariables.ClearAnalysisResults(); } } #region Visitor Overrides protected override AstNode VisitChildren(AstNode node) { // Go through the children, and keep visiting a node as long as it changes. // Because some transforms delete/replace nodes before and after the node being transformed, we rely // on the transform's return value to know where we need to keep iterating. for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) { AstNode oldChild; do { oldChild = child; child = child.AcceptVisitor(this); Debug.Assert(child != null && child.Parent == node); } while (child != oldChild); } return node; } public override AstNode VisitExpressionStatement(ExpressionStatement expressionStatement) { AstNode result = TransformForeachOnMultiDimArray(expressionStatement); if (result != null) return result; result = TransformFor(expressionStatement); if (result != null) return result; return base.VisitExpressionStatement(expressionStatement); } public override AstNode VisitForStatement(ForStatement forStatement) { AstNode result = TransformForeachOnArray(forStatement); if (result != null) return result; return base.VisitForStatement(forStatement); } public override AstNode VisitIfElseStatement(IfElseStatement ifElseStatement) { AstNode simplifiedIfElse = SimplifyCascadingIfElseStatements(ifElseStatement); if (simplifiedIfElse != null) return simplifiedIfElse; return base.VisitIfElseStatement(ifElseStatement); } public override AstNode VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) { if (context.Settings.AutomaticProperties && (!propertyDeclaration.Setter.IsNull || context.Settings.GetterOnlyAutomaticProperties)) { AstNode result = TransformAutomaticProperty(propertyDeclaration); if (result != null) return result; } return base.VisitPropertyDeclaration(propertyDeclaration); } public override AstNode VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration) { // first apply transforms to the accessor bodies base.VisitCustomEventDeclaration(eventDeclaration); if (context.Settings.AutomaticEvents) { AstNode result = TransformAutomaticEvents(eventDeclaration); if (result != null) return result; } return eventDeclaration; } public override AstNode VisitMethodDeclaration(MethodDeclaration methodDeclaration) { return TransformDestructor(methodDeclaration) ?? base.VisitMethodDeclaration(methodDeclaration); } public override AstNode VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration) { return TransformDestructorBody(destructorDeclaration) ?? base.VisitDestructorDeclaration(destructorDeclaration); } public override AstNode VisitTryCatchStatement(TryCatchStatement tryCatchStatement) { return TransformTryCatchFinally(tryCatchStatement) ?? base.VisitTryCatchStatement(tryCatchStatement); } #endregion /// <summary> /// $variable = $initializer; /// </summary> static readonly AstNode variableAssignPattern = new ExpressionStatement( new AssignmentExpression( new NamedNode("variable", new IdentifierExpression(Pattern.AnyString)), new AnyNode("initializer") )); #region for static readonly WhileStatement forPattern = new WhileStatement { Condition = new BinaryOperatorExpression { Left = new NamedNode("ident", new IdentifierExpression(Pattern.AnyString)), Operator = BinaryOperatorType.Any, Right = new AnyNode("endExpr") }, EmbeddedStatement = new BlockStatement { Statements = { new Repeat(new AnyNode("statement")), new NamedNode( "iterator", new ExpressionStatement( new AssignmentExpression { Left = new Backreference("ident"), Operator = AssignmentOperatorType.Any, Right = new AnyNode() })) } } }; public ForStatement TransformFor(ExpressionStatement node) { if (!context.Settings.ForStatement) return null; Match m1 = variableAssignPattern.Match(node); if (!m1.Success) return null; var variable = m1.Get<IdentifierExpression>("variable").Single().GetILVariable(); AstNode next = node.NextSibling; if (next is ForStatement forStatement && ForStatementUsesVariable(forStatement, variable)) { node.Remove(); next.InsertChildAfter(null, node, ForStatement.InitializerRole); return (ForStatement)next; } Match m3 = forPattern.Match(next); if (!m3.Success) return null; // ensure the variable in the for pattern is the same as in the declaration if (variable != m3.Get<IdentifierExpression>("ident").Single().GetILVariable()) return null; WhileStatement loop = (WhileStatement)next; // Cannot convert to for loop, if any variable that is used in the "iterator" part of the pattern, // will be declared in the body of the while-loop. var iteratorStatement = m3.Get<Statement>("iterator").Single(); if (IteratorVariablesDeclaredInsideLoopBody(iteratorStatement)) return null; // Cannot convert to for loop, because that would change the semantics of the program. // continue in while jumps to the condition block. // Whereas continue in for jumps to the increment block. if (loop.DescendantNodes(DescendIntoStatement).OfType<Statement>().Any(s => s is ContinueStatement)) return null; node.Remove(); BlockStatement newBody = new BlockStatement(); foreach (Statement stmt in m3.Get<Statement>("statement")) newBody.Add(stmt.Detach()); forStatement = new ForStatement(); forStatement.CopyAnnotationsFrom(loop); forStatement.Initializers.Add(node); forStatement.Condition = loop.Condition.Detach(); forStatement.Iterators.Add(iteratorStatement.Detach()); forStatement.EmbeddedStatement = newBody; loop.ReplaceWith(forStatement); return forStatement; } bool DescendIntoStatement(AstNode node) { if (node is Expression || node is ExpressionStatement) return false; if (node is WhileStatement || node is ForeachStatement || node is DoWhileStatement || node is ForStatement) return false; return true; } bool ForStatementUsesVariable(ForStatement statement, IL.ILVariable variable) { if (statement.Condition.DescendantsAndSelf.OfType<IdentifierExpression>().Any(ie => ie.GetILVariable() == variable)) return true; if (statement.Iterators.Any(i => i.DescendantsAndSelf.OfType<IdentifierExpression>().Any(ie => ie.GetILVariable() == variable))) return true; return false; } bool IteratorVariablesDeclaredInsideLoopBody(Statement iteratorStatement) { foreach (var id in iteratorStatement.DescendantsAndSelf.OfType<IdentifierExpression>()) { var v = id.GetILVariable(); if (v == null || !DeclareVariables.VariableNeedsDeclaration(v.Kind)) continue; if (declareVariables.GetDeclarationPoint(v).Parent == iteratorStatement.Parent) return true; } return false; } #endregion #region foreach static readonly ForStatement forOnArrayPattern = new ForStatement { Initializers = { new ExpressionStatement( new AssignmentExpression( new NamedNode("indexVariable", new IdentifierExpression(Pattern.AnyString)), new PrimitiveExpression(0) )) }, Condition = new BinaryOperatorExpression( new IdentifierExpressionBackreference("indexVariable"), BinaryOperatorType.LessThan, new MemberReferenceExpression(new NamedNode("arrayVariable", new IdentifierExpression(Pattern.AnyString)), "Length") ), Iterators = { new ExpressionStatement( new AssignmentExpression( new IdentifierExpressionBackreference("indexVariable"), new BinaryOperatorExpression(new IdentifierExpressionBackreference("indexVariable"), BinaryOperatorType.Add, new PrimitiveExpression(1)) )) }, EmbeddedStatement = new BlockStatement { Statements = { new ExpressionStatement(new AssignmentExpression( new NamedNode("itemVariable", new IdentifierExpression(Pattern.AnyString)), new IndexerExpression(new IdentifierExpressionBackreference("arrayVariable"), new IdentifierExpressionBackreference("indexVariable")) )), new Repeat(new AnyNode("statements")) } } }; bool VariableCanBeUsedAsForeachLocal(IL.ILVariable itemVar, Statement loop) { if (itemVar == null || !(itemVar.Kind == IL.VariableKind.Local || itemVar.Kind == IL.VariableKind.StackSlot)) { // only locals/temporaries can be converted into foreach loop variable return false; } var blockContainer = loop.Annotation<IL.BlockContainer>(); if (!itemVar.IsSingleDefinition) { // foreach variable cannot be assigned to. // As a special case, we accept taking the address for a method call, // but only if the call is the only use, so that any mutation by the call // cannot be observed. if (!AddressUsedForSingleCall(itemVar, blockContainer)) { return false; } } if (itemVar.CaptureScope != null && itemVar.CaptureScope != blockContainer) { // captured variables cannot be declared in the loop unless the loop is their capture scope return false; } AstNode declPoint = declareVariables.GetDeclarationPoint(itemVar); return declPoint.Ancestors.Contains(loop) && !declareVariables.WasMerged(itemVar); } static bool AddressUsedForSingleCall(IL.ILVariable v, IL.BlockContainer loop) { if (v.StoreCount == 1 && v.AddressCount == 1 && v.LoadCount == 0 && v.Type.IsReferenceType == false) { if (v.AddressInstructions[0].Parent is IL.Call call && v.AddressInstructions[0].ChildIndex == 0 && !call.Method.IsStatic) { // used as this pointer for a method call // this is OK iff the call is not within a nested loop for (var node = call.Parent; node != null; node = node.Parent) { if (node == loop) return true; else if (node is IL.BlockContainer) break; } } } return false; } Statement TransformForeachOnArray(ForStatement forStatement) { if (!context.Settings.ForEachStatement) return null; Match m = forOnArrayPattern.Match(forStatement); if (!m.Success) return null; var itemVariable = m.Get<IdentifierExpression>("itemVariable").Single().GetILVariable(); var indexVariable = m.Get<IdentifierExpression>("indexVariable").Single().GetILVariable(); var arrayVariable = m.Get<IdentifierExpression>("arrayVariable").Single().GetILVariable(); if (itemVariable == null || indexVariable == null || arrayVariable == null) return null; if (arrayVariable.Type.Kind != TypeKind.Array && !arrayVariable.Type.IsKnownType(KnownTypeCode.String)) return null; if (!VariableCanBeUsedAsForeachLocal(itemVariable, forStatement)) return null; if (indexVariable.StoreCount != 2 || indexVariable.LoadCount != 3 || indexVariable.AddressCount != 0) return null; var body = new BlockStatement(); foreach (var statement in m.Get<Statement>("statements")) body.Statements.Add(statement.Detach()); var foreachStmt = new ForeachStatement { VariableType = context.Settings.AnonymousTypes && itemVariable.Type.ContainsAnonymousType() ? new SimpleType("var") : context.TypeSystemAstBuilder.ConvertType(itemVariable.Type), VariableDesignation = new SingleVariableDesignation { Identifier = itemVariable.Name }, InExpression = m.Get<IdentifierExpression>("arrayVariable").Single().Detach(), EmbeddedStatement = body }; foreachStmt.CopyAnnotationsFrom(forStatement); itemVariable.Kind = IL.VariableKind.ForeachLocal; // Add the variable annotation for highlighting (TokenTextWriter expects it directly on the ForeachStatement). foreachStmt.VariableDesignation.AddAnnotation(new ILVariableResolveResult(itemVariable, itemVariable.Type)); // TODO : add ForeachAnnotation forStatement.ReplaceWith(foreachStmt); return foreachStmt; } static readonly ForStatement forOnArrayMultiDimPattern = new ForStatement { Initializers = { }, Condition = new BinaryOperatorExpression( new NamedNode("indexVariable", new IdentifierExpression(Pattern.AnyString)), BinaryOperatorType.LessThanOrEqual, new NamedNode("upperBoundVariable", new IdentifierExpression(Pattern.AnyString)) ), Iterators = { new ExpressionStatement( new AssignmentExpression( new IdentifierExpressionBackreference("indexVariable"), new BinaryOperatorExpression(new IdentifierExpressionBackreference("indexVariable"), BinaryOperatorType.Add, new PrimitiveExpression(1)) )) }, EmbeddedStatement = new BlockStatement { Statements = { new AnyNode("lowerBoundAssign"), new Repeat(new AnyNode("statements")) } } }; /// <summary> /// $variable = $collection.GetUpperBound($index); /// </summary> static readonly AstNode variableAssignUpperBoundPattern = new ExpressionStatement( new AssignmentExpression( new NamedNode("variable", new IdentifierExpression(Pattern.AnyString)), new InvocationExpression( new MemberReferenceExpression( new NamedNode("collection", new IdentifierExpression(Pattern.AnyString)), "GetUpperBound" ), new NamedNode("index", new PrimitiveExpression(PrimitiveExpression.AnyValue)) ))); /// <summary> /// $variable = $collection.GetLowerBound($index); /// </summary> static readonly ExpressionStatement variableAssignLowerBoundPattern = new ExpressionStatement( new AssignmentExpression( new NamedNode("variable", new IdentifierExpression(Pattern.AnyString)), new InvocationExpression( new MemberReferenceExpression( new NamedNode("collection", new IdentifierExpression(Pattern.AnyString)), "GetLowerBound" ), new NamedNode("index", new PrimitiveExpression(PrimitiveExpression.AnyValue)) ))); /// <summary> /// $variable = $collection[$index1, $index2, ...]; /// </summary> static readonly ExpressionStatement foreachVariableOnMultArrayAssignPattern = new ExpressionStatement( new AssignmentExpression( new NamedNode("variable", new IdentifierExpression(Pattern.AnyString)), new IndexerExpression( new NamedNode("collection", new IdentifierExpression(Pattern.AnyString)), new Repeat(new NamedNode("index", new IdentifierExpression(Pattern.AnyString)) ) ))); bool MatchLowerBound(int indexNum, out IL.ILVariable index, IL.ILVariable collection, Statement statement) { index = null; var m = variableAssignLowerBoundPattern.Match(statement); if (!m.Success) return false; if (!int.TryParse(m.Get<PrimitiveExpression>("index").Single().Value.ToString(), out int i) || indexNum != i) return false; index = m.Get<IdentifierExpression>("variable").Single().GetILVariable(); return m.Get<IdentifierExpression>("collection").Single().GetILVariable() == collection; } bool MatchForeachOnMultiDimArray(IL.ILVariable[] upperBounds, IL.ILVariable collection, Statement firstInitializerStatement, out IdentifierExpression foreachVariable, out IList<Statement> statements, out IL.ILVariable[] lowerBounds) { int i = 0; foreachVariable = null; statements = null; lowerBounds = new IL.ILVariable[upperBounds.Length]; Statement stmt = firstInitializerStatement; Match m = default(Match); while (i < upperBounds.Length && MatchLowerBound(i, out IL.ILVariable indexVariable, collection, stmt)) { m = forOnArrayMultiDimPattern.Match(stmt.GetNextStatement()); if (!m.Success) return false; var upperBound = m.Get<IdentifierExpression>("upperBoundVariable").Single().GetILVariable(); if (upperBounds[i] != upperBound) return false; stmt = m.Get<Statement>("lowerBoundAssign").Single(); lowerBounds[i] = indexVariable; i++; } if (collection.Type.Kind != TypeKind.Array) return false; var m2 = foreachVariableOnMultArrayAssignPattern.Match(stmt); if (!m2.Success) return false; var collection2 = m2.Get<IdentifierExpression>("collection").Single().GetILVariable(); if (collection2 != collection) return false; foreachVariable = m2.Get<IdentifierExpression>("variable").Single(); statements = m.Get<Statement>("statements").ToList(); return true; } Statement TransformForeachOnMultiDimArray(ExpressionStatement expressionStatement) { if (!context.Settings.ForEachStatement) return null; Match m; Statement stmt = expressionStatement; IL.ILVariable collection = null; IL.ILVariable[] upperBounds = null; List<Statement> statementsToDelete = new List<Statement>(); int i = 0; // first we look for all the upper bound initializations do { m = variableAssignUpperBoundPattern.Match(stmt); if (!m.Success) break; if (upperBounds == null) { collection = m.Get<IdentifierExpression>("collection").Single().GetILVariable(); if (!(collection?.Type is Decompiler.TypeSystem.ArrayType arrayType)) break; upperBounds = new IL.ILVariable[arrayType.Dimensions]; } else { statementsToDelete.Add(stmt); } var nextCollection = m.Get<IdentifierExpression>("collection").Single().GetILVariable(); if (nextCollection != collection) break; if (!int.TryParse(m.Get<PrimitiveExpression>("index").Single().Value?.ToString() ?? "", out int index) || index != i) break; upperBounds[i] = m.Get<IdentifierExpression>("variable").Single().GetILVariable(); stmt = stmt.GetNextStatement(); i++; } while (stmt != null && i < upperBounds.Length); if (upperBounds?.LastOrDefault() == null || collection == null) return null; if (!MatchForeachOnMultiDimArray(upperBounds, collection, stmt, out var foreachVariable, out var statements, out var lowerBounds)) return null; statementsToDelete.Add(stmt); statementsToDelete.Add(stmt.GetNextStatement()); var itemVariable = foreachVariable.GetILVariable(); if (itemVariable == null || !itemVariable.IsSingleDefinition || (itemVariable.Kind != IL.VariableKind.Local && itemVariable.Kind != IL.VariableKind.StackSlot) || !upperBounds.All(ub => ub.IsSingleDefinition && ub.LoadCount == 1) || !lowerBounds.All(lb => lb.StoreCount == 2 && lb.LoadCount == 3 && lb.AddressCount == 0)) return null; var body = new BlockStatement(); foreach (var statement in statements) body.Statements.Add(statement.Detach()); var foreachStmt = new ForeachStatement { VariableType = context.Settings.AnonymousTypes && itemVariable.Type.ContainsAnonymousType() ? new SimpleType("var") : context.TypeSystemAstBuilder.ConvertType(itemVariable.Type), VariableDesignation = new SingleVariableDesignation { Identifier = itemVariable.Name }, InExpression = m.Get<IdentifierExpression>("collection").Single().Detach(), EmbeddedStatement = body }; foreach (var statement in statementsToDelete) statement.Detach(); //foreachStmt.CopyAnnotationsFrom(forStatement); itemVariable.Kind = IL.VariableKind.ForeachLocal; // Add the variable annotation for highlighting (TokenTextWriter expects it directly on the ForeachStatement). foreachStmt.VariableDesignation.AddAnnotation(new ILVariableResolveResult(itemVariable, itemVariable.Type)); // TODO : add ForeachAnnotation expressionStatement.ReplaceWith(foreachStmt); return foreachStmt; } #endregion #region Automatic Properties static readonly PropertyDeclaration automaticPropertyPattern = new PropertyDeclaration { Attributes = { new Repeat(new AnyNode()) }, Modifiers = Modifiers.Any, ReturnType = new AnyNode(), PrivateImplementationType = new OptionalNode(new AnyNode()), Name = Pattern.AnyString, Getter = new Accessor { Attributes = { new Repeat(new AnyNode()) }, Modifiers = Modifiers.Any, Body = new BlockStatement { new ReturnStatement { Expression = new AnyNode("fieldReference") } } }, Setter = new Accessor { Attributes = { new Repeat(new AnyNode()) }, Modifiers = Modifiers.Any, Body = new BlockStatement { new AssignmentExpression { Left = new Backreference("fieldReference"), Right = new IdentifierExpression("value") } } } }; static readonly PropertyDeclaration automaticReadonlyPropertyPattern = new PropertyDeclaration { Attributes = { new Repeat(new AnyNode()) }, Modifiers = Modifiers.Any, ReturnType = new AnyNode(), PrivateImplementationType = new OptionalNode(new AnyNode()), Name = Pattern.AnyString, Getter = new Accessor { Attributes = { new Repeat(new AnyNode()) }, Modifiers = Modifiers.Any, Body = new BlockStatement { new ReturnStatement { Expression = new AnyNode("fieldReference") } } } }; bool CanTransformToAutomaticProperty(IProperty property, bool accessorsMustBeCompilerGenerated) { if (!property.CanGet) return false; if (accessorsMustBeCompilerGenerated && !property.Getter.IsCompilerGenerated()) return false; if (property.Setter is IMethod setter) { if (accessorsMustBeCompilerGenerated && !setter.IsCompilerGenerated()) return false; if (setter.HasReadonlyModifier()) return false; } return true; } PropertyDeclaration TransformAutomaticProperty(PropertyDeclaration propertyDeclaration) { IProperty property = propertyDeclaration.GetSymbol() as IProperty; if (!CanTransformToAutomaticProperty(property, !property.DeclaringTypeDefinition.Fields.Any(f => f.Name == "_" + property.Name && f.IsCompilerGenerated()))) return null; IField field = null; Match m = automaticPropertyPattern.Match(propertyDeclaration); if (m.Success) { field = m.Get<AstNode>("fieldReference").Single().GetSymbol() as IField; } else { Match m2 = automaticReadonlyPropertyPattern.Match(propertyDeclaration); if (m2.Success) { field = m2.Get<AstNode>("fieldReference").Single().GetSymbol() as IField; } } if (field == null || !NameCouldBeBackingFieldOfAutomaticProperty(field.Name, out _)) return null; if (propertyDeclaration.Setter.HasModifier(Modifiers.Readonly) || (propertyDeclaration.HasModifier(Modifiers.Readonly) && !propertyDeclaration.Setter.IsNull)) return null; if (field.IsCompilerGenerated() && field.DeclaringTypeDefinition == property.DeclaringTypeDefinition) { RemoveCompilerGeneratedAttribute(propertyDeclaration.Getter.Attributes); RemoveCompilerGeneratedAttribute(propertyDeclaration.Setter.Attributes); propertyDeclaration.Getter.Body = null; propertyDeclaration.Setter.Body = null; propertyDeclaration.Modifiers &= ~Modifiers.Readonly; propertyDeclaration.Getter.Modifiers &= ~Modifiers.Readonly; var fieldDecl = propertyDeclaration.Parent?.Children.OfType<FieldDeclaration>() .FirstOrDefault(fd => field.Equals(fd.GetSymbol())); if (fieldDecl != null) { fieldDecl.Remove(); // Add C# 7.3 attributes on backing field: CSharpDecompiler.RemoveAttribute(fieldDecl, KnownAttribute.CompilerGenerated); CSharpDecompiler.RemoveAttribute(fieldDecl, KnownAttribute.DebuggerBrowsable); foreach (var section in fieldDecl.Attributes) { section.AttributeTarget = "field"; propertyDeclaration.Attributes.Add(section.Detach()); } } } // Since the property instance is not changed, we can continue in the visitor as usual, so return null return null; } void RemoveCompilerGeneratedAttribute(AstNodeCollection<AttributeSection> attributeSections) { RemoveCompilerGeneratedAttribute(attributeSections, "System.Runtime.CompilerServices.CompilerGeneratedAttribute"); } void RemoveCompilerGeneratedAttribute(AstNodeCollection<AttributeSection> attributeSections, params string[] attributesToRemove) { foreach (AttributeSection section in attributeSections) { foreach (var attr in section.Attributes) { var tr = attr.Type.GetSymbol() as IType; if (tr != null && attributesToRemove.Contains(tr.FullName)) { attr.Remove(); } } if (section.Attributes.Count == 0) section.Remove(); } } #endregion public override AstNode VisitIdentifier(Identifier identifier) { if (context.Settings.AutomaticProperties) { var newIdentifier = ReplaceBackingFieldUsage(identifier); if (newIdentifier != null) { identifier.ReplaceWith(newIdentifier); return newIdentifier; } } if (context.Settings.AutomaticEvents) { var newIdentifier = ReplaceEventFieldAnnotation(identifier); if (newIdentifier != null) return newIdentifier; } return base.VisitIdentifier(identifier); } internal static bool IsBackingFieldOfAutomaticProperty(IField field, out IProperty property) { property = null; if (!NameCouldBeBackingFieldOfAutomaticProperty(field.Name, out string propertyName)) return false; if (!field.IsCompilerGenerated()) return false; property = field.DeclaringTypeDefinition .GetProperties(p => p.Name == propertyName, GetMemberOptions.IgnoreInheritedMembers) .FirstOrDefault(); return property != null; } /// <summary> /// This matches the following patterns /// <list type="bullet"> /// <item>&lt;Property&gt;k__BackingField (used by C#)</item> /// <item>_Property (used by VB)</item> /// </list> /// </summary> static readonly System.Text.RegularExpressions.Regex automaticPropertyBackingFieldNameRegex = new System.Text.RegularExpressions.Regex(@"^(<(?<name>.+)>k__BackingField|_(?<name>.+))$"); static bool NameCouldBeBackingFieldOfAutomaticProperty(string name, out string propertyName) { propertyName = null; var m = automaticPropertyBackingFieldNameRegex.Match(name); if (!m.Success) return false; propertyName = m.Groups["name"].Value; return true; } Identifier ReplaceBackingFieldUsage(Identifier identifier) { if (NameCouldBeBackingFieldOfAutomaticProperty(identifier.Name, out _)) { var parent = identifier.Parent; var mrr = parent.Annotation<MemberResolveResult>(); var field = mrr?.Member as IField; if (field != null && IsBackingFieldOfAutomaticProperty(field, out var property) && CanTransformToAutomaticProperty(property, !(field.IsCompilerGenerated() && field.Name == "_" + property.Name)) && currentMethod.AccessorOwner != property) { if (!property.CanSet && !context.Settings.GetterOnlyAutomaticProperties) return null; parent.RemoveAnnotations<MemberResolveResult>(); parent.AddAnnotation(new MemberResolveResult(mrr.TargetResult, property)); return Identifier.Create(property.Name); } } return null; } Identifier ReplaceEventFieldAnnotation(Identifier identifier) { var parent = identifier.Parent; var mrr = parent.Annotation<MemberResolveResult>(); var field = mrr?.Member as IField; if (field == null) return null; foreach (var ev in field.DeclaringType.GetEvents(null, GetMemberOptions.IgnoreInheritedMembers)) { if (CSharpDecompiler.IsEventBackingFieldName(field.Name, ev.Name, out int suffixLength) && currentMethod.AccessorOwner != ev) { parent.RemoveAnnotations<MemberResolveResult>(); parent.AddAnnotation(new MemberResolveResult(mrr.TargetResult, ev)); if (suffixLength != 0) identifier.Name = identifier.Name.Substring(0, identifier.Name.Length - suffixLength); return identifier; } } return null; } #region Automatic Events static readonly Expression fieldReferencePattern = new Choice { new IdentifierExpression(Pattern.AnyString), new MemberReferenceExpression { Target = new Choice { new ThisReferenceExpression(), new TypeReferenceExpression { Type = new AnyNode() } }, MemberName = Pattern.AnyString } }; static readonly Accessor automaticEventPatternV2 = new Accessor { Attributes = { new Repeat(new AnyNode()) }, Body = new BlockStatement { new AssignmentExpression { Left = new NamedNode("field", fieldReferencePattern), Operator = AssignmentOperatorType.Assign, Right = new CastExpression( new AnyNode("type"), new InvocationExpression(new AnyNode("delegateCombine").ToExpression(), new Backreference("field"), new IdentifierExpression("value")) ) }, } }; static readonly Accessor automaticEventPatternV4 = new Accessor { Attributes = { new Repeat(new AnyNode()) }, Body = new BlockStatement { new AssignmentExpression { Left = new NamedNode("var1", new IdentifierExpression(Pattern.AnyString)), Operator = AssignmentOperatorType.Assign, Right = new NamedNode("field", fieldReferencePattern) }, new DoWhileStatement { EmbeddedStatement = new BlockStatement { new AssignmentExpression(new NamedNode("var2", new IdentifierExpression(Pattern.AnyString)), new IdentifierExpressionBackreference("var1")), new AssignmentExpression { Left = new NamedNode("var3", new IdentifierExpression(Pattern.AnyString)), Operator = AssignmentOperatorType.Assign, Right = new CastExpression(new AnyNode("type"), new InvocationExpression(new AnyNode("delegateCombine").ToExpression(), new IdentifierExpressionBackreference("var2"), new IdentifierExpression("value"))) }, new AssignmentExpression { Left = new IdentifierExpressionBackreference("var1"), Right = new InvocationExpression(new MemberReferenceExpression(new TypeReferenceExpression(new TypePattern(typeof(System.Threading.Interlocked)).ToType()), "CompareExchange"), new Expression[] { // arguments new DirectionExpression { FieldDirection = FieldDirection.Ref, Expression = new Backreference("field") }, new IdentifierExpressionBackreference("var3"), new IdentifierExpressionBackreference("var2") } )} }, Condition = new BinaryOperatorExpression { Left = new CastExpression(new TypePattern(typeof(object)), new IdentifierExpressionBackreference("var1")), Operator = BinaryOperatorType.InEquality, Right = new IdentifierExpressionBackreference("var2") }, } } }; static readonly Accessor automaticEventPatternV4AggressivelyInlined = new Accessor { Attributes = { new Repeat(new AnyNode()) }, Body = new BlockStatement { new AssignmentExpression { Left = new NamedNode("var1", new IdentifierExpression(Pattern.AnyString)), Operator = AssignmentOperatorType.Assign, Right = new NamedNode("field", fieldReferencePattern) }, new DoWhileStatement { EmbeddedStatement = new BlockStatement { new AssignmentExpression(new NamedNode("var2", new IdentifierExpression(Pattern.AnyString)), new IdentifierExpressionBackreference("var1")), new AssignmentExpression { Left = new IdentifierExpressionBackreference("var1"), Right = new InvocationExpression(new MemberReferenceExpression(new TypeReferenceExpression(new TypePattern(typeof(System.Threading.Interlocked)).ToType()), "CompareExchange"), new Expression[] { // arguments new NamedArgumentExpression("value", new CastExpression(new AnyNode("type"), new InvocationExpression(new AnyNode("delegateCombine").ToExpression(), new IdentifierExpressionBackreference("var2"), new IdentifierExpression("value")))), new NamedArgumentExpression("location1", new DirectionExpression { FieldDirection = FieldDirection.Ref, Expression = new Backreference("field") }), new NamedArgumentExpression("comparand", new IdentifierExpressionBackreference("var2")) } )} }, Condition = new BinaryOperatorExpression { Left = new CastExpression(new TypePattern(typeof(object)), new IdentifierExpressionBackreference("var1")), Operator = BinaryOperatorType.InEquality, Right = new IdentifierExpressionBackreference("var2") }, } } }; static readonly Accessor automaticEventPatternV4MCS = new Accessor { Attributes = { new Repeat(new AnyNode()) }, Body = new BlockStatement { new AssignmentExpression { Left = new NamedNode("var1", new IdentifierExpression(Pattern.AnyString)), Operator = AssignmentOperatorType.Assign, Right = new NamedNode( "field", new MemberReferenceExpression { Target = new Choice { new ThisReferenceExpression(), new TypeReferenceExpression { Type = new AnyNode() } }, MemberName = Pattern.AnyString } ) }, new DoWhileStatement { EmbeddedStatement = new BlockStatement { new AssignmentExpression(new NamedNode("var2", new IdentifierExpression(Pattern.AnyString)), new IdentifierExpressionBackreference("var1")), new AssignmentExpression { Left = new IdentifierExpressionBackreference("var1"), Right = new InvocationExpression(new MemberReferenceExpression(new TypeReferenceExpression(new TypePattern(typeof(System.Threading.Interlocked)).ToType()), "CompareExchange", new AstType[] { new Repeat(new AnyNode()) }), // optional type arguments new Expression[] { // arguments new DirectionExpression { FieldDirection = FieldDirection.Ref, Expression = new Backreference("field") }, new CastExpression(new AnyNode("type"), new InvocationExpression(new AnyNode("delegateCombine").ToExpression(), new IdentifierExpressionBackreference("var2"), new IdentifierExpression("value"))), new IdentifierExpressionBackreference("var1") } ) } }, Condition = new BinaryOperatorExpression { Left = new CastExpression(new TypePattern(typeof(object)), new IdentifierExpressionBackreference("var1")), Operator = BinaryOperatorType.InEquality, Right = new IdentifierExpressionBackreference("var2") }, } } }; bool CheckAutomaticEventMatch(Match m, CustomEventDeclaration ev, bool isAddAccessor) { if (!m.Success) return false; Expression fieldExpression = m.Get<Expression>("field").Single(); // field name must match event name switch (fieldExpression) { case IdentifierExpression identifier: if (!CSharpDecompiler.IsEventBackingFieldName(identifier.Identifier, ev.Name, out _)) return false; break; case MemberReferenceExpression memberRef: if (!CSharpDecompiler.IsEventBackingFieldName(memberRef.MemberName, ev.Name, out _)) return false; break; default: return false; } var returnType = ev.ReturnType.GetResolveResult().Type; var eventType = m.Get<AstType>("type").Single().GetResolveResult().Type; // ignore tuple element names, dynamic and nullability if (!NormalizeTypeVisitor.TypeErasure.EquivalentTypes(returnType, eventType)) return false; var combineMethod = m.Get<AstNode>("delegateCombine").Single().Parent.GetSymbol() as IMethod; if (combineMethod == null || combineMethod.Name != (isAddAccessor ? "Combine" : "Remove")) return false; return combineMethod.DeclaringType.FullName == "System.Delegate"; } static readonly string[] attributeTypesToRemoveFromAutoEvents = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute", "System.Runtime.CompilerServices.MethodImplAttribute" }; internal static readonly string[] attributeTypesToRemoveFromAutoProperties = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute" }; bool CheckAutomaticEventV4(CustomEventDeclaration ev) { Match addMatch = automaticEventPatternV4.Match(ev.AddAccessor); if (!CheckAutomaticEventMatch(addMatch, ev, isAddAccessor: true)) return false; Match removeMatch = automaticEventPatternV4.Match(ev.RemoveAccessor); if (!CheckAutomaticEventMatch(removeMatch, ev, isAddAccessor: false)) return false; return true; } bool CheckAutomaticEventV4AggressivelyInlined(CustomEventDeclaration ev) { if (!context.Settings.AggressiveInlining) return false; Match addMatch = automaticEventPatternV4AggressivelyInlined.Match(ev.AddAccessor); if (!CheckAutomaticEventMatch(addMatch, ev, isAddAccessor: true)) return false; Match removeMatch = automaticEventPatternV4AggressivelyInlined.Match(ev.RemoveAccessor); if (!CheckAutomaticEventMatch(removeMatch, ev, isAddAccessor: false)) return false; return true; } bool CheckAutomaticEventV2(CustomEventDeclaration ev) { Match addMatch = automaticEventPatternV2.Match(ev.AddAccessor); if (!CheckAutomaticEventMatch(addMatch, ev, isAddAccessor: true)) return false; Match removeMatch = automaticEventPatternV2.Match(ev.RemoveAccessor); if (!CheckAutomaticEventMatch(removeMatch, ev, isAddAccessor: false)) return false; return true; } bool CheckAutomaticEventV4MCS(CustomEventDeclaration ev) { Match addMatch = automaticEventPatternV4MCS.Match(ev.AddAccessor); if (!CheckAutomaticEventMatch(addMatch, ev, true)) return false; Match removeMatch = automaticEventPatternV4MCS.Match(ev.RemoveAccessor); if (!CheckAutomaticEventMatch(removeMatch, ev, false)) return false; return true; } EventDeclaration TransformAutomaticEvents(CustomEventDeclaration ev) { if (!ev.PrivateImplementationType.IsNull) return null; const Modifiers withoutBody = Modifiers.Abstract | Modifiers.Extern; if ((ev.Modifiers & withoutBody) == 0 && ev.GetSymbol() is IEvent symbol) { if (!CheckAutomaticEventV4AggressivelyInlined(ev) && !CheckAutomaticEventV4(ev) && !CheckAutomaticEventV2(ev) && !CheckAutomaticEventV4MCS(ev)) return null; } RemoveCompilerGeneratedAttribute(ev.AddAccessor.Attributes, attributeTypesToRemoveFromAutoEvents); EventDeclaration ed = new EventDeclaration(); ev.Attributes.MoveTo(ed.Attributes); foreach (var attr in ev.AddAccessor.Attributes) { attr.AttributeTarget = "method"; ed.Attributes.Add(attr.Detach()); } ed.ReturnType = ev.ReturnType.Detach(); ed.Modifiers = ev.Modifiers; ed.Variables.Add(new VariableInitializer(ev.Name)); ed.CopyAnnotationsFrom(ev); var fieldDecl = ev.Parent?.Children.OfType<FieldDeclaration>() .FirstOrDefault(fd => CSharpDecompiler.IsEventBackingFieldName(fd.Variables.Single().Name, ev.Name, out _)); if (fieldDecl != null) { fieldDecl.Remove(); CSharpDecompiler.RemoveAttribute(fieldDecl, KnownAttribute.CompilerGenerated); CSharpDecompiler.RemoveAttribute(fieldDecl, KnownAttribute.DebuggerBrowsable); foreach (var section in fieldDecl.Attributes) { section.AttributeTarget = "field"; ed.Attributes.Add(section.Detach()); } } ev.ReplaceWith(ed); return ed; } #endregion #region Destructor static readonly BlockStatement destructorBodyPattern = new BlockStatement { new TryCatchStatement { TryBlock = new AnyNode("body"), FinallyBlock = new BlockStatement { new InvocationExpression(new MemberReferenceExpression(new BaseReferenceExpression(), "Finalize")) } } }; static readonly MethodDeclaration destructorPattern = new MethodDeclaration { Attributes = { new Repeat(new AnyNode()) }, Modifiers = Modifiers.Any, ReturnType = new PrimitiveType("void"), Name = "Finalize", Body = destructorBodyPattern }; DestructorDeclaration TransformDestructor(MethodDeclaration methodDef) { Match m = destructorPattern.Match(methodDef); if (m.Success) { DestructorDeclaration dd = new DestructorDeclaration(); methodDef.Attributes.MoveTo(dd.Attributes); dd.CopyAnnotationsFrom(methodDef); dd.Modifiers = methodDef.Modifiers & ~(Modifiers.Protected | Modifiers.Override); dd.Body = m.Get<BlockStatement>("body").Single().Detach(); dd.Name = currentTypeDefinition?.Name; methodDef.ReplaceWith(dd); return dd; } return null; } DestructorDeclaration TransformDestructorBody(DestructorDeclaration dtorDef) { Match m = destructorBodyPattern.Match(dtorDef.Body); if (m.Success) { dtorDef.Body = m.Get<BlockStatement>("body").Single().Detach(); return dtorDef; } return null; } #endregion #region Try-Catch-Finally static readonly TryCatchStatement tryCatchFinallyPattern = new TryCatchStatement { TryBlock = new BlockStatement { new TryCatchStatement { TryBlock = new AnyNode(), CatchClauses = { new Repeat(new AnyNode()) } } }, FinallyBlock = new AnyNode() }; /// <summary> /// Simplify nested 'try { try {} catch {} } finally {}'. /// This transformation must run after the using/lock tranformations. /// </summary> TryCatchStatement TransformTryCatchFinally(TryCatchStatement tryFinally) { if (tryCatchFinallyPattern.IsMatch(tryFinally)) { TryCatchStatement tryCatch = (TryCatchStatement)tryFinally.TryBlock.Statements.Single(); tryFinally.TryBlock = tryCatch.TryBlock.Detach(); tryCatch.CatchClauses.MoveTo(tryFinally.CatchClauses); } // Since the tryFinally instance is not changed, we can continue in the visitor as usual, so return null return null; } #endregion #region Simplify cascading if-else-if statements static readonly IfElseStatement cascadingIfElsePattern = new IfElseStatement { Condition = new AnyNode(), TrueStatement = new AnyNode(), FalseStatement = new BlockStatement { Statements = { new NamedNode( "nestedIfStatement", new IfElseStatement { Condition = new AnyNode(), TrueStatement = new AnyNode(), FalseStatement = new OptionalNode(new AnyNode()) } ) } } }; AstNode SimplifyCascadingIfElseStatements(IfElseStatement node) { Match m = cascadingIfElsePattern.Match(node); if (m.Success) { IfElseStatement elseIf = m.Get<IfElseStatement>("nestedIfStatement").Single(); node.FalseStatement = elseIf.Detach(); } return null; } /// <summary> /// Use associativity of logic operators to avoid parentheses. /// </summary> public override AstNode VisitBinaryOperatorExpression(BinaryOperatorExpression expr) { switch (expr.Operator) { case BinaryOperatorType.ConditionalAnd: case BinaryOperatorType.ConditionalOr: // a && (b && c) ==> (a && b) && c var bAndC = expr.Right as BinaryOperatorExpression; if (bAndC != null && bAndC.Operator == expr.Operator) { // make bAndC the parent and expr the child var b = bAndC.Left.Detach(); var c = bAndC.Right.Detach(); expr.ReplaceWith(bAndC.Detach()); bAndC.Left = expr; bAndC.Right = c; expr.Right = b; return base.VisitBinaryOperatorExpression(bAndC); } break; } return base.VisitBinaryOperatorExpression(expr); } #endregion #region C# 7.3 pattern based fixed (for value types) // reference types are handled by DetectPinnedRegions.IsCustomRefPinPattern static readonly Expression addressOfPinnableReference = new UnaryOperatorExpression { Operator = UnaryOperatorType.AddressOf, Expression = new InvocationExpression { Target = new MemberReferenceExpression(new AnyNode("target"), "GetPinnableReference"), Arguments = { } } }; public override AstNode VisitFixedStatement(FixedStatement fixedStatement) { if (context.Settings.PatternBasedFixedStatement) { foreach (var v in fixedStatement.Variables) { var m = addressOfPinnableReference.Match(v.Initializer); if (m.Success) { Expression target = m.Get<Expression>("target").Single(); if (target.GetResolveResult().Type.IsReferenceType == false) { v.Initializer = target.Detach(); } } } } return base.VisitFixedStatement(fixedStatement); } #endregion #region C# 8.0 Using variables public override AstNode VisitUsingStatement(UsingStatement usingStatement) { usingStatement = (UsingStatement)base.VisitUsingStatement(usingStatement); if (!context.Settings.UseEnhancedUsing) return usingStatement; if (usingStatement.GetNextStatement() != null || !(usingStatement.Parent is BlockStatement)) return usingStatement; if (!(usingStatement.ResourceAcquisition is VariableDeclarationStatement)) return usingStatement; usingStatement.IsEnhanced = true; return usingStatement; } #endregion } }
ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs", "repo_id": "ILSpy", "token_count": 16024 }
205
using System; using System.Collections.Immutable; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace ICSharpCode.Decompiler.DebugInfo { public readonly struct AsyncDebugInfo { public readonly int CatchHandlerOffset; public readonly ImmutableArray<Await> Awaits; public AsyncDebugInfo(int catchHandlerOffset, ImmutableArray<Await> awaits) { this.CatchHandlerOffset = catchHandlerOffset; this.Awaits = awaits; } public readonly struct Await { public readonly int YieldOffset; public readonly int ResumeOffset; public Await(int yieldOffset, int resumeOffset) { this.YieldOffset = yieldOffset; this.ResumeOffset = resumeOffset; } } public BlobBuilder BuildBlob(MethodDefinitionHandle moveNext) { BlobBuilder blob = new BlobBuilder(); blob.WriteUInt32((uint)CatchHandlerOffset); foreach (var await in Awaits) { blob.WriteUInt32((uint)await.YieldOffset); blob.WriteUInt32((uint)await.ResumeOffset); blob.WriteCompressedInteger(MetadataTokens.GetRowNumber(moveNext)); } return blob; } } }
ILSpy/ICSharpCode.Decompiler/DebugInfo/AsyncDebugInfo.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/DebugInfo/AsyncDebugInfo.cs", "repo_id": "ILSpy", "token_count": 413 }
206
// 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.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.Disassembler { /// <summary> /// Specifies the type of an IL structure. /// </summary> public enum ILStructureType { /// <summary> /// The root block of the method /// </summary> Root, /// <summary> /// A nested control structure representing a loop. /// </summary> Loop, /// <summary> /// A nested control structure representing a try block. /// </summary> Try, /// <summary> /// A nested control structure representing a catch, finally, or fault block. /// </summary> Handler, /// <summary> /// A nested control structure representing an exception filter block. /// </summary> Filter } /// <summary> /// An IL structure. /// </summary> public class ILStructure { public readonly PEFile Module; public readonly MethodDefinitionHandle MethodHandle; public readonly MetadataGenericContext GenericContext; public readonly ILStructureType Type; /// <summary> /// Start position of the structure. /// </summary> public readonly int StartOffset; /// <summary> /// End position of the structure. (exclusive) /// </summary> public readonly int EndOffset; /// <summary> /// The exception handler associated with the Try, Filter or Handler block. /// </summary> public readonly ExceptionRegion ExceptionHandler; /// <summary> /// The loop's entry point. /// </summary> public readonly int LoopEntryPointOffset; /// <summary> /// The list of child structures. /// </summary> public readonly List<ILStructure> Children = new List<ILStructure>(); public ILStructure(PEFile module, MethodDefinitionHandle handle, MetadataGenericContext genericContext, MethodBodyBlock body) : this(module, handle, genericContext, ILStructureType.Root, 0, body.GetILReader().Length) { // Build the tree of exception structures: for (int i = 0; i < body.ExceptionRegions.Length; i++) { ExceptionRegion eh = body.ExceptionRegions[i]; if (!body.ExceptionRegions.Take(i).Any(oldEh => oldEh.TryOffset == eh.TryOffset && oldEh.TryLength == eh.TryLength)) AddNestedStructure(new ILStructure(module, handle, genericContext, ILStructureType.Try, eh.TryOffset, eh.TryOffset + eh.TryLength, eh)); if (eh.Kind == ExceptionRegionKind.Filter) AddNestedStructure(new ILStructure(module, handle, genericContext, ILStructureType.Filter, eh.FilterOffset, eh.HandlerOffset, eh)); AddNestedStructure(new ILStructure(module, handle, genericContext, ILStructureType.Handler, eh.HandlerOffset, eh.HandlerOffset + eh.HandlerLength, eh)); } // Very simple loop detection: look for backward branches (var allBranches, var isAfterUnconditionalBranch) = FindAllBranches(body.GetILReader()); // We go through the branches in reverse so that we find the biggest possible loop boundary first (think loops with "continue;") for (int i = allBranches.Count - 1; i >= 0; i--) { int loopEnd = allBranches[i].Source.End; int loopStart = allBranches[i].Target; if (loopStart < loopEnd) { // We found a backward branch. This is a potential loop. // Check that is has only one entry point: int entryPoint = -1; // entry point is first instruction in loop if prev inst isn't an unconditional branch if (loopStart > 0 && !isAfterUnconditionalBranch[loopStart]) entryPoint = allBranches[i].Target; bool multipleEntryPoints = false; foreach (var branch in allBranches) { if (branch.Source.Start < loopStart || branch.Source.Start >= loopEnd) { if (loopStart <= branch.Target && branch.Target < loopEnd) { // jump from outside the loop into the loop if (entryPoint < 0) entryPoint = branch.Target; else if (branch.Target != entryPoint) multipleEntryPoints = true; } } } if (!multipleEntryPoints) { AddNestedStructure(new ILStructure(module, handle, genericContext, ILStructureType.Loop, loopStart, loopEnd, entryPoint)); } } } SortChildren(); } public ILStructure(PEFile module, MethodDefinitionHandle handle, MetadataGenericContext genericContext, ILStructureType type, int startOffset, int endOffset, ExceptionRegion handler = default) { Debug.Assert(startOffset < endOffset); this.Module = module; this.MethodHandle = handle; this.GenericContext = genericContext; this.Type = type; this.StartOffset = startOffset; this.EndOffset = endOffset; this.ExceptionHandler = handler; } public ILStructure(PEFile module, MethodDefinitionHandle handle, MetadataGenericContext genericContext, ILStructureType type, int startOffset, int endOffset, int loopEntryPoint) { Debug.Assert(startOffset < endOffset); this.Module = module; this.MethodHandle = handle; this.GenericContext = genericContext; this.Type = type; this.StartOffset = startOffset; this.EndOffset = endOffset; this.LoopEntryPointOffset = loopEntryPoint; } bool AddNestedStructure(ILStructure newStructure) { // special case: don't consider the loop-like structure of "continue;" statements to be nested loops if (this.Type == ILStructureType.Loop && newStructure.Type == ILStructureType.Loop && newStructure.StartOffset == this.StartOffset) return false; // use <= for end-offset comparisons because both end and EndOffset are exclusive Debug.Assert(StartOffset <= newStructure.StartOffset && newStructure.EndOffset <= EndOffset); foreach (ILStructure child in this.Children) { if (child.StartOffset <= newStructure.StartOffset && newStructure.EndOffset <= child.EndOffset) { return child.AddNestedStructure(newStructure); } else if (!(child.EndOffset <= newStructure.StartOffset || newStructure.EndOffset <= child.StartOffset)) { // child and newStructure overlap if (!(newStructure.StartOffset <= child.StartOffset && child.EndOffset <= newStructure.EndOffset)) { // Invalid nesting, can't build a tree. -> Don't add the new structure. return false; } } } // Move existing structures into the new structure: for (int i = 0; i < this.Children.Count; i++) { ILStructure child = this.Children[i]; if (newStructure.StartOffset <= child.StartOffset && child.EndOffset <= newStructure.EndOffset) { this.Children.RemoveAt(i--); newStructure.Children.Add(child); } } // Add the structure here: this.Children.Add(newStructure); return true; } struct Branch { public Interval Source; public int Target; public Branch(int start, int end, int target) { this.Source = new Interval(start, end); this.Target = target; } public override string ToString() { return $"[Branch Source={Source}, Target={Target}]"; } } /// <summary> /// Finds all branches. Returns list of source offset->target offset mapping. /// Multiple entries for the same source offset are possible (switch statements). /// The result is sorted by source offset. /// </summary> (List<Branch> Branches, BitSet IsAfterUnconditionalBranch) FindAllBranches(BlobReader body) { var result = new List<Branch>(); var bitset = new BitSet(body.Length + 1); body.Reset(); int target; while (body.RemainingBytes > 0) { var offset = body.Offset; int endOffset; var thisOpCode = body.DecodeOpCode(); switch (thisOpCode.GetOperandType()) { case OperandType.BrTarget: case OperandType.ShortBrTarget: target = ILParser.DecodeBranchTarget(ref body, thisOpCode); endOffset = body.Offset; result.Add(new Branch(offset, endOffset, target)); bitset[endOffset] = IsUnconditionalBranch(thisOpCode); break; case OperandType.Switch: var targets = ILParser.DecodeSwitchTargets(ref body); foreach (int t in targets) result.Add(new Branch(offset, body.Offset, t)); break; default: ILParser.SkipOperand(ref body, thisOpCode); bitset[body.Offset] = IsUnconditionalBranch(thisOpCode); break; } } return (result, bitset); } static bool IsUnconditionalBranch(ILOpCode opCode) { switch (opCode) { case ILOpCode.Br: case ILOpCode.Br_s: case ILOpCode.Ret: case ILOpCode.Endfilter: case ILOpCode.Endfinally: case ILOpCode.Throw: case ILOpCode.Rethrow: case ILOpCode.Leave: case ILOpCode.Leave_s: return true; default: return false; } } void SortChildren() { Children.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset)); foreach (ILStructure child in Children) child.SortChildren(); } /// <summary> /// Gets the innermost structure containing the specified offset. /// </summary> public ILStructure GetInnermost(int offset) { Debug.Assert(StartOffset <= offset && offset < EndOffset); foreach (ILStructure child in this.Children) { if (child.StartOffset <= offset && offset < child.EndOffset) return child.GetInnermost(offset); } return this; } } }
ILSpy/ICSharpCode.Decompiler/Disassembler/ILStructure.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Disassembler/ILStructure.cs", "repo_id": "ILSpy", "token_count": 3620 }
207
// 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.Linq; using ICSharpCode.Decompiler.FlowAnalysis; using ICSharpCode.Decompiler.IL.Transforms; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.IL.ControlFlow { /// <summary> /// Detect loops in IL AST. /// </summary> /// <remarks> /// Transform ordering: /// * LoopDetection should run before other control flow structures are detected. /// * Blocks should be basic blocks (not extended basic blocks) so that the natural loops /// don't include more instructions than strictly necessary. /// * Loop detection should run after the 'return block' is duplicated (ControlFlowSimplification). /// </remarks> public class LoopDetection : IBlockTransform { BlockTransformContext context; /// <summary>Block container corresponding to the current cfg.</summary> BlockContainer currentBlockContainer; /// <summary> /// Enabled during DetectSwitchBody, used by ExtendLoop and children /// </summary> private bool isSwitch; /// <summary> /// Used when isSwitch == true, to determine appropriate exit points within loops /// </summary> private SwitchDetection.LoopContext loopContext; /// <summary> /// Check whether 'block' is a loop head; and construct a loop instruction /// (nested BlockContainer) if it is. /// </summary> public void Run(Block block, BlockTransformContext context) { this.context = context; // LoopDetection runs early enough so that block should still // be in the original container at this point. Debug.Assert(block.Parent == context.ControlFlowGraph.Container); this.currentBlockContainer = context.ControlFlowGraph.Container; // Because this is a post-order block transform, we can assume that // any nested loops within this loop have already been constructed. if (block.Instructions.Last() is SwitchInstruction switchInst) { // Switch instructions support "break;" just like loops DetectSwitchBody(block, switchInst); } ControlFlowNode h = context.ControlFlowNode; // CFG node for our potential loop head Debug.Assert(h.UserData == block); Debug.Assert(!TreeTraversal.PreOrder(h, n => n.DominatorTreeChildren).Any(n => n.Visited)); List<ControlFlowNode> loop = null; foreach (var t in h.Predecessors) { if (h.Dominates(t)) { // h->t is a back edge, and h is a loop header // Add the natural loop of t->h to the loop. // Definitions: // * A back edge is an edge t->h so that h dominates t. // * The natural loop of the back edge is the smallest set of nodes // that includes the back edge and has no predecessors outside the set // except for the predecessor of the header. if (loop == null) { loop = new List<ControlFlowNode>(); loop.Add(h); // Mark loop header as visited so that the pre-order traversal // stops at the loop header. h.Visited = true; } t.TraversePreOrder(n => n.Predecessors, loop.Add); } } if (loop != null) { var headBlock = (Block)h.UserData; context.Step($"Construct loop with head {headBlock.Label}", headBlock); // loop now is the union of all natural loops with loop head h. // Ensure any block included into nested loops is also considered part of this loop: IncludeNestedContainers(loop); // Try to extend the loop to reduce the number of exit points: ExtendLoop(h, loop, out var exitPoint); // Sort blocks in the loop in reverse post-order to make the output look a bit nicer. // (if the loop doesn't contain nested loops, this is a topological sort) loop.Sort((a, b) => b.PostOrderNumber.CompareTo(a.PostOrderNumber)); Debug.Assert(loop[0] == h); foreach (var node in loop) { node.Visited = false; // reset visited flag so that we can find outer loops Debug.Assert(h.Dominates(node), "The loop body must be dominated by the loop head"); } ConstructLoop(loop, exitPoint); } } /// <summary> /// For each block in the input loop that is the head of a nested loop or switch, /// include all blocks from the nested container into the loop. /// /// This ensures that all blocks that were included into inner loops are also /// included into the outer loop, thus keeping our loops well-nested. /// </summary> /// <remarks> /// More details for why this is necessary are here: /// https://github.com/icsharpcode/ILSpy/issues/915 /// /// Pre+Post-Condition: node.Visited iff loop.Contains(node) /// </remarks> void IncludeNestedContainers(List<ControlFlowNode> loop) { for (int i = 0; i < loop.Count; i++) { IncludeBlock((Block)loop[i].UserData); } void IncludeBlock(Block block) { foreach (var nestedContainer in block.Instructions.OfType<BlockContainer>()) { // Just in case the block has multiple nested containers (e.g. due to loop and switch), // also check the entry point: IncludeBlock(nestedContainer.EntryPoint); // Use normal processing for all non-entry-point blocks // (the entry-point itself doesn't have a CFG node, because it's newly created by this transform) for (int i = 1; i < nestedContainer.Blocks.Count; i++) { var node = context.ControlFlowGraph.GetNode(nestedContainer.Blocks[i]); Debug.Assert(loop[0].Dominates(node)); if (!node.Visited) { node.Visited = true; loop.Add(node); // note: this block will be re-visited when the "i < loop.Count" // gets around to the new entry } } } } } #region ExtendLoop /// <summary> /// Given a natural loop, add additional CFG nodes to the loop in order /// to reduce the number of exit points out of the loop. /// We do this because C# only allows reaching a single exit point (with 'break' /// statements or when the loop condition evaluates to false), so we'd have /// to introduce 'goto' statements for any additional exit points. /// </summary> /// <remarks> /// Definition: /// A "reachable exit" is a branch/leave target that is reachable from the loop, /// but not dominated by the loop head. A reachable exit may or may not have a /// corresponding CFG node (depending on whether it is a block in the current block container). /// -> reachable exits are leaving the code region dominated by the loop /// /// Definition: /// A loop "exit point" is a CFG node that is not itself part of the loop, /// but has at least one predecessor which is part of the loop. /// -> exit points are leaving the loop itself /// /// Nodes can only be added to the loop if they are dominated by the loop head. /// When adding a node to the loop, we must also add all of that node's predecessors /// to the loop. (this ensures that the loop keeps its single entry point) /// /// Goal: If possible, find a set of nodes that can be added to the loop so that there /// remains only a single exit point. /// Add as little code as possible to the loop to reach this goal. /// /// This means we need to partition the set of nodes dominated by the loop entry point /// into two sets (in-loop and out-of-loop). /// Constraints: /// * the loop head itself is in-loop /// * there must not be any edge from an out-of-loop node to an in-loop node /// -> all predecessors of in-loop nodes are also in-loop /// -> all nodes in a cycle are part of the same partition /// Optimize: /// * use only a single exit point if at all possible /// * minimize the amount of code in the in-loop partition /// (thus: maximize the amount of code in the out-of-loop partition) /// /// Observations: /// * If a node is in-loop, so are all its ancestors in the dominator tree (up to the loop entry point) /// * If there are no exits reachable from a node (i.e. all paths from that node lead to a return/throw instruction), /// it is valid to put the group of nodes dominated by that node into either partition independently of /// any other nodes except for the ancestors in the dominator tree. /// (exception: the loop head itself must always be in-loop) /// /// There are two different cases we need to consider: /// 1) There are no exits reachable at all from the loop head. /// -> it is possible to create a loop with zero exit points by adding all nodes /// dominated by the loop to the loop. /// -> the only way to exit the loop is by "return;" or "throw;" /// 2) There are some exits reachable from the loop head. /// /// In case 1, we can pick a single exit point freely by picking any node that has no reachable exits /// (other than the loop head). /// All nodes dominated by the exit point are out-of-loop, all other nodes are in-loop. /// See PickExitPoint() for the heuristic that picks the exit point in this case. /// /// In case 2, we need to pick our exit point so that all paths from the loop head /// to the reachable exits run through that exit point. /// /// This is a form of postdominance where the reachable exits are considered exit nodes, /// while "return;" or "throw;" instructions are not considered exit nodes. /// /// Using this form of postdominance, we are looking for an exit point that post-dominates all nodes in the natural loop. /// --> a common ancestor in post-dominator tree. /// To minimize the amount of code in-loop, we pick the lowest common ancestor. /// All nodes dominated by the exit point are out-of-loop, all other nodes are in-loop. /// (using normal dominance as in case 1, not post-dominance!) /// /// If it is impossible to use a single exit point for the loop, the lowest common ancestor will be the fake "exit node" /// used by the post-dominance analysis. In this case, we fall back to the old heuristic algorithm. /// /// Requires and maintains the invariant that a node is marked as visited iff it is contained in the loop. /// </remarks> void ExtendLoop(ControlFlowNode loopHead, List<ControlFlowNode> loop, out ControlFlowNode exitPoint) { exitPoint = FindExitPoint(loopHead, loop); Debug.Assert(!loop.Contains(exitPoint), "Cannot pick an exit point that is part of the natural loop"); if (exitPoint != null) { // Either we are in case 1 and just picked an exit that maximizes the amount of code // outside the loop, or we are in case 2 and found an exit point via post-dominance. // Note that if exitPoint == NoExitPoint, we end up adding all dominated blocks to the loop. var ep = exitPoint; foreach (var node in TreeTraversal.PreOrder(loopHead, n => DominatorTreeChildren(n, ep))) { if (!node.Visited) { node.Visited = true; loop.Add(node); } } // The loop/switch can only be entered through the entry point. if (isSwitch) { // In the case of a switch, false positives in the "continue;" detection logic // can lead to falsely excludes some blocks from the body. // Fix that by including all predecessors of included blocks. Debug.Assert(loop[0] == loopHead); for (int i = 1; i < loop.Count; i++) { foreach (var p in loop[i].Predecessors) { if (!p.Visited) { p.Visited = true; loop.Add(p); } } } } Debug.Assert(loop.All(n => n == loopHead || n.Predecessors.All(p => p.Visited))); } else { // We are in case 2, but could not find a suitable exit point. // Heuristically try to minimize the number of exit points // (but we'll always end up with more than 1 exit and will require goto statements). ExtendLoopHeuristic(loopHead, loop, loopHead); } } /// <summary> /// Special control flow node (not part of any graph) that signifies that we want to construct a loop /// without any exit point. /// </summary> static readonly ControlFlowNode NoExitPoint = new ControlFlowNode(); /// <summary> /// Finds a suitable single exit point for the specified loop. /// </summary> /// <returns> /// 1) If a suitable exit point was found: the control flow block that should be reached when breaking from the loop /// 2) If the loop should not have any exit point (extend by all dominated blocks): NoExitPoint /// 3) otherwise (exit point unknown, heuristically extend loop): null /// </returns> /// <remarks>This method must not write to the Visited flags on the CFG.</remarks> internal ControlFlowNode FindExitPoint(ControlFlowNode loopHead, IReadOnlyList<ControlFlowNode> naturalLoop) { bool hasReachableExit = HasReachableExit(loopHead); if (!hasReachableExit) { // Case 1: // There are no nodes n so that loopHead dominates a predecessor of n but not n itself // -> we could build a loop with zero exit points. if (IsPossibleForeachLoop((Block)loopHead.UserData, out var exitBranch)) { if (exitBranch != null) { // let's see if the target of the exit branch is a suitable exit point var cfgNode = loopHead.Successors.FirstOrDefault(n => n.UserData == exitBranch.TargetBlock); if (cfgNode != null && loopHead.Dominates(cfgNode) && !context.ControlFlowGraph.HasReachableExit(cfgNode)) { return cfgNode; } } return NoExitPoint; } ControlFlowNode exitPoint = null; int exitPointILOffset = -1; ConsiderReturnAsExitPoint((Block)loopHead.UserData, ref exitPoint, ref exitPointILOffset); foreach (var node in loopHead.DominatorTreeChildren) { PickExitPoint(node, ref exitPoint, ref exitPointILOffset); } return exitPoint; } else { // Case 2: // We need to pick our exit point so that all paths from the loop head // to the reachable exits run through that exit point. var cfg = context.ControlFlowGraph.cfg; var revCfg = PrepareReverseCFG(loopHead, out int exitNodeArity); //ControlFlowNode.ExportGraph(cfg).Show("cfg"); //ControlFlowNode.ExportGraph(revCfg).Show("rev"); ControlFlowNode commonAncestor = revCfg[loopHead.UserIndex]; Debug.Assert(commonAncestor.IsReachable); foreach (ControlFlowNode cfgNode in naturalLoop) { ControlFlowNode revNode = revCfg[cfgNode.UserIndex]; if (revNode.IsReachable) { commonAncestor = Dominance.FindCommonDominator(commonAncestor, revNode); } } // All paths from within the loop to a reachable exit run through 'commonAncestor'. // However, this doesn't mean that 'commonAncestor' is valid as an exit point. // We walk up the post-dominator tree until we've got a valid exit point: ControlFlowNode exitPoint; while (commonAncestor.UserIndex >= 0) { exitPoint = cfg[commonAncestor.UserIndex]; Debug.Assert(exitPoint.Visited == naturalLoop.Contains(exitPoint)); // It's possible that 'commonAncestor' is itself part of the natural loop. // If so, it's not a valid exit point. if (!exitPoint.Visited && ValidateExitPoint(loopHead, exitPoint)) { // we found an exit point return exitPoint; } commonAncestor = commonAncestor.ImmediateDominator; } // least common post-dominator is the artificial exit node // This means we're in one of two cases: // * The loop might have multiple exit points. // -> we should return null // * The loop has a single exit point that wasn't considered during post-dominance analysis. // (which means the single exit isn't dominated by the loop head) // -> we should return NoExitPoint so that all code dominated by the loop head is included into the loop if (exitNodeArity > 1) return null; // Exit node is on the very edge of the tree, and isn't important for determining inclusion // Still necessary for switch detection to insert correct leave statements if (exitNodeArity == 1 && isSwitch) return loopContext.GetBreakTargets(loopHead).Distinct().Single(); // If exitNodeArity == 0, we should maybe look test if our exits out of the block container are all compatible? // but I don't think it hurts to have a bit too much code inside the loop in this rare case. return NoExitPoint; } } /// <summary> /// Validates an exit point. /// /// An exit point is invalid iff there is a node reachable from the exit point that /// is dominated by the loop head, but not by the exit point. /// (i.e. this method returns false iff the exit point's dominance frontier contains /// a node dominated by the loop head. but we implement this the slow way because /// we don't have dominance frontiers precomputed) /// </summary> /// <remarks> /// We need this because it's possible that there's a return block (thus reverse-unreachable node ignored by post-dominance) /// that is reachable both directly from the loop, and from the exit point. /// </remarks> bool ValidateExitPoint(ControlFlowNode loopHead, ControlFlowNode exitPoint) { var cfg = context.ControlFlowGraph; return IsValid(exitPoint); bool IsValid(ControlFlowNode node) { if (!cfg.HasReachableExit(node)) { // Optimization: if the dominance frontier is empty, we don't need // to check every node. return true; } foreach (var succ in node.Successors) { if (loopHead != succ && loopHead.Dominates(succ) && !exitPoint.Dominates(succ)) return false; } foreach (var child in node.DominatorTreeChildren) { if (!IsValid(child)) return false; } return true; } } /// <summary> /// Extension of ControlFlowGraph.HasReachableExit /// Uses loopContext.GetBreakTargets().Any() when analyzing switches to avoid /// classifying continue blocks as reachable exits. /// </summary> bool HasReachableExit(ControlFlowNode node) => isSwitch ? loopContext.GetBreakTargets(node).Any() : context.ControlFlowGraph.HasReachableExit(node); /// <summary> /// Returns the children in a loop dominator tree, with an optional exit point /// Avoids returning continue statements when analysing switches (because increment blocks can be dominated) /// </summary> IEnumerable<ControlFlowNode> DominatorTreeChildren(ControlFlowNode n, ControlFlowNode exitPoint) => n.DominatorTreeChildren.Where(c => c != exitPoint && (!isSwitch || !loopContext.MatchContinue(c))); /// <summary> /// Pick exit point by picking any node that has no reachable exits. /// /// In the common case where the code was compiled with a compiler that emits IL code /// in source order (like the C# compiler), we can find the "real" exit point /// by simply picking the block with the highest IL offset. /// So let's do that instead of maximizing amount of code. /// </summary> /// <returns>Code amount in <paramref name="node"/> and its dominated nodes.</returns> /// <remarks>This method must not write to the Visited flags on the CFG.</remarks> void PickExitPoint(ControlFlowNode node, ref ControlFlowNode exitPoint, ref int exitPointILOffset) { if (isSwitch && loopContext.MatchContinue(node)) return; Block block = (Block)node.UserData; if (block.StartILOffset > exitPointILOffset && !HasReachableExit(node) && ((Block)node.UserData).Parent == currentBlockContainer) { // HasReachableExit(node) == false // -> there are no nodes n so that `node` dominates a predecessor of n but not n itself // -> there is no control flow out of `node` back into the loop, so it's usable as exit point // Additionally, we require that the block wasn't already moved into a nested loop, // since there's no way to jump into the middle of that loop when we need to exit. // NB: this is the only reason why we detect nested loops before outer loops: // If we detected the outer loop first, the outer loop might pick an exit point // that prevents us from finding a nice exit for the inner loops, causing // unnecessary gotos. exitPoint = node; exitPointILOffset = block.StartILOffset; return; // don't visit children, they are likely to have even later IL offsets and we'd end up // moving almost all of the code into the loop. } ConsiderReturnAsExitPoint(block, ref exitPoint, ref exitPointILOffset); foreach (var child in node.DominatorTreeChildren) { PickExitPoint(child, ref exitPoint, ref exitPointILOffset); } } private static void ConsiderReturnAsExitPoint(Block block, ref ControlFlowNode exitPoint, ref int exitPointILOffset) { // It's possible that the real exit point of the loop is a "return;" that has been combined (by ControlFlowSimplification) // with the condition block. if (!block.MatchIfAtEndOfBlock(out _, out var trueInst, out var falseInst)) return; if (trueInst.StartILOffset > exitPointILOffset && trueInst is Leave { IsLeavingFunction: true, Value: Nop _ }) { // By using NoExitPoint, everything (including the "return;") becomes part of the loop body // Then DetectExitPoint will move the "return;" out of the loop body. exitPoint = NoExitPoint; exitPointILOffset = trueInst.StartILOffset; } if (falseInst.StartILOffset > exitPointILOffset && falseInst is Leave { IsLeavingFunction: true, Value: Nop _ }) { exitPoint = NoExitPoint; exitPointILOffset = falseInst.StartILOffset; } } /// <summary> /// Constructs a new control flow graph. /// Each node cfg[i] has a corresponding node rev[i]. /// Edges are only created for nodes dominated by loopHead, and are in reverse from their direction /// in the primary CFG. /// An artificial exit node is used for edges that leave the set of nodes dominated by loopHead, /// or that leave the block Container. /// </summary> /// <param name="loopHead">Entry point of the loop.</param> /// <param name="exitNodeArity">out: The number of different CFG nodes. /// Possible values: /// 0 = no CFG nodes used as exit nodes (although edges leaving the block container might still be exits); /// 1 = a single CFG node (not dominated by loopHead) was used as an exit node; /// 2 = more than one CFG node (not dominated by loopHead) was used as an exit node. /// </param> /// <returns></returns> ControlFlowNode[] PrepareReverseCFG(ControlFlowNode loopHead, out int exitNodeArity) { ControlFlowNode[] cfg = context.ControlFlowGraph.cfg; ControlFlowNode[] rev = new ControlFlowNode[cfg.Length + 1]; for (int i = 0; i < cfg.Length; i++) { rev[i] = new ControlFlowNode { UserIndex = i, UserData = cfg[i].UserData }; } ControlFlowNode nodeTreatedAsExitNode = null; bool multipleNodesTreatedAsExitNodes = false; ControlFlowNode exitNode = new ControlFlowNode { UserIndex = -1 }; rev[cfg.Length] = exitNode; for (int i = 0; i < cfg.Length; i++) { if (!loopHead.Dominates(cfg[i]) || isSwitch && cfg[i] != loopHead && loopContext.MatchContinue(cfg[i])) continue; // Add reverse edges for all edges in cfg foreach (var succ in cfg[i].Successors) { // edges to outer loops still count as exits (labelled continue not implemented) if (isSwitch && loopContext.MatchContinue(succ, 1)) continue; if (loopHead.Dominates(succ)) { rev[succ.UserIndex].AddEdgeTo(rev[i]); } else { if (nodeTreatedAsExitNode == null) nodeTreatedAsExitNode = succ; if (nodeTreatedAsExitNode != succ) multipleNodesTreatedAsExitNodes = true; exitNode.AddEdgeTo(rev[i]); } } if (context.ControlFlowGraph.HasDirectExitOutOfContainer(cfg[i])) { exitNode.AddEdgeTo(rev[i]); } } if (multipleNodesTreatedAsExitNodes) exitNodeArity = 2; // more than 1 else if (nodeTreatedAsExitNode != null) exitNodeArity = 1; else exitNodeArity = 0; Dominance.ComputeDominance(exitNode, context.CancellationToken); return rev; } static bool IsPossibleForeachLoop(Block loopHead, out Branch exitBranch) { exitBranch = null; var container = (BlockContainer)loopHead.Parent; if (!(container.SlotInfo == TryInstruction.TryBlockSlot && container.Parent is TryFinally)) return false; if (loopHead.Instructions.Count != 2) return false; if (!loopHead.Instructions[0].MatchIfInstruction(out var condition, out var trueInst)) return false; var falseInst = loopHead.Instructions[1]; while (condition.MatchLogicNot(out var arg)) { condition = arg; ExtensionMethods.Swap(ref trueInst, ref falseInst); } if (!(condition is CallInstruction call && call.Method.Name == "MoveNext")) return false; if (!(call.Arguments.Count == 1 && call.Arguments[0].MatchLdLocRef(out var enumeratorVar))) return false; exitBranch = falseInst as Branch; // Check that loopHead is entry-point of try-block: Block entryPoint = container.EntryPoint; while (entryPoint.IncomingEdgeCount == 1 && entryPoint.Instructions.Count == 1 && entryPoint.Instructions[0].MatchBranch(out var targetBlock)) { // skip blocks that only branch to another block entryPoint = targetBlock; } return entryPoint == loopHead; } #endregion #region ExtendLoop (fall-back heuristic) /// <summary> /// This function implements a heuristic algorithm that tries to reduce the number of exit /// points. It is only used as fall-back when it is impossible to use a single exit point. /// </summary> /// <remarks> /// This heuristic loop extension algorithm traverses the loop head's dominator tree in pre-order. /// For each candidate node, we detect whether adding it to the loop reduces the number of exit points. /// If it does, the candidate is added to the loop. /// /// Adding a node to the loop has two effects on the the number of exit points: /// * exit points that were added to the loop are no longer exit points, thus reducing the total number of exit points /// * successors of the newly added nodes might be new, additional exit points /// /// Requires and maintains the invariant that a node is marked as visited iff it is contained in the loop. /// </remarks> void ExtendLoopHeuristic(ControlFlowNode loopHead, List<ControlFlowNode> loop, ControlFlowNode candidate) { Debug.Assert(candidate.Visited == loop.Contains(candidate)); if (!candidate.Visited) { // This node not yet part of the loop, but might be added List<ControlFlowNode> additionalNodes = new List<ControlFlowNode>(); // Find additionalNodes nodes and mark them as visited. candidate.TraversePreOrder(n => n.Predecessors, additionalNodes.Add); // This means Visited now represents the candidate extended loop. // Determine new exit points that are reachable from the additional nodes // (note: some of these might have previously been exit points, too) var newExitPoints = additionalNodes.SelectMany(n => n.Successors).Where(n => !n.Visited).ToHashSet(); // Make visited represent the unextended loop, so that we can measure the exit points // in the old state. foreach (var node in additionalNodes) node.Visited = false; // Measure number of added and removed exit points int removedExitPoints = additionalNodes.Count(IsExitPoint); int addedExitPoints = newExitPoints.Count(n => !IsExitPoint(n)); if (removedExitPoints > addedExitPoints) { // We can reduce the number of exit points by adding the candidate node to the loop. candidate.TraversePreOrder(n => n.Predecessors, loop.Add); } } // Pre-order traversal of dominator tree foreach (var node in candidate.DominatorTreeChildren) { ExtendLoopHeuristic(loopHead, loop, node); } } /// <summary> /// Gets whether 'node' is an exit point for the loop marked by the Visited flag. /// </summary> bool IsExitPoint(ControlFlowNode node) { if (node.Visited) return false; // nodes in the loop are not exit points foreach (var pred in node.Predecessors) { if (pred.Visited) return true; } return false; } #endregion /// <summary> /// Move the blocks associated with the loop into a new block container. /// </summary> void ConstructLoop(List<ControlFlowNode> loop, ControlFlowNode exitPoint) { Block oldEntryPoint = (Block)loop[0].UserData; Block exitTargetBlock = (Block)exitPoint?.UserData; BlockContainer loopContainer = new BlockContainer(ContainerKind.Loop); Block newEntryPoint = new Block(); loopContainer.Blocks.Add(newEntryPoint); // Move contents of oldEntryPoint to newEntryPoint // (we can't move the block itself because it might be the target of branch instructions outside the loop) newEntryPoint.Instructions.ReplaceList(oldEntryPoint.Instructions); newEntryPoint.AddILRange(oldEntryPoint); oldEntryPoint.Instructions.ReplaceList(new[] { loopContainer }); if (exitTargetBlock != null) oldEntryPoint.Instructions.Add(new Branch(exitTargetBlock)); loopContainer.AddILRange(newEntryPoint); MoveBlocksIntoContainer(loop, loopContainer); // Rewrite branches within the loop from oldEntryPoint to newEntryPoint: foreach (var branch in loopContainer.Descendants.OfType<Branch>()) { if (branch.TargetBlock == oldEntryPoint) { branch.TargetBlock = newEntryPoint; } else if (branch.TargetBlock == exitTargetBlock) { branch.ReplaceWith(new Leave(loopContainer).WithILRange(branch)); } } } private void MoveBlocksIntoContainer(List<ControlFlowNode> loop, BlockContainer loopContainer) { // Move other blocks into the loop body: they're all dominated by the loop header, // and thus cannot be the target of branch instructions outside the loop. for (int i = 1; i < loop.Count; i++) { Block block = (Block)loop[i].UserData; // some blocks might already be in use by nested loops that were detected earlier; // don't move those (they'll be implicitly moved when the block containing the // nested loop container is moved). if (block.Parent == currentBlockContainer) { Debug.Assert(block.ChildIndex != 0); int oldChildIndex = block.ChildIndex; loopContainer.Blocks.Add(block); currentBlockContainer.Blocks.SwapRemoveAt(oldChildIndex); } } for (int i = 1; i < loop.Count; i++) { // Verify that we moved all loop blocks into the loop container. // If we wanted to move any blocks already in use by a nested loop, // this means we check that the whole nested loop got moved. Block block = (Block)loop[i].UserData; Debug.Assert(block.IsDescendantOf(loopContainer)); } } private void DetectSwitchBody(Block block, SwitchInstruction switchInst) { Debug.Assert(block.Instructions.Last() == switchInst); ControlFlowNode h = context.ControlFlowNode; // CFG node for our switch head Debug.Assert(h.UserData == block); Debug.Assert(!TreeTraversal.PreOrder(h, n => n.DominatorTreeChildren).Any(n => n.Visited)); isSwitch = true; loopContext = new SwitchDetection.LoopContext(context.ControlFlowGraph, h); var nodesInSwitch = new List<ControlFlowNode>(); nodesInSwitch.Add(h); h.Visited = true; ExtendLoop(h, nodesInSwitch, out var exitPoint); if (exitPoint != null && h.Dominates(exitPoint) && exitPoint.Predecessors.Count == 1 && !HasReachableExit(exitPoint)) { // If the exit point is reachable from just one single "break;", // it's better to move the code into the switch. // (unlike loops which should not be nested unless necessary, // nesting switches makes it clearer in which cases a piece of code is reachable) nodesInSwitch.AddRange(TreeTraversal.PreOrder(exitPoint, p => p.DominatorTreeChildren)); foreach (var node in nodesInSwitch) { node.Visited = true; } exitPoint = null; } context.Step("Create BlockContainer for switch", switchInst); // Sort blocks in the loop in reverse post-order to make the output look a bit nicer. // (if the loop doesn't contain nested loops, this is a topological sort) nodesInSwitch.Sort((a, b) => b.PostOrderNumber.CompareTo(a.PostOrderNumber)); Debug.Assert(nodesInSwitch[0] == h); foreach (var node in nodesInSwitch) { node.Visited = false; // reset visited flag so that we can find outer loops Debug.Assert(h.Dominates(node), "The switch body must be dominated by the switch head"); } BlockContainer switchContainer = new BlockContainer(ContainerKind.Switch); Block newEntryPoint = new Block(); newEntryPoint.AddILRange(switchInst); switchContainer.Blocks.Add(newEntryPoint); newEntryPoint.Instructions.Add(switchInst); block.Instructions[block.Instructions.Count - 1] = switchContainer; Block exitTargetBlock = (Block)exitPoint?.UserData; if (exitTargetBlock != null) { block.Instructions.Add(new Branch(exitTargetBlock)); } switchContainer.AddILRange(newEntryPoint); MoveBlocksIntoContainer(nodesInSwitch, switchContainer); // Rewrite branches within the loop from oldEntryPoint to newEntryPoint: foreach (var branch in switchContainer.Descendants.OfType<Branch>()) { if (branch.TargetBlock == exitTargetBlock) { branch.ReplaceWith(new Leave(switchContainer).WithILRange(branch)); } } isSwitch = false; } } }
ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs", "repo_id": "ILSpy", "token_count": 11469 }
208
// 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; using System.Diagnostics.CodeAnalysis; using System.Threading; using ICSharpCode.Decompiler.IL.Patterns; using ICSharpCode.Decompiler.IL.Transforms; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.IL { internal enum ILPhase { /// <summary> /// Reading the individual instructions. /// * Variables don't have scopes yet as the ILFunction is not created yet. /// * Branches point to IL offsets, not blocks. /// </summary> InILReader, /// <summary> /// The usual invariants are established. /// </summary> Normal, /// <summary> /// Special phase within the async-await decompiler, where a few selected invariants /// are temporarily suspended. (see Leave.CheckInvariant) /// </summary> InAsyncAwait } /// <summary> /// Represents a decoded IL instruction /// </summary> public abstract partial class ILInstruction { public readonly OpCode OpCode; protected ILInstruction(OpCode opCode) { this.OpCode = opCode; } protected void ValidateChild(ILInstruction? inst) { if (inst == null) throw new ArgumentNullException(nameof(inst)); Debug.Assert(!this.IsDescendantOf(inst), "ILAst must form a tree"); // If a call to ReplaceWith() triggers the "ILAst must form a tree" assertion, // make sure to read the remarks on the ReplaceWith() method. } internal static void DebugAssert([DoesNotReturnIf(false)] bool b) { Debug.Assert(b); } internal static void DebugAssert([DoesNotReturnIf(false)] bool b, string msg) { Debug.Assert(b, msg); } [Conditional("DEBUG")] internal virtual void CheckInvariant(ILPhase phase) { foreach (var child in Children) { Debug.Assert(child.Parent == this); Debug.Assert(this.GetChild(child.ChildIndex) == child); // if child flags are invalid, parent flags must be too // exception: nested ILFunctions (lambdas) Debug.Assert(this is ILFunction || child.flags != invalidFlags || this.flags == invalidFlags); Debug.Assert(child.IsConnected == this.IsConnected); child.CheckInvariant(phase); } Debug.Assert((this.DirectFlags & ~this.Flags) == 0, "All DirectFlags must also appear in this.Flags"); } /// <summary> /// Gets whether this node is a descendant of <paramref name="possibleAncestor"/>. /// Also returns true if <c>this</c>==<paramref name="possibleAncestor"/>. /// </summary> /// <remarks> /// This method uses the <c>Parent</c> property, so it may produce surprising results /// when called on orphaned nodes or with a possibleAncestor that contains stale positions /// (see remarks on Parent property). /// </remarks> public bool IsDescendantOf(ILInstruction possibleAncestor) { for (ILInstruction? ancestor = this; ancestor != null; ancestor = ancestor.Parent) { if (ancestor == possibleAncestor) return true; } return false; } public ILInstruction? GetCommonParent(ILInstruction other) { if (other == null) throw new ArgumentNullException(nameof(other)); ILInstruction? a = this; ILInstruction? b = other; int levelA = a.CountAncestors(); int levelB = b.CountAncestors(); while (levelA > levelB) { a = a!.Parent; levelA--; } while (levelB > levelA) { b = b!.Parent; levelB--; } while (a != b) { a = a!.Parent; b = b!.Parent; } return a; } /// <summary> /// Returns whether this appears before other in a post-order walk of the whole tree. /// </summary> public bool IsBefore(ILInstruction other) { if (other == null) throw new ArgumentNullException(nameof(other)); ILInstruction a = this; ILInstruction b = other; int levelA = a.CountAncestors(); int levelB = b.CountAncestors(); int originalLevelA = levelA; int originalLevelB = levelB; while (levelA > levelB) { a = a.Parent!; levelA--; } while (levelB > levelA) { b = b.Parent!; levelB--; } if (a == b) { // a or b is a descendant of the other, // whichever node has the higher level comes first in post-order walk. return originalLevelA > originalLevelB; } while (a.Parent != b.Parent) { a = a.Parent!; b = b.Parent!; } // now a and b have the same parent or are both root nodes return a.ChildIndex < b.ChildIndex; } private int CountAncestors() { int level = 0; for (ILInstruction? ancestor = this; ancestor != null; ancestor = ancestor.Parent) { level++; } return level; } /// <summary> /// Gets the stack type of the value produced by this instruction. /// </summary> public abstract StackType ResultType { get; } /* Not sure if it's a good idea to offer this on all instructions -- * e.g. ldloc for a local of type `int?` would return StackType.O (because it's not a lifted operation), * even though the underlying type is int = StackType.I4. /// <summary> /// Gets the underlying result type of the value produced by this instruction. /// /// If this is a lifted operation, the ResultType will be `StackType.O` (because Nullable{T} is a struct), /// and UnderlyingResultType will be result type of the corresponding non-lifted operation. /// /// If this is not a lifted operation, the underlying result type is equal to the result type. /// </summary> public virtual StackType UnderlyingResultType { get => ResultType; } */ internal static StackType CommonResultType(StackType a, StackType b) { if (a == StackType.I || b == StackType.I) return StackType.I; Debug.Assert(a == b); return a; } #if DEBUG /// <summary> /// Gets whether this node (or any subnode) was modified since the last <c>ResetDirty()</c> call. /// </summary> /// <remarks> /// IsDirty is used by the StatementTransform, and must not be used by individual transforms within the loop. /// </remarks> internal bool IsDirty { get; private set; } /// <summary> /// Marks this node (and all subnodes) as <c>IsDirty=false</c>. /// </summary> internal void ResetDirty() { foreach (ILInstruction inst in Descendants) inst.IsDirty = false; } #endif [Conditional("DEBUG")] protected private void MakeDirty() { #if DEBUG for (ILInstruction? inst = this; inst != null && !inst.IsDirty; inst = inst.parent) { inst.IsDirty = true; } #endif } const InstructionFlags invalidFlags = (InstructionFlags)(-1); InstructionFlags flags = invalidFlags; /// <summary> /// Gets the flags describing the behavior of this instruction. /// This property computes the flags on-demand and caches them /// until some change to the ILAst invalidates the cache. /// </summary> /// <remarks> /// Flag cache invalidation makes use of the <c>Parent</c> property, /// so it is possible for this property to return a stale value /// if the instruction contains "stale positions" (see remarks on Parent property). /// </remarks> public InstructionFlags Flags { get { if (flags == invalidFlags) { flags = ComputeFlags(); } return flags; } } /// <summary> /// Returns whether the instruction (or one of its child instructions) has at least one of the specified flags. /// </summary> public bool HasFlag(InstructionFlags flags) { return (this.Flags & flags) != 0; } /// <summary> /// Returns whether the instruction (without considering child instructions) has at least one of the specified flags. /// </summary> public bool HasDirectFlag(InstructionFlags flags) { return (this.DirectFlags & flags) != 0; } protected void InvalidateFlags() { for (ILInstruction? inst = this; inst != null && inst.flags != invalidFlags; inst = inst.parent) inst.flags = invalidFlags; } protected abstract InstructionFlags ComputeFlags(); /// <summary> /// Gets the flags for this instruction only, without considering the child instructions. /// </summary> public abstract InstructionFlags DirectFlags { get; } /// <summary> /// Gets the ILRange for this instruction alone, ignoring the operands. /// </summary> private Interval ILRange; public void AddILRange(Interval newRange) { this.ILRange = CombineILRange(this.ILRange, newRange); } protected static Interval CombineILRange(Interval oldRange, Interval newRange) { if (oldRange.IsEmpty) { return newRange; } if (newRange.IsEmpty) { return oldRange; } if (newRange.Start <= oldRange.Start) { if (newRange.End < oldRange.Start) { return newRange; // use the earlier range } else { // join overlapping ranges return new Interval(newRange.Start, Math.Max(newRange.End, oldRange.End)); } } else if (newRange.Start <= oldRange.End) { // join overlapping ranges return new Interval(oldRange.Start, Math.Max(newRange.End, oldRange.End)); } return oldRange; } public void AddILRange(ILInstruction sourceInstruction) { AddILRange(sourceInstruction.ILRange); } public void SetILRange(ILInstruction sourceInstruction) { ILRange = sourceInstruction.ILRange; } public void SetILRange(Interval range) { ILRange = range; } public int StartILOffset => ILRange.Start; public int EndILOffset => ILRange.End; public bool ILRangeIsEmpty => ILRange.IsEmpty; public IEnumerable<Interval> ILRanges => new[] { ILRange }; public void WriteILRange(ITextOutput output, ILAstWritingOptions options) { ILRange.WriteTo(output, options); } /// <summary> /// Writes the ILAst to the text output. /// </summary> public abstract void WriteTo(ITextOutput output, ILAstWritingOptions options); public override string ToString() { var output = new PlainTextOutput(); WriteTo(output, new ILAstWritingOptions()); if (!ILRange.IsEmpty) { output.Write(" at IL_" + ILRange.Start.ToString("x4")); } return output.ToString(); } /// <summary> /// Calls the Visit*-method on the visitor corresponding to the concrete type of this instruction. /// </summary> public abstract void AcceptVisitor(ILVisitor visitor); /// <summary> /// Calls the Visit*-method on the visitor corresponding to the concrete type of this instruction. /// </summary> public abstract T AcceptVisitor<T>(ILVisitor<T> visitor); /// <summary> /// Calls the Visit*-method on the visitor corresponding to the concrete type of this instruction. /// </summary> public abstract T AcceptVisitor<C, T>(ILVisitor<C, T> visitor, C context); /// <summary> /// Gets the child nodes of this instruction. /// </summary> /// <remarks> /// The ChildrenCollection does not actually store the list of children, /// it merely allows accessing the children stored in the various slots. /// </remarks> public ChildrenCollection Children { get { return new ChildrenCollection(this); } } protected abstract int GetChildCount(); protected abstract ILInstruction GetChild(int index); protected abstract void SetChild(int index, ILInstruction value); protected abstract SlotInfo GetChildSlot(int index); #region ChildrenCollection + ChildrenEnumerator public readonly struct ChildrenCollection : IReadOnlyList<ILInstruction> { readonly ILInstruction inst; internal ChildrenCollection(ILInstruction inst) { Debug.Assert(inst != null); this.inst = inst!; } public int Count { get { return inst.GetChildCount(); } } public ILInstruction this[int index] { get { return inst.GetChild(index); } set { inst.SetChild(index, value); } } public ChildrenEnumerator GetEnumerator() { return new ChildrenEnumerator(inst); } IEnumerator<ILInstruction> IEnumerable<ILInstruction>.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } #if DEBUG int activeEnumerators; [Conditional("DEBUG")] internal void StartEnumerator() { activeEnumerators++; } [Conditional("DEBUG")] internal void StopEnumerator() { Debug.Assert(activeEnumerators > 0); activeEnumerators--; } #endif [Conditional("DEBUG")] internal void AssertNoEnumerators() { #if DEBUG Debug.Assert(activeEnumerators == 0); #endif } /// <summary> /// Enumerator over the children of an ILInstruction. /// 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 ChildrenEnumerator : IEnumerator<ILInstruction> { ILInstruction? inst; readonly int end; int pos; internal ChildrenEnumerator(ILInstruction inst) { DebugAssert(inst != null); this.inst = inst; this.pos = -1; this.end = inst!.GetChildCount(); #if DEBUG inst.StartEnumerator(); #endif } public ILInstruction Current { get { return inst!.GetChild(pos); } } public bool MoveNext() { return ++pos < end; } public void Dispose() { #if DEBUG if (inst != null) { inst.StopEnumerator(); inst = null; } #endif } object System.Collections.IEnumerator.Current { get { return this.Current; } } void System.Collections.IEnumerator.Reset() { pos = -1; } } #endregion /// <summary> /// Replaces this ILInstruction with the given replacement instruction. /// </summary> /// <remarks> /// It is temporarily possible for a node to be used in multiple places in the ILAst, /// this method only replaces this node at its primary position (see remarks on <see cref="Parent"/>). /// /// This means you cannot use ReplaceWith() to wrap an instruction in another node. /// For example, <c>node.ReplaceWith(new BitNot(node))</c> will first call the BitNot constructor, /// which sets <c>node.Parent</c> to the BitNot instance. /// The ReplaceWith() call then attempts to set <c>BitNot.Argument</c> to the BitNot instance, /// which creates a cyclic ILAst. Meanwhile, node's original parent remains unmodified. /// /// The solution in this case is to avoid using <c>ReplaceWith</c>. /// If the parent node is unknown, the following trick can be used: /// <code> /// node.Parent.Children[node.ChildIndex] = new BitNot(node); /// </code> /// Unlike the <c>ReplaceWith()</c> call, this will evaluate <c>node.Parent</c> and <c>node.ChildIndex</c> /// before the <c>BitNot</c> constructor is called, thus modifying the expected position in the ILAst. /// </remarks> public void ReplaceWith(ILInstruction replacement) { Debug.Assert(parent!.GetChild(ChildIndex) == this); if (replacement == this) return; parent.SetChild(ChildIndex, replacement); } /// <summary> /// Returns all descendants of the ILInstruction in post-order. /// (including the ILInstruction itself) /// </summary> /// <remarks> /// Within a loop 'foreach (var node in inst.Descendants)', it is illegal to /// add or remove from the child collections of node's ancestors, as those are /// currently being enumerated. /// Note that it is valid to modify node's children as those were already previously visited. /// As a special case, it is also allowed to replace node itself with another node. /// </remarks> public IEnumerable<ILInstruction> Descendants { get { // Copy of TreeTraversal.PostOrder() specialized for ChildrenEnumerator // We could potentially eliminate the stack by using Parent/ChildIndex, // but that makes it difficult to reason about the behavior in the cases // where Parent/ChildIndex is not accurate (stale positions), especially // if the ILAst is modified during enumeration. Stack<ChildrenEnumerator> stack = new Stack<ChildrenEnumerator>(); ChildrenEnumerator enumerator = new ChildrenEnumerator(this); try { while (true) { while (enumerator.MoveNext()) { var element = enumerator.Current; stack.Push(enumerator); enumerator = new ChildrenEnumerator(element); } enumerator.Dispose(); if (stack.Count > 0) { enumerator = stack.Pop(); yield return enumerator.Current; } else { break; } } } finally { enumerator.Dispose(); while (stack.Count > 0) { stack.Pop().Dispose(); } } yield return this; } } /// <summary> /// Gets the ancestors of this node (including the node itself as first element). /// </summary> public IEnumerable<ILInstruction> Ancestors { get { for (ILInstruction? node = this; node != null; node = node.Parent) { yield return node; } } } /// <summary> /// Number of parents that refer to this instruction and are connected to the root. /// Usually is 0 for unconnected nodes and 1 for connected nodes, but may temporarily increase to 2 /// when the ILAst is re-arranged (e.g. within SetChildInstruction), /// or possibly even more (re-arrangement with stale positions). /// </summary> byte refCount; internal void AddRef() { if (refCount++ == 0) { Connected(); } } internal void ReleaseRef() { Debug.Assert(refCount > 0); if (--refCount == 0) { Disconnected(); } } /// <summary> /// Gets whether this ILInstruction is connected to the root node of the ILAst. /// </summary> /// <remarks> /// This property returns true if the ILInstruction is reachable from the root node /// of the ILAst; it does not make use of the <c>Parent</c> field so the considerations /// about orphaned nodes and stale positions don't apply. /// </remarks> protected internal bool IsConnected { get { return refCount > 0; } } /// <summary> /// Called after the ILInstruction was connected to the root node of the ILAst. /// </summary> protected virtual void Connected() { foreach (var child in Children) child.AddRef(); } /// <summary> /// Called after the ILInstruction was disconnected from the root node of the ILAst. /// </summary> protected virtual void Disconnected() { foreach (var child in Children) child.ReleaseRef(); } ILInstruction? parent; /// <summary> /// Gets the parent of this ILInstruction. /// </summary> /// <remarks> /// It is temporarily possible for a node to be used in multiple places in the ILAst /// (making the ILAst a DAG instead of a tree). /// The <c>Parent</c> and <c>ChildIndex</c> properties are written whenever /// a node is stored in a slot. /// The node's occurrence in that slot is termed the "primary position" of the node, /// and all other (older) uses of the nodes are termed "stale positions". /// /// A consistent ILAst must not contain any stale positions. /// Debug builds of ILSpy check the ILAst for consistency after every IL transform. /// /// If a slot containing a node is overwritten with another node, the <c>Parent</c> /// and <c>ChildIndex</c> of the old node are not modified. /// This allows overwriting stale positions to restore consistency of the ILAst. /// /// If a "primary position" is overwritten, the <c>Parent</c> of the old node also remains unmodified. /// This makes the old node an "orphaned node". /// Orphaned nodes may later be added back to the ILAst (or can just be garbage-collected). /// /// Note that is it is possible (though unusual) for a stale position to reference an orphaned node. /// </remarks> public ILInstruction? Parent { get { return parent; } } /// <summary> /// Gets the index of this node in the <c>Parent.Children</c> collection. /// </summary> /// <remarks> /// It is temporarily possible for a node to be used in multiple places in the ILAst, /// this property returns the index of the primary position of this node (see remarks on <see cref="Parent"/>). /// </remarks> public int ChildIndex { get; internal set; } = -1; /// <summary> /// Gets information about the slot in which this instruction is stored. /// (i.e., the relation of this instruction to its parent instruction) /// </summary> /// <remarks> /// It is temporarily possible for a node to be used in multiple places in the ILAst, /// this property returns the slot of the primary position of this node (see remarks on <see cref="Parent"/>). /// /// Precondition: this node must not be orphaned. /// </remarks> public SlotInfo? SlotInfo { get { if (parent == null) return null; Debug.Assert(parent.GetChild(this.ChildIndex) == this); return parent.GetChildSlot(this.ChildIndex); } } /// <summary> /// Replaces a child of this ILInstruction. /// </summary> /// <param name="childPointer">Reference to the field holding the child</param> /// <param name="newValue">New child</param> /// <param name="index">Index of the field in the Children collection</param> protected internal void SetChildInstruction<T>(ref T childPointer, T newValue, int index) where T : ILInstruction? { T oldValue = childPointer; Debug.Assert(oldValue == GetChild(index)); if (oldValue == newValue && newValue?.parent == this && newValue.ChildIndex == index) return; childPointer = newValue; if (newValue != null) { newValue.parent = this; newValue.ChildIndex = index; } InvalidateFlags(); MakeDirty(); if (refCount > 0) { // The new value may be a subtree of the old value. // We first call AddRef(), then ReleaseRef() to prevent the subtree // that stays connected from receiving a Disconnected() notification followed by a Connected() notification. if (newValue != null) newValue.AddRef(); if (oldValue != null) oldValue.ReleaseRef(); } } /// <summary> /// Called when a new child is added to a InstructionCollection. /// </summary> protected internal void InstructionCollectionAdded(ILInstruction newChild) { Debug.Assert(GetChild(newChild.ChildIndex) == newChild); Debug.Assert(!this.IsDescendantOf(newChild), "ILAst must form a tree"); // If a call to ReplaceWith() triggers the "ILAst must form a tree" assertion, // make sure to read the remarks on the ReplaceWith() method. newChild.parent = this; if (refCount > 0) newChild.AddRef(); } /// <summary> /// Called when a child is removed from a InstructionCollection. /// </summary> protected internal void InstructionCollectionRemoved(ILInstruction oldChild) { if (refCount > 0) oldChild.ReleaseRef(); } /// <summary> /// Called when a series of add/remove operations on the InstructionCollection is complete. /// </summary> protected internal virtual void InstructionCollectionUpdateComplete() { InvalidateFlags(); MakeDirty(); } /// <summary> /// Creates a deep clone of the ILInstruction. /// </summary> /// <remarks> /// It is valid to clone nodes with stale positions (see remarks on <c>Parent</c>); /// the result of such a clone will not contain any stale positions (nodes at /// multiple positions will be cloned once per position). /// </remarks> public abstract ILInstruction Clone(); /// <summary> /// Creates a shallow clone of the ILInstruction. /// </summary> /// <remarks> /// Like MemberwiseClone(), except that the new instruction starts as disconnected. /// </remarks> protected ILInstruction ShallowClone() { ILInstruction inst = (ILInstruction)MemberwiseClone(); // reset refCount and parent so that the cloned instruction starts as disconnected inst.refCount = 0; inst.parent = null; inst.flags = invalidFlags; #if DEBUG inst.activeEnumerators = 0; #endif return inst; } /// <summary> /// Attempts to match the specified node against the pattern. /// </summary> /// <c>this</c>: The syntactic pattern. /// <param name="node">The syntax node to test against the pattern.</param> /// <returns> /// Returns a match object describing the result of the matching operation. /// Check the <see cref="Match.Success"/> property to see whether the match was successful. /// For successful matches, the match object allows retrieving the nodes that were matched with the captured groups. /// </returns> public Match Match(ILInstruction node) { Match match = new Match(); match.Success = PerformMatch(node, ref match); return match; } /// <summary> /// Attempts matching this instruction against the other instruction. /// </summary> /// <param name="other">The instruction to compare with.</param> /// <param name="match">The match object, used to store global state during the match (such as the results of capture groups).</param> /// <returns>Returns whether the (partial) match was successful. /// If the method returns true, it adds the capture groups (if any) to the match. /// If the method returns false, the match object may remain in a partially-updated state and /// needs to be restored before it can be reused.</returns> protected internal abstract bool PerformMatch(ILInstruction? other, ref Match match); /// <summary> /// Attempts matching this instruction against a list of other instructions (or a part of said list). /// </summary> /// <param name="listMatch">Stores state about the current list match.</param> /// <param name="match">The match object, used to store global state during the match (such as the results of capture groups).</param> /// <returns>Returns whether the (partial) match was successful. /// If the method returns true, it updates listMatch.SyntaxIndex to point to the next node that was not part of the match, /// and adds the capture groups (if any) to the match. /// If the method returns false, the listMatch and match objects remain in a partially-updated state and need to be restored /// before they can be reused.</returns> protected internal virtual bool PerformMatch(ref ListMatch listMatch, ref Match match) { // Base implementation expects the node to match a single element. // Any patterns matching 0 or more than 1 element must override this method. if (listMatch.SyntaxIndex < listMatch.SyntaxList.Count) { if (PerformMatch(listMatch.SyntaxList[listMatch.SyntaxIndex], ref match)) { listMatch.SyntaxIndex++; return true; } } return false; } /// <summary> /// Extracts the this instruction. /// The instruction is replaced with a load of a new temporary variable; /// and the instruction is moved to a store to said variable at block-level. /// Returns the new variable. /// /// If extraction is not possible, the ILAst is left unmodified and the function returns null. /// May return null if extraction is not possible. /// </summary> public ILVariable Extract(ILTransformContext context) { return Transforms.ExtractionContext.Extract(this, context); } /// <summary> /// Prepares "extracting" a descendant instruction out of this instruction. /// This is the opposite of ILInlining. It may involve re-compiling high-level constructs into lower-level constructs. /// </summary> /// <returns>True if extraction is possible; false otherwise.</returns> internal virtual bool PrepareExtract(int childIndex, Transforms.ExtractionContext ctx) { if (!GetChildSlot(childIndex).CanInlineInto) { return false; } // Check whether re-ordering with predecessors is valid: for (int i = childIndex - 1; i >= 0; --i) { ILInstruction predecessor = GetChild(i); if (!GetChildSlot(i).CanInlineInto) { return false; } ctx.RegisterMoveIfNecessary(predecessor); } return true; } /// <summary> /// Gets whether the specified instruction may be inlined into the specified slot. /// Note: this does not check whether reordering with the previous slots is valid; only wheter the target slot supports inlining at all! /// </summary> internal virtual bool CanInlineIntoSlot(int childIndex, ILInstruction expressionBeingMoved) { return GetChildSlot(childIndex).CanInlineInto; } } public interface IInstructionWithTypeOperand { IType Type { get; } } public interface IInstructionWithFieldOperand { IField Field { get; } } public interface IInstructionWithMethodOperand { IMethod? Method { get; } } public interface ILiftableInstruction { /// <summary> /// Gets whether the instruction was lifted; that is, whether is accepts /// potentially nullable arguments. /// </summary> bool IsLifted { get; } /// <summary> /// If the instruction is lifted and returns a nullable result, /// gets the underlying result type. /// /// Note that not all lifted instructions return a nullable result: /// C# comparisons always return a bool! /// </summary> StackType UnderlyingResultType { get; } } }
ILSpy/ICSharpCode.Decompiler/IL/Instructions/ILInstruction.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/ILInstruction.cs", "repo_id": "ILSpy", "token_count": 10149 }
209
// 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. namespace ICSharpCode.Decompiler.IL.Transforms { class CombineExitsTransform : IILTransform { public void Run(ILFunction function, ILTransformContext context) { if (!(function.Body is BlockContainer container && container.Blocks.Count == 1)) return; var combinedExit = CombineExits(container.EntryPoint); if (combinedExit == null) return; ExpressionTransforms.RunOnSingleStatement(combinedExit, context); } static Leave CombineExits(Block block) { if (!(block.Instructions.SecondToLastOrDefault() is IfInstruction ifInst && block.Instructions.LastOrDefault() is Leave leaveElse)) return null; if (!ifInst.FalseInst.MatchNop()) return null; // try to unwrap true branch to single instruction: var trueInstruction = Block.Unwrap(ifInst.TrueInst); // if the true branch is a block with multiple instructions: // try to apply the combine exits transform to the nested block // and then continue on that transformed block. // Example: // if (cond) { // if (cond2) { // leave (value) // } // leave (value2) // } // leave (value3) // => // leave (if (cond) value else if (cond2) value2 else value3) if (trueInstruction is Block nestedBlock && nestedBlock.Instructions.Count == 2) trueInstruction = CombineExits(nestedBlock); if (!(trueInstruction is Leave leave)) return null; if (!(leave.IsLeavingFunction && leaveElse.IsLeavingFunction)) return null; if (leave.Value.MatchNop() || leaveElse.Value.MatchNop()) return null; // if (cond) { // leave (value) // } // leave (elseValue) // => // leave (if (cond) value else elseValue) IfInstruction value = new IfInstruction(ifInst.Condition, leave.Value, leaveElse.Value); value.AddILRange(ifInst); Leave combinedLeave = new Leave(leave.TargetContainer, value); combinedLeave.AddILRange(leaveElse); combinedLeave.AddILRange(leave); ifInst.ReplaceWith(combinedLeave); block.Instructions.RemoveAt(combinedLeave.ChildIndex + 1); return combinedLeave; } } }
ILSpy/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs", "repo_id": "ILSpy", "token_count": 1028 }
210
// 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. using System; using System.Collections.Generic; using System.Linq; namespace ICSharpCode.Decompiler.IL.Transforms { /// <summary> /// This transform duplicates return blocks if they return a local variable that was assigned right before the return. /// </summary> class InlineReturnTransform : IILTransform { public void Run(ILFunction function, ILTransformContext context) { var instructionsToModify = new List<(BlockContainer, Block, Branch)>(); // Process all leave instructions in a leave-block, that is a block consisting solely of a leave instruction. foreach (var leave in function.Descendants.OfType<Leave>()) { if (!(leave.Parent is Block leaveBlock && leaveBlock.Instructions.Count == 1)) continue; // Skip, if the leave instruction has no value or the value is not a load of a local variable. if (!leave.Value.MatchLdLoc(out var returnVar) || returnVar.Kind != VariableKind.Local) continue; // If all instructions can be modified, add item to the global list. if (CanModifyInstructions(returnVar, leaveBlock, out var list)) instructionsToModify.AddRange(list); } foreach (var (container, b, br) in instructionsToModify) { Block block = b; // if there is only one branch to this return block, move it to the matching container. // otherwise duplicate the return block. if (block.IncomingEdgeCount == 1) { block.Remove(); } else { block = (Block)block.Clone(); } container.Blocks.Add(block); // adjust the target of the branch to the newly created block. br.TargetBlock = block; } } /// <summary> /// Determines a list of all store instructions that write to a given <paramref name="returnVar"/>. /// Returns false if any of these instructions does not meet the following criteria: /// - must be a stloc /// - must be a direct child of a block /// - must be the penultimate instruction /// - must be followed by a branch instruction to <paramref name="leaveBlock"/> /// - must have a BlockContainer as ancestor. /// Returns true, if all instructions meet these criteria, and <paramref name="instructionsToModify"/> contains a list of 3-tuples. /// Each tuple consists of the target block container, the leave block, and the branch instruction that should be modified. /// </summary> static bool CanModifyInstructions(ILVariable returnVar, Block leaveBlock, out List<(BlockContainer, Block, Branch)> instructionsToModify) { instructionsToModify = new List<(BlockContainer, Block, Branch)>(); foreach (var inst in returnVar.StoreInstructions) { if (!(inst is StLoc store)) return false; if (!(store.Parent is Block storeBlock)) return false; if (store.ChildIndex + 2 != storeBlock.Instructions.Count) return false; if (!(storeBlock.Instructions[store.ChildIndex + 1] is Branch br)) return false; if (br.TargetBlock != leaveBlock) return false; var targetBlockContainer = BlockContainer.FindClosestContainer(store); if (targetBlockContainer == null) return false; instructionsToModify.Add((targetBlockContainer, leaveBlock, br)); } return true; } } }
ILSpy/ICSharpCode.Decompiler/IL/Transforms/InlineReturnTransform.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/InlineReturnTransform.cs", "repo_id": "ILSpy", "token_count": 1331 }
211
// Copyright (c) 2016 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.Collections.Generic; using System.Linq; using ICSharpCode.Decompiler.FlowAnalysis; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.IL.Transforms { /// <summary> /// Remove <c>HasInitialValue</c> from locals that are definitely assigned before every use /// (=the initial value is a dead store). /// /// In yield return generators, additionally removes dead 'V = null;' assignments. /// /// Additionally infers IType of stack slots that have StackType.Ref /// </summary> public class RemoveDeadVariableInit : IILTransform { public void Run(ILFunction function, ILTransformContext context) { ResetUsesInitialValueFlag(function, context); // Remove dead stores to variables that are never read from. // If the stored value has some side-effect, the value is unwrapped. // This is necessary to remove useless stores generated by some compilers, e.g., the F# compiler. // In yield return + async, the C# compiler tends to store null/default(T) to variables // when the variable goes out of scope. bool removeDeadStores = function.IsAsync || function.IsIterator || context.Settings.RemoveDeadStores; var variableQueue = new Queue<ILVariable>(function.Variables); while (variableQueue.Count > 0) { var v = variableQueue.Dequeue(); if (v.Kind != VariableKind.Local && v.Kind != VariableKind.StackSlot) continue; if (!(v.RemoveIfRedundant || removeDeadStores)) continue; // Skip variables that are captured in a mcs yield state-machine // loads of these will only be visible after DelegateConstruction step. if (function.StateMachineCompiledWithMono && v.StateMachineField != null) continue; if (v.LoadCount != 0 || v.AddressCount != 0) continue; foreach (var stloc in v.StoreInstructions.OfType<StLoc>().ToArray()) { if (stloc.Parent is Block block) { context.Step($"Dead store to {v.Name}", stloc); if (SemanticHelper.IsPure(stloc.Value.Flags)) { block.Instructions.Remove(stloc); } else { stloc.ReplaceWith(stloc.Value); } if (stloc.Value is LdLoc ldloc) { variableQueue.Enqueue(ldloc.Variable); } } } } // Try to infer IType of stack slots that are of StackType.Ref: foreach (var v in function.Variables) { if (v.Kind == VariableKind.StackSlot && v.StackType == StackType.Ref && v.AddressCount == 0) { IType newType = null; // Multiple store are possible in case of (c ? ref a : ref b) += 1, for example. foreach (var stloc in v.StoreInstructions.OfType<StLoc>()) { var inferredType = stloc.Value.InferType(context.TypeSystem); // cancel, if types of values do not match exactly if (newType != null && !newType.Equals(inferredType)) { newType = SpecialType.UnknownType; break; } newType = inferredType; } // Only overwrite existing type, if a "better" type was found. if (newType != null && newType != SpecialType.UnknownType) v.Type = newType; } } } internal static void ResetUsesInitialValueFlag(ILFunction function, ILTransformContext context) { var visitor = new DefiniteAssignmentVisitor(function, context.CancellationToken); function.AcceptVisitor(visitor); foreach (var v in function.Variables) { if (v.Kind != VariableKind.Parameter && !visitor.IsPotentiallyUsedUninitialized(v)) { v.UsesInitialValue = false; } } } } }
ILSpy/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs", "repo_id": "ILSpy", "token_count": 1603 }
212
// 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. #nullable enable using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace ICSharpCode.Decompiler.Metadata { public sealed class ResolutionException : Exception { public IAssemblyReference? Reference { get; } public string? ModuleName { get; } public string? MainModuleFullPath { get; } public string? ResolvedFullPath { get; } public ResolutionException(IAssemblyReference reference, string? resolvedPath, Exception? innerException) : base($"Failed to resolve assembly: '{reference}'{Environment.NewLine}" + $"Resolve result: {resolvedPath ?? "<not found>"}", innerException) { this.Reference = reference ?? throw new ArgumentNullException(nameof(reference)); this.ResolvedFullPath = resolvedPath; } public ResolutionException(string mainModule, string moduleName, string? resolvedPath, Exception? innerException) : base($"Failed to resolve module: '{moduleName} of {mainModule}'{Environment.NewLine}" + $"Resolve result: {resolvedPath ?? "<not found>"}", innerException) { this.MainModuleFullPath = mainModule ?? throw new ArgumentNullException(nameof(mainModule)); this.ModuleName = moduleName ?? throw new ArgumentNullException(nameof(moduleName)); this.ResolvedFullPath = resolvedPath; } } public interface IAssemblyResolver { #if !VSADDIN PEFile? Resolve(IAssemblyReference reference); PEFile? ResolveModule(PEFile mainModule, string moduleName); Task<PEFile?> ResolveAsync(IAssemblyReference reference); Task<PEFile?> ResolveModuleAsync(PEFile mainModule, string moduleName); #endif } public class AssemblyReferenceClassifier { /// <summary> /// For GAC assembly references, the WholeProjectDecompiler will omit the HintPath in the /// generated .csproj file. /// </summary> public virtual bool IsGacAssembly(IAssemblyReference reference) { return UniversalAssemblyResolver.GetAssemblyInGac(reference) != null; } /// <summary> /// For .NET Core framework references, the WholeProjectDecompiler will omit the /// assembly reference if the runtimePack is already included as an SDK. /// </summary> public virtual bool IsSharedAssembly(IAssemblyReference reference, [NotNullWhen(true)] out string? runtimePack) { runtimePack = null; return false; } } public interface IAssemblyReference { string Name { get; } string FullName { get; } Version? Version { get; } string? Culture { get; } byte[]? PublicKeyToken { get; } bool IsWindowsRuntime { get; } bool IsRetargetable { get; } } public class AssemblyNameReference : IAssemblyReference { string? fullName; public string Name { get; private set; } = string.Empty; public string FullName { get { if (fullName != null) return fullName; const string sep = ", "; var builder = new StringBuilder(); builder.Append(Name); builder.Append(sep); builder.Append("Version="); builder.Append((Version ?? UniversalAssemblyResolver.ZeroVersion).ToString(fieldCount: 4)); builder.Append(sep); builder.Append("Culture="); builder.Append(string.IsNullOrEmpty(Culture) ? "neutral" : Culture); builder.Append(sep); builder.Append("PublicKeyToken="); var pk_token = PublicKeyToken; if (pk_token != null && pk_token.Length > 0) { for (int i = 0; i < pk_token.Length; i++) { builder.Append(pk_token[i].ToString("x2")); } } else builder.Append("null"); if (IsRetargetable) { builder.Append(sep); builder.Append("Retargetable=Yes"); } return fullName = builder.ToString(); } } public Version? Version { get; private set; } public string? Culture { get; private set; } public byte[]? PublicKeyToken { get; private set; } public bool IsWindowsRuntime { get; private set; } public bool IsRetargetable { get; private set; } public static AssemblyNameReference Parse(string fullName) { if (fullName == null) throw new ArgumentNullException(nameof(fullName)); if (fullName.Length == 0) throw new ArgumentException("Name can not be empty"); var name = new AssemblyNameReference(); var tokens = fullName.Split(','); for (int i = 0; i < tokens.Length; i++) { var token = tokens[i].Trim(); if (i == 0) { name.Name = token; continue; } var parts = token.Split('='); if (parts.Length != 2) throw new ArgumentException("Malformed name"); switch (parts[0].ToLowerInvariant()) { case "version": name.Version = new Version(parts[1]); break; case "culture": name.Culture = parts[1] == "neutral" ? "" : parts[1]; break; case "publickeytoken": var pk_token = parts[1]; if (pk_token == "null") break; name.PublicKeyToken = new byte[pk_token.Length / 2]; for (int j = 0; j < name.PublicKeyToken.Length; j++) name.PublicKeyToken[j] = Byte.Parse(pk_token.Substring(j * 2, 2), System.Globalization.NumberStyles.HexNumber); break; } } return name; } public override string ToString() { return FullName; } } #if !VSADDIN public class AssemblyReference : IAssemblyReference { static readonly SHA1 sha1 = SHA1.Create(); readonly System.Reflection.Metadata.AssemblyReference entry; public MetadataReader Metadata { get; } public AssemblyReferenceHandle Handle { get; } public bool IsWindowsRuntime => (entry.Flags & AssemblyFlags.WindowsRuntime) != 0; public bool IsRetargetable => (entry.Flags & AssemblyFlags.Retargetable) != 0; string? name; string? fullName; public string Name { get { if (name == null) { try { name = Metadata.GetString(entry.Name); } catch (BadImageFormatException) { name = $"AR:{Handle}"; } } return name; } } public string FullName { get { if (fullName == null) { try { fullName = entry.GetFullAssemblyName(Metadata); } catch (BadImageFormatException) { fullName = $"fullname(AR:{Handle})"; } } return fullName; } } public Version? Version => entry.Version; public string Culture => Metadata.GetString(entry.Culture); byte[]? IAssemblyReference.PublicKeyToken => GetPublicKeyToken(); public byte[]? GetPublicKeyToken() { if (entry.PublicKeyOrToken.IsNil) return null; var bytes = Metadata.GetBlobBytes(entry.PublicKeyOrToken); if ((entry.Flags & AssemblyFlags.PublicKey) != 0) { return sha1.ComputeHash(bytes).Skip(12).ToArray(); } return bytes; } ImmutableArray<TypeReferenceMetadata> typeReferences; public ImmutableArray<TypeReferenceMetadata> TypeReferences { get { var value = typeReferences; if (value.IsDefault) { value = Metadata.TypeReferences .Select(r => new TypeReferenceMetadata(Metadata, r)) .Where(r => r.ResolutionScope == Handle) .OrderBy(r => r.Namespace) .ThenBy(r => r.Name) .ToImmutableArray(); typeReferences = value; } return value; } } ImmutableArray<ExportedTypeMetadata> exportedTypes; public ImmutableArray<ExportedTypeMetadata> ExportedTypes { get { var value = exportedTypes; if (value.IsDefault) { value = Metadata.ExportedTypes .Select(r => new ExportedTypeMetadata(Metadata, r)) .Where(r => r.Implementation == Handle) .OrderBy(r => r.Namespace) .ThenBy(r => r.Name) .ToImmutableArray(); exportedTypes = value; } return value; } } public AssemblyReference(MetadataReader metadata, AssemblyReferenceHandle handle) { if (metadata == null) throw new ArgumentNullException(nameof(metadata)); if (handle.IsNil) throw new ArgumentNullException(nameof(handle)); Metadata = metadata; Handle = handle; entry = metadata.GetAssemblyReference(handle); } public AssemblyReference(PEFile module, AssemblyReferenceHandle handle) { if (module == null) throw new ArgumentNullException(nameof(module)); if (handle.IsNil) throw new ArgumentNullException(nameof(handle)); Metadata = module.Metadata; Handle = handle; entry = Metadata.GetAssemblyReference(handle); } public override string ToString() { return FullName; } } #endif }
ILSpy/ICSharpCode.Decompiler/Metadata/AssemblyReferences.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/AssemblyReferences.cs", "repo_id": "ILSpy", "token_count": 3469 }
213
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace LightJson.Serialization { using System; using System.Globalization; using System.IO; using System.Text; using ErrorType = JsonParseException.ErrorType; /// <summary> /// Represents a reader that can read JsonValues. /// </summary> internal sealed class JsonReader { private TextScanner scanner; private JsonReader(TextReader reader) { this.scanner = new TextScanner(reader); } /// <summary> /// Creates a JsonValue by using the given TextReader. /// </summary> /// <param name="reader">The TextReader used to read a JSON message.</param> /// <returns>The parsed <see cref="JsonValue"/>.</returns> public static JsonValue Parse(TextReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return new JsonReader(reader).Parse(); } /// <summary> /// Creates a JsonValue by reader the JSON message in the given string. /// </summary> /// <param name="source">The string containing the JSON message.</param> /// <returns>The parsed <see cref="JsonValue"/>.</returns> public static JsonValue Parse(string source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } using (var reader = new StringReader(source)) { return Parse(reader); } } private string ReadJsonKey() { return this.ReadString(); } private JsonValue ReadJsonValue() { this.scanner.SkipWhitespace(); var next = this.scanner.Peek(); if (char.IsNumber(next)) { return this.ReadNumber(); } switch (next) { case '{': return this.ReadObject(); case '[': return this.ReadArray(); case '"': return this.ReadString(); case '-': return this.ReadNumber(); case 't': case 'f': return this.ReadBoolean(); case 'n': return this.ReadNull(); default: throw new JsonParseException( ErrorType.InvalidOrUnexpectedCharacter, this.scanner.Position); } } private JsonValue ReadNull() { this.scanner.Assert("null"); return JsonValue.Null; } private JsonValue ReadBoolean() { switch (this.scanner.Peek()) { case 't': this.scanner.Assert("true"); return true; default: this.scanner.Assert("false"); return false; } } private void ReadDigits(StringBuilder builder) { while (true) { int next = this.scanner.Peek(throwAtEndOfFile: false); if (next == -1 || !char.IsNumber((char)next)) { return; } builder.Append(this.scanner.Read()); } } private JsonValue ReadNumber() { var builder = new StringBuilder(); if (this.scanner.Peek() == '-') { builder.Append(this.scanner.Read()); } if (this.scanner.Peek() == '0') { builder.Append(this.scanner.Read()); } else { this.ReadDigits(builder); } if (this.scanner.Peek(throwAtEndOfFile: false) == '.') { builder.Append(this.scanner.Read()); this.ReadDigits(builder); } if (this.scanner.Peek(throwAtEndOfFile: false) == 'e' || this.scanner.Peek(throwAtEndOfFile: false) == 'E') { builder.Append(this.scanner.Read()); var next = this.scanner.Peek(); switch (next) { case '+': case '-': builder.Append(this.scanner.Read()); break; } this.ReadDigits(builder); } return double.Parse( builder.ToString(), CultureInfo.InvariantCulture); } private string ReadString() { var builder = new StringBuilder(); this.scanner.Assert('"'); while (true) { var errorPosition = this.scanner.Position; var c = this.scanner.Read(); if (c == '\\') { errorPosition = this.scanner.Position; c = this.scanner.Read(); switch (char.ToLower(c)) { case '"': case '\\': case '/': builder.Append(c); break; case 'b': builder.Append('\b'); break; case 'f': builder.Append('\f'); break; case 'n': builder.Append('\n'); break; case 'r': builder.Append('\r'); break; case 't': builder.Append('\t'); break; case 'u': builder.Append(this.ReadUnicodeLiteral()); break; default: throw new JsonParseException( ErrorType.InvalidOrUnexpectedCharacter, errorPosition); } } else if (c == '"') { break; } else { if (char.IsControl(c)) { throw new JsonParseException( ErrorType.InvalidOrUnexpectedCharacter, errorPosition); } else { builder.Append(c); } } } return builder.ToString(); } private int ReadHexDigit() { var errorPosition = this.scanner.Position; switch (char.ToUpper(this.scanner.Read())) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'A': return 10; case 'B': return 11; case 'C': return 12; case 'D': return 13; case 'E': return 14; case 'F': return 15; default: throw new JsonParseException( ErrorType.InvalidOrUnexpectedCharacter, errorPosition); } } private char ReadUnicodeLiteral() { int value = 0; value += this.ReadHexDigit() * 4096; // 16^3 value += this.ReadHexDigit() * 256; // 16^2 value += this.ReadHexDigit() * 16; // 16^1 value += this.ReadHexDigit(); // 16^0 return (char)value; } private JsonObject ReadObject() { return this.ReadObject(new JsonObject()); } private JsonObject ReadObject(JsonObject jsonObject) { this.scanner.Assert('{'); this.scanner.SkipWhitespace(); if (this.scanner.Peek() == '}') { this.scanner.Read(); } else { while (true) { this.scanner.SkipWhitespace(); var errorPosition = this.scanner.Position; var key = this.ReadJsonKey(); if (jsonObject.ContainsKey(key)) { throw new JsonParseException( ErrorType.DuplicateObjectKeys, errorPosition); } this.scanner.SkipWhitespace(); this.scanner.Assert(':'); this.scanner.SkipWhitespace(); var value = this.ReadJsonValue(); jsonObject.Add(key, value); this.scanner.SkipWhitespace(); errorPosition = this.scanner.Position; var next = this.scanner.Read(); if (next == ',') { // Allow trailing commas in objects this.scanner.SkipWhitespace(); if (this.scanner.Peek() == '}') { next = this.scanner.Read(); } } if (next == '}') { break; } else if (next == ',') { continue; } else { throw new JsonParseException( ErrorType.InvalidOrUnexpectedCharacter, errorPosition); } } } return jsonObject; } private JsonArray ReadArray() { return this.ReadArray(new JsonArray()); } private JsonArray ReadArray(JsonArray jsonArray) { this.scanner.Assert('['); this.scanner.SkipWhitespace(); if (this.scanner.Peek() == ']') { this.scanner.Read(); } else { while (true) { this.scanner.SkipWhitespace(); var value = this.ReadJsonValue(); jsonArray.Add(value); this.scanner.SkipWhitespace(); var errorPosition = this.scanner.Position; var next = this.scanner.Read(); if (next == ',') { // Allow trailing commas in arrays this.scanner.SkipWhitespace(); if (this.scanner.Peek() == ']') { next = this.scanner.Read(); } } if (next == ']') { break; } else if (next == ',') { continue; } else { throw new JsonParseException( ErrorType.InvalidOrUnexpectedCharacter, errorPosition); } } } return jsonArray; } private JsonValue Parse() { this.scanner.SkipWhitespace(); return this.ReadJsonValue(); } } }
ILSpy/ICSharpCode.Decompiler/Metadata/LightJson/Serialization/JsonReader.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/LightJson/Serialization/JsonReader.cs", "repo_id": "ILSpy", "token_count": 3950 }
214
// Copyright (c) 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; namespace ICSharpCode.Decompiler.TypeSystem { public struct AssemblyQualifiedTypeName : IEquatable<AssemblyQualifiedTypeName> { public readonly string AssemblyName; public readonly FullTypeName TypeName; public AssemblyQualifiedTypeName(FullTypeName typeName, string assemblyName) { this.AssemblyName = assemblyName; this.TypeName = typeName; } public AssemblyQualifiedTypeName(ITypeDefinition typeDefinition) { this.AssemblyName = typeDefinition.ParentModule.AssemblyName; this.TypeName = typeDefinition.FullTypeName; } public override string ToString() { if (string.IsNullOrEmpty(AssemblyName)) return TypeName.ToString(); else return TypeName.ToString() + ", " + AssemblyName; } public override bool Equals(object obj) { return (obj is AssemblyQualifiedTypeName) && Equals((AssemblyQualifiedTypeName)obj); } public bool Equals(AssemblyQualifiedTypeName other) { return this.AssemblyName == other.AssemblyName && this.TypeName == other.TypeName; } public override int GetHashCode() { int hashCode = 0; unchecked { if (AssemblyName != null) hashCode += 1000000007 * AssemblyName.GetHashCode(); hashCode += TypeName.GetHashCode(); } return hashCode; } public static bool operator ==(AssemblyQualifiedTypeName lhs, AssemblyQualifiedTypeName rhs) { return lhs.Equals(rhs); } public static bool operator !=(AssemblyQualifiedTypeName lhs, AssemblyQualifiedTypeName rhs) { return !lhs.Equals(rhs); } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs", "repo_id": "ILSpy", "token_count": 829 }
215
// 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 using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// Provider used for interning. /// </summary> /// <remarks> /// A simple IInterningProvider implementation could use 3 dictionaries: /// 1. using value equality comparer (for certain types known to implement value equality, e.g. string and IType) /// 2. using comparer that calls into ISupportsInterning (for types implementing ISupportsInterning) /// 3. list comparer (for InternList method) /// /// On the first Intern()-call, the provider tells the object to prepare for interning (ISupportsInterning.PrepareForInterning) /// and stores it into a dictionary. On further Intern() calls, the original object is returned for all equal objects. /// This allows reducing the memory usage by using a single object instance where possible. /// /// Interning provider implementations could also use the interning logic for different purposes: /// for example, it could be used to determine which objects are used jointly between multiple type definitions /// and which are used only within a single type definition. Then a persistent file format could be organized so /// that shared objects are loaded only once, yet non-shared objects get loaded lazily together with the class. /// </remarks> public abstract class InterningProvider { public static readonly InterningProvider Dummy = new DummyInterningProvider(); /// <summary> /// Interns the specified object. /// /// If the object is freezable, it will be frozen. /// </summary> [return: NotNullIfNotNull("obj")] public abstract ISupportsInterning? Intern(ISupportsInterning? obj); /// <summary> /// Interns the specified object. /// /// If the object is freezable, it will be frozen. /// </summary> [return: NotNullIfNotNull("obj")] public T? Intern<T>(T? obj) where T : class, ISupportsInterning { ISupportsInterning? input = obj; return (T?)Intern(input); } /// <summary> /// Interns the specified string. /// </summary> [return: NotNullIfNotNull("text")] public abstract string? Intern(string? text); /// <summary> /// Inters a boxed value type. /// </summary> [return: NotNullIfNotNull("obj")] public abstract object? InternValue(object? obj); /// <summary> /// Interns the given list. Uses reference equality to compare the list elements. /// </summary> [return: NotNullIfNotNull("list")] public abstract IList<T>? InternList<T>(IList<T>? list) where T : class; sealed class DummyInterningProvider : InterningProvider { public override ISupportsInterning? Intern(ISupportsInterning? obj) { return obj; } public override string? Intern(string? text) { return text; } public override object? InternValue(object? obj) { return obj; } public override IList<T>? InternList<T>(IList<T>? list) { return list; } } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/IInterningProvider.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/IInterningProvider.cs", "repo_id": "ILSpy", "token_count": 1223 }
216
// 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.Collections.ObjectModel; using System.Linq; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.TypeSystem.Implementation { public static class FreezableHelper { public static void ThrowIfFrozen(IFreezable freezable) { if (freezable.IsFrozen) throw new InvalidOperationException("Cannot mutate frozen " + freezable.GetType().Name); } public static IList<T> FreezeListAndElements<T>(IList<T> list) { if (list != null) { foreach (T item in list) Freeze(item); } return FreezeList(list); } public static IList<T> FreezeList<T>(IList<T> list) { if (list == null || list.Count == 0) return EmptyList<T>.Instance; if (list.IsReadOnly) { // If the list is already read-only, return it directly. // This is important, otherwise we might undo the effects of interning. return list; } else { return new ReadOnlyCollection<T>(list.ToArray()); } } public static void Freeze(object item) { IFreezable f = item as IFreezable; if (f != null) f.Freeze(); } public static T FreezeAndReturn<T>(T item) where T : IFreezable { item.Freeze(); return item; } /// <summary> /// If the item is not frozen, this method creates and returns a frozen clone. /// If the item is already frozen, it is returned without creating a clone. /// </summary> public static T GetFrozenClone<T>(T item) where T : IFreezable, ICloneable { if (!item.IsFrozen) { item = (T)item.Clone(); item.Freeze(); } return item; } } [Serializable] public abstract class AbstractFreezable : IFreezable { bool isFrozen; /// <summary> /// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe. /// </summary> public bool IsFrozen { get { return isFrozen; } } /// <summary> /// Freezes this instance. /// </summary> public void Freeze() { if (!isFrozen) { FreezeInternal(); isFrozen = true; } } protected virtual void FreezeInternal() { } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs", "repo_id": "ILSpy", "token_count": 1125 }
217
// 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.Util; namespace ICSharpCode.Decompiler.TypeSystem.Implementation { /// <summary> /// Provides helper methods for implementing GetMembers() on IType-implementations. /// Note: GetMembersHelper will recursively call back into IType.GetMembers(), but only with /// both GetMemberOptions.IgnoreInheritedMembers and GetMemberOptions.ReturnMemberDefinitions set, /// and only the 'simple' overloads (not taking type arguments). /// /// Ensure that your IType implementation does not use the GetMembersHelper if both flags are set, /// otherwise you'll get a StackOverflowException! /// </summary> static class GetMembersHelper { #region GetNestedTypes public static IEnumerable<IType> GetNestedTypes(IType type, Predicate<ITypeDefinition> filter, GetMemberOptions options) { return GetNestedTypes(type, null, filter, options); } public static IEnumerable<IType> GetNestedTypes(IType type, IReadOnlyList<IType> nestedTypeArguments, Predicate<ITypeDefinition> filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { return GetNestedTypesImpl(type, nestedTypeArguments, filter, options); } else { return type.GetNonInterfaceBaseTypes().SelectMany(t => GetNestedTypesImpl(t, nestedTypeArguments, filter, options)); } } static IEnumerable<IType> GetNestedTypesImpl(IType outerType, IReadOnlyList<IType> nestedTypeArguments, Predicate<ITypeDefinition> filter, GetMemberOptions options) { ITypeDefinition outerTypeDef = outerType.GetDefinition(); if (outerTypeDef == null) yield break; int outerTypeParameterCount = outerTypeDef.TypeParameterCount; ParameterizedType pt = outerType as ParameterizedType; foreach (ITypeDefinition nestedType in outerTypeDef.NestedTypes) { int totalTypeParameterCount = nestedType.TypeParameterCount; if (nestedTypeArguments != null) { if (totalTypeParameterCount - outerTypeParameterCount != nestedTypeArguments.Count) continue; } if (!(filter == null || filter(nestedType))) continue; if (totalTypeParameterCount == 0 || (options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) { yield return nestedType; } else { // We need to parameterize the nested type IType[] newTypeArguments = new IType[totalTypeParameterCount]; for (int i = 0; i < outerTypeParameterCount; i++) { newTypeArguments[i] = pt != null ? pt.GetTypeArgument(i) : outerTypeDef.TypeParameters[i]; } for (int i = outerTypeParameterCount; i < totalTypeParameterCount; i++) { if (nestedTypeArguments != null) newTypeArguments[i] = nestedTypeArguments[i - outerTypeParameterCount]; else newTypeArguments[i] = SpecialType.UnboundTypeArgument; } yield return new ParameterizedType(nestedType, newTypeArguments); } } } #endregion #region GetMethods public static IEnumerable<IMethod> GetMethods(IType type, Predicate<IMethod> filter, GetMemberOptions options) { return GetMethods(type, null, filter, options); } public static IEnumerable<IMethod> GetMethods(IType type, IReadOnlyList<IType> typeArguments, Predicate<IMethod> filter, GetMemberOptions options) { if (typeArguments != null && typeArguments.Count > 0) { filter = FilterTypeParameterCount(typeArguments.Count).And(filter); } if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { return GetMethodsImpl(type, typeArguments, filter, options); } else { return type.GetNonInterfaceBaseTypes().SelectMany(t => GetMethodsImpl(t, typeArguments, filter, options)); } } static Predicate<IMethod> FilterTypeParameterCount(int expectedTypeParameterCount) { return m => m.TypeParameters.Count == expectedTypeParameterCount; } const GetMemberOptions declaredMembers = GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions; static IEnumerable<IMethod> GetMethodsImpl(IType baseType, IReadOnlyList<IType> methodTypeArguments, Predicate<IMethod> filter, GetMemberOptions options) { IEnumerable<IMethod> declaredMethods = baseType.GetMethods(filter, options | declaredMembers); ParameterizedType pt = baseType as ParameterizedType; if ((options & GetMemberOptions.ReturnMemberDefinitions) == 0 && (pt != null || (methodTypeArguments != null && methodTypeArguments.Count > 0))) { TypeParameterSubstitution substitution = null; foreach (IMethod m in declaredMethods) { if (methodTypeArguments != null && methodTypeArguments.Count > 0) { if (m.TypeParameters.Count != methodTypeArguments.Count) continue; } if (substitution == null) { if (pt != null) substitution = pt.GetSubstitution(methodTypeArguments); else substitution = new TypeParameterSubstitution(null, methodTypeArguments); } yield return new SpecializedMethod(m, substitution); } } else { foreach (IMethod m in declaredMethods) { yield return m; } } } #endregion #region GetAccessors public static IEnumerable<IMethod> GetAccessors(IType type, Predicate<IMethod> filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { return GetAccessorsImpl(type, filter, options); } else { return type.GetNonInterfaceBaseTypes().SelectMany(t => GetAccessorsImpl(t, filter, options)); } } static IEnumerable<IMethod> GetAccessorsImpl(IType baseType, Predicate<IMethod> filter, GetMemberOptions options) { return GetConstructorsOrAccessorsImpl(baseType, baseType.GetAccessors(filter, options | declaredMembers), options); } #endregion #region GetConstructors public static IEnumerable<IMethod> GetConstructors(IType type, Predicate<IMethod> filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { return GetConstructorsImpl(type, filter, options); } else { return type.GetNonInterfaceBaseTypes().SelectMany(t => GetConstructorsImpl(t, filter, options)); } } static IEnumerable<IMethod> GetConstructorsImpl(IType baseType, Predicate<IMethod> filter, GetMemberOptions options) { return GetConstructorsOrAccessorsImpl(baseType, baseType.GetConstructors(filter, options | declaredMembers), options); } static IEnumerable<IMethod> GetConstructorsOrAccessorsImpl(IType baseType, IEnumerable<IMethod> declaredMembers, GetMemberOptions options) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) { return declaredMembers; } ParameterizedType pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); return declaredMembers.Select(m => new SpecializedMethod(m, substitution) { DeclaringType = pt }); } else { return declaredMembers; } } #endregion #region GetProperties public static IEnumerable<IProperty> GetProperties(IType type, Predicate<IProperty> filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { return GetPropertiesImpl(type, filter, options); } else { return type.GetNonInterfaceBaseTypes().SelectMany(t => GetPropertiesImpl(t, filter, options)); } } static IEnumerable<IProperty> GetPropertiesImpl(IType baseType, Predicate<IProperty> filter, GetMemberOptions options) { IEnumerable<IProperty> declaredProperties = baseType.GetProperties(filter, options | declaredMembers); if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) { return declaredProperties; } ParameterizedType pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); return declaredProperties.Select(m => new SpecializedProperty(m, substitution) { DeclaringType = pt }); } else { return declaredProperties; } } #endregion #region GetFields public static IEnumerable<IField> GetFields(IType type, Predicate<IField> filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { return GetFieldsImpl(type, filter, options); } else { return type.GetNonInterfaceBaseTypes().SelectMany(t => GetFieldsImpl(t, filter, options)); } } static IEnumerable<IField> GetFieldsImpl(IType baseType, Predicate<IField> filter, GetMemberOptions options) { IEnumerable<IField> declaredFields = baseType.GetFields(filter, options | declaredMembers); if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) { return declaredFields; } ParameterizedType pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); return declaredFields.Select(m => new SpecializedField(m, substitution) { DeclaringType = pt }); } else { return declaredFields; } } #endregion #region GetEvents public static IEnumerable<IEvent> GetEvents(IType type, Predicate<IEvent> filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { return GetEventsImpl(type, filter, options); } else { return type.GetNonInterfaceBaseTypes().SelectMany(t => GetEventsImpl(t, filter, options)); } } static IEnumerable<IEvent> GetEventsImpl(IType baseType, Predicate<IEvent> filter, GetMemberOptions options) { IEnumerable<IEvent> declaredEvents = baseType.GetEvents(filter, options | declaredMembers); if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) { return declaredEvents; } ParameterizedType pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); return declaredEvents.Select(m => new SpecializedEvent(m, substitution) { DeclaringType = pt }); } else { return declaredEvents; } } #endregion #region GetMembers public static IEnumerable<IMember> GetMembers(IType type, Predicate<IMember> filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { return GetMembersImpl(type, filter, options); } else { return type.GetNonInterfaceBaseTypes().SelectMany(t => GetMembersImpl(t, filter, options)); } } static IEnumerable<IMember> GetMembersImpl(IType baseType, Predicate<IMember> filter, GetMemberOptions options) { foreach (var m in GetMethodsImpl(baseType, null, filter, options)) yield return m; foreach (var m in GetPropertiesImpl(baseType, filter, options)) yield return m; foreach (var m in GetFieldsImpl(baseType, filter, options)) yield return m; foreach (var m in GetEventsImpl(baseType, filter, options)) yield return m; } #endregion } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs", "repo_id": "ILSpy", "token_count": 4283 }
218
// 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; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem.Implementation; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// Type system implementation for Metadata.PEFile. /// </summary> [DebuggerDisplay("<MetadataModule: {AssemblyName}>")] public class MetadataModule : IModule { public ICompilation Compilation { get; } internal readonly MetadataReader metadata; readonly TypeSystemOptions options; internal readonly TypeProvider TypeProvider; internal readonly Nullability NullableContext; readonly MetadataNamespace rootNamespace; readonly MetadataTypeDefinition[] typeDefs; readonly MetadataField[] fieldDefs; readonly MetadataMethod[] methodDefs; readonly MetadataProperty[] propertyDefs; readonly MetadataEvent[] eventDefs; readonly IModule[] referencedAssemblies; internal MetadataModule(ICompilation compilation, Metadata.PEFile peFile, TypeSystemOptions options) { this.Compilation = compilation; this.PEFile = peFile; this.metadata = peFile.Metadata; this.options = options; this.TypeProvider = new TypeProvider(this); // assembly metadata if (metadata.IsAssembly) { var asmdef = metadata.GetAssemblyDefinition(); try { this.AssemblyName = metadata.GetString(asmdef.Name); this.AssemblyVersion = asmdef.Version; this.FullAssemblyName = metadata.GetFullAssemblyName(); } catch (BadImageFormatException) { this.AssemblyName = "<ERR: invalid assembly name>"; this.FullAssemblyName = "<ERR: invalid assembly name>"; } } else { try { var moddef = metadata.GetModuleDefinition(); this.AssemblyName = metadata.GetString(moddef.Name); } catch (BadImageFormatException) { this.AssemblyName = "<ERR: invalid assembly name>"; } this.FullAssemblyName = this.AssemblyName; } var customAttrs = metadata.GetModuleDefinition().GetCustomAttributes(); this.NullableContext = customAttrs.GetNullableContext(metadata) ?? Nullability.Oblivious; this.minAccessibilityForNRT = FindMinimumAccessibilityForNRT(metadata, customAttrs); this.rootNamespace = new MetadataNamespace(this, null, string.Empty, metadata.GetNamespaceDefinitionRoot()); if (!options.HasFlag(TypeSystemOptions.Uncached)) { // create arrays for resolved entities, indexed by row index this.typeDefs = new MetadataTypeDefinition[metadata.TypeDefinitions.Count + 1]; this.fieldDefs = new MetadataField[metadata.FieldDefinitions.Count + 1]; this.methodDefs = new MetadataMethod[metadata.MethodDefinitions.Count + 1]; this.propertyDefs = new MetadataProperty[metadata.PropertyDefinitions.Count + 1]; this.eventDefs = new MetadataEvent[metadata.EventDefinitions.Count + 1]; this.referencedAssemblies = new IModule[metadata.AssemblyReferences.Count + 1]; } } internal string GetString(StringHandle name) { return metadata.GetString(name); } public TypeSystemOptions TypeSystemOptions => options; #region IAssembly interface public PEFile PEFile { get; } public bool IsMainModule => this == Compilation.MainModule; public string AssemblyName { get; } public Version AssemblyVersion { get; } public string FullAssemblyName { get; } string ISymbol.Name => AssemblyName; SymbolKind ISymbol.SymbolKind => SymbolKind.Module; public INamespace RootNamespace => rootNamespace; public IEnumerable<ITypeDefinition> TopLevelTypeDefinitions => TypeDefinitions.Where(td => td.DeclaringTypeDefinition == null); public ITypeDefinition GetTypeDefinition(TopLevelTypeName topLevelTypeName) { var typeDefHandle = PEFile.GetTypeDefinition(topLevelTypeName); if (typeDefHandle.IsNil) { var forwarderHandle = PEFile.GetTypeForwarder(topLevelTypeName); if (!forwarderHandle.IsNil) { var forwarder = metadata.GetExportedType(forwarderHandle); return ResolveForwardedType(forwarder).GetDefinition(); } } return GetDefinition(typeDefHandle); } #endregion #region InternalsVisibleTo public bool InternalsVisibleTo(IModule module) { if (this == module) return true; foreach (string shortName in GetInternalsVisibleTo()) { if (string.Equals(module.AssemblyName, shortName, StringComparison.OrdinalIgnoreCase)) return true; } return false; } string[] internalsVisibleTo; string[] GetInternalsVisibleTo() { var result = LazyInit.VolatileRead(ref this.internalsVisibleTo); if (result != null) { return result; } if (metadata.IsAssembly) { var list = new List<string>(); foreach (var attrHandle in metadata.GetAssemblyDefinition().GetCustomAttributes()) { var attr = metadata.GetCustomAttribute(attrHandle); if (attr.IsKnownAttribute(metadata, KnownAttribute.InternalsVisibleTo)) { var attrValue = attr.DecodeValue(this.TypeProvider); if (attrValue.FixedArguments.Length == 1) { if (attrValue.FixedArguments[0].Value is string s) { list.Add(GetShortName(s)); } } } } result = list.ToArray(); } else { result = Empty<string>.Array; } return LazyInit.GetOrSet(ref this.internalsVisibleTo, result); } static string GetShortName(string fullAssemblyName) { if (fullAssemblyName == null) return null; int pos = fullAssemblyName.IndexOf(','); if (pos < 0) return fullAssemblyName; else return fullAssemblyName.Substring(0, pos); } #endregion #region GetDefinition /// <summary> /// Gets all types in the assembly, including nested types. /// </summary> public IEnumerable<ITypeDefinition> TypeDefinitions { get { foreach (var tdHandle in metadata.TypeDefinitions) { yield return GetDefinition(tdHandle); } } } public ITypeDefinition GetDefinition(TypeDefinitionHandle handle) { if (handle.IsNil) return null; if (typeDefs == null) return new MetadataTypeDefinition(this, handle); int row = MetadataTokens.GetRowNumber(handle); if (row >= typeDefs.Length) HandleOutOfRange(handle); var typeDef = LazyInit.VolatileRead(ref typeDefs[row]); if (typeDef != null) return typeDef; typeDef = new MetadataTypeDefinition(this, handle); return LazyInit.GetOrSet(ref typeDefs[row], typeDef); } public IField GetDefinition(FieldDefinitionHandle handle) { if (handle.IsNil) return null; if (fieldDefs == null) return new MetadataField(this, handle); int row = MetadataTokens.GetRowNumber(handle); if (row >= fieldDefs.Length) HandleOutOfRange(handle); var field = LazyInit.VolatileRead(ref fieldDefs[row]); if (field != null) return field; field = new MetadataField(this, handle); return LazyInit.GetOrSet(ref fieldDefs[row], field); } public IMethod GetDefinition(MethodDefinitionHandle handle) { if (handle.IsNil) return null; if (methodDefs == null) return new MetadataMethod(this, handle); int row = MetadataTokens.GetRowNumber(handle); Debug.Assert(row != 0); if (row >= methodDefs.Length) HandleOutOfRange(handle); var method = LazyInit.VolatileRead(ref methodDefs[row]); if (method != null) return method; method = new MetadataMethod(this, handle); return LazyInit.GetOrSet(ref methodDefs[row], method); } public IProperty GetDefinition(PropertyDefinitionHandle handle) { if (handle.IsNil) return null; if (propertyDefs == null) return new MetadataProperty(this, handle); int row = MetadataTokens.GetRowNumber(handle); Debug.Assert(row != 0); if (row >= methodDefs.Length) HandleOutOfRange(handle); var property = LazyInit.VolatileRead(ref propertyDefs[row]); if (property != null) return property; property = new MetadataProperty(this, handle); return LazyInit.GetOrSet(ref propertyDefs[row], property); } public IEvent GetDefinition(EventDefinitionHandle handle) { if (handle.IsNil) return null; if (eventDefs == null) return new MetadataEvent(this, handle); int row = MetadataTokens.GetRowNumber(handle); Debug.Assert(row != 0); if (row >= methodDefs.Length) HandleOutOfRange(handle); var ev = LazyInit.VolatileRead(ref eventDefs[row]); if (ev != null) return ev; ev = new MetadataEvent(this, handle); return LazyInit.GetOrSet(ref eventDefs[row], ev); } void HandleOutOfRange(EntityHandle handle) { throw new BadImageFormatException("Handle with invalid row number."); } #endregion #region Resolve Module public IModule ResolveModule(AssemblyReferenceHandle handle) { if (handle.IsNil) return null; if (referencedAssemblies == null) return ResolveModuleUncached(handle); int row = metadata.GetRowNumber(handle); Debug.Assert(row != 0); if (row >= referencedAssemblies.Length) HandleOutOfRange(handle); var module = LazyInit.VolatileRead(ref referencedAssemblies[row]); if (module != null) return module; module = ResolveModuleUncached(handle); return LazyInit.GetOrSet(ref referencedAssemblies[row], module); } IModule ResolveModuleUncached(AssemblyReferenceHandle handle) { var asmRef = new Metadata.AssemblyReference(metadata, handle); return Compilation.FindModuleByReference(asmRef); } public IModule ResolveModule(ModuleReferenceHandle handle) { if (handle.IsNil) return null; var modRef = metadata.GetModuleReference(handle); string name = metadata.GetString(modRef.Name); foreach (var mod in Compilation.Modules) { if (mod.Name == name) { return mod; } } return null; } public IModule GetDeclaringModule(TypeReferenceHandle handle) { if (handle.IsNil) return null; var tr = metadata.GetTypeReference(handle); switch (tr.ResolutionScope.Kind) { case HandleKind.TypeReference: return GetDeclaringModule((TypeReferenceHandle)tr.ResolutionScope); case HandleKind.AssemblyReference: return ResolveModule((AssemblyReferenceHandle)tr.ResolutionScope); case HandleKind.ModuleReference: return ResolveModule((ModuleReferenceHandle)tr.ResolutionScope); default: return this; } } #endregion #region Resolve Type public IType ResolveType(EntityHandle typeRefDefSpec, GenericContext context, CustomAttributeHandleCollection? typeAttributes = null, Nullability nullableContext = Nullability.Oblivious) { return ResolveType(typeRefDefSpec, context, options, typeAttributes, nullableContext); } public IType ResolveType(EntityHandle typeRefDefSpec, GenericContext context, TypeSystemOptions customOptions, CustomAttributeHandleCollection? typeAttributes = null, Nullability nullableContext = Nullability.Oblivious) { if (typeRefDefSpec.IsNil) return SpecialType.UnknownType; IType ty; switch (typeRefDefSpec.Kind) { case HandleKind.TypeDefinition: ty = TypeProvider.GetTypeFromDefinition(metadata, (TypeDefinitionHandle)typeRefDefSpec, 0); break; case HandleKind.TypeReference: ty = TypeProvider.GetTypeFromReference(metadata, (TypeReferenceHandle)typeRefDefSpec, 0); break; case HandleKind.TypeSpecification: var typeSpec = metadata.GetTypeSpecification((TypeSpecificationHandle)typeRefDefSpec); ty = typeSpec.DecodeSignature(TypeProvider, context); break; case HandleKind.ExportedType: return ResolveForwardedType(metadata.GetExportedType((ExportedTypeHandle)typeRefDefSpec)); default: throw new BadImageFormatException("Not a type handle"); } ty = ApplyAttributeTypeVisitor.ApplyAttributesToType(ty, Compilation, typeAttributes, metadata, customOptions, nullableContext); return ty; } IType ResolveDeclaringType(EntityHandle declaringTypeReference, GenericContext context) { // resolve without substituting dynamic/tuple types const TypeSystemOptions removedOptions = TypeSystemOptions.Dynamic | TypeSystemOptions.Tuple | TypeSystemOptions.NullabilityAnnotations | TypeSystemOptions.NativeIntegers | TypeSystemOptions.NativeIntegersWithoutAttribute; var ty = ResolveType(declaringTypeReference, context, options & ~removedOptions); // but substitute tuple types in type arguments: ty = ApplyAttributeTypeVisitor.ApplyAttributesToType(ty, Compilation, null, metadata, options, Nullability.Oblivious, typeChildrenOnly: true); return ty; } IType IntroduceTupleTypes(IType ty) { // run ApplyAttributeTypeVisitor without attributes, in order to introduce tuple types return ApplyAttributeTypeVisitor.ApplyAttributesToType(ty, Compilation, null, metadata, options, Nullability.Oblivious); } #endregion #region Resolve Method public IMethod ResolveMethod(EntityHandle methodReference, GenericContext context) { if (methodReference.IsNil) throw new ArgumentNullException(nameof(methodReference)); switch (methodReference.Kind) { case HandleKind.MethodDefinition: return ResolveMethodDefinition((MethodDefinitionHandle)methodReference, expandVarArgs: true); case HandleKind.MemberReference: return ResolveMethodReference((MemberReferenceHandle)methodReference, context, expandVarArgs: true); case HandleKind.MethodSpecification: return ResolveMethodSpecification((MethodSpecificationHandle)methodReference, context, expandVarArgs: true); default: throw new BadImageFormatException("Metadata token must be either a methoddef, memberref or methodspec"); } } IMethod ResolveMethodDefinition(MethodDefinitionHandle methodDefHandle, bool expandVarArgs) { var method = GetDefinition(methodDefHandle); if (expandVarArgs && method.Parameters.LastOrDefault()?.Type.Kind == TypeKind.ArgList) { method = new VarArgInstanceMethod(method, EmptyList<IType>.Instance); } return method; } IMethod ResolveMethodSpecification(MethodSpecificationHandle methodSpecHandle, GenericContext context, bool expandVarArgs) { var methodSpec = metadata.GetMethodSpecification(methodSpecHandle); var methodTypeArgs = methodSpec.DecodeSignature(TypeProvider, context) .SelectReadOnlyArray(IntroduceTupleTypes); IMethod method; if (methodSpec.Method.Kind == HandleKind.MethodDefinition) { // generic instance of a methoddef (=generic method in non-generic class in current assembly) method = ResolveMethodDefinition((MethodDefinitionHandle)methodSpec.Method, expandVarArgs); method = method.Specialize(new TypeParameterSubstitution(null, methodTypeArgs)); } else { method = ResolveMethodReference((MemberReferenceHandle)methodSpec.Method, context, methodTypeArgs, expandVarArgs); } return method; } /// <summary> /// Resolves a method reference. /// </summary> /// <remarks> /// Class type arguments are provided by the declaring type stored in the memberRef. /// Method type arguments are provided by the caller. /// </remarks> IMethod ResolveMethodReference(MemberReferenceHandle memberRefHandle, GenericContext context, IReadOnlyList<IType> methodTypeArguments = null, bool expandVarArgs = true) { var memberRef = metadata.GetMemberReference(memberRefHandle); if (memberRef.GetKind() != MemberReferenceKind.Method) { throw new BadImageFormatException($"Member reference must be method, but was: {memberRef.GetKind()}"); } MethodSignature<IType> signature; IReadOnlyList<IType> classTypeArguments = null; IMethod method; if (memberRef.Parent.Kind == HandleKind.MethodDefinition) { method = ResolveMethodDefinition((MethodDefinitionHandle)memberRef.Parent, expandVarArgs: false); signature = memberRef.DecodeMethodSignature(TypeProvider, context); } else { var declaringType = ResolveDeclaringType(memberRef.Parent, context); var declaringTypeDefinition = declaringType.GetDefinition(); if (declaringType.TypeArguments.Count > 0) { classTypeArguments = declaringType.TypeArguments; } // Note: declaringType might be parameterized, but the signature is for the original method definition. // We'll have to search the member directly on declaringTypeDefinition. string name = metadata.GetString(memberRef.Name); signature = memberRef.DecodeMethodSignature(TypeProvider, new GenericContext(declaringTypeDefinition?.TypeParameters)); if (declaringTypeDefinition != null) { // Find the set of overloads to search: IEnumerable<IMethod> methods; if (name == ".ctor") { methods = declaringTypeDefinition.GetConstructors(); } else if (name == ".cctor") { methods = declaringTypeDefinition.Methods.Where(m => m.IsConstructor && m.IsStatic); } else { methods = declaringTypeDefinition.GetMethods(m => m.Name == name, GetMemberOptions.IgnoreInheritedMembers) .Concat(declaringTypeDefinition.GetAccessors(m => m.Name == name, GetMemberOptions.IgnoreInheritedMembers)); } // Determine the expected parameters from the signature: ImmutableArray<IType> parameterTypes; if (signature.Header.CallingConvention == SignatureCallingConvention.VarArgs) { parameterTypes = signature.ParameterTypes .Take(signature.RequiredParameterCount) .Concat(new[] { SpecialType.ArgList }) .ToImmutableArray(); } else { parameterTypes = signature.ParameterTypes; } // Search for the matching method: method = null; foreach (var m in methods) { if (m.TypeParameters.Count != signature.GenericParameterCount) continue; if (CompareSignatures(m.Parameters, parameterTypes) && CompareTypes(m.ReturnType, signature.ReturnType)) { method = m; break; } } } else { method = null; } if (method == null) { method = CreateFakeMethod(declaringType, name, signature); } } if (classTypeArguments != null || methodTypeArguments != null) { method = method.Specialize(new TypeParameterSubstitution(classTypeArguments, methodTypeArguments)); } if (expandVarArgs && signature.Header.CallingConvention == SignatureCallingConvention.VarArgs) { method = new VarArgInstanceMethod(method, signature.ParameterTypes.Skip(signature.RequiredParameterCount)); } return method; } static readonly NormalizeTypeVisitor normalizeTypeVisitor = new NormalizeTypeVisitor { ReplaceClassTypeParametersWithDummy = true, ReplaceMethodTypeParametersWithDummy = true, }; static bool CompareTypes(IType a, IType b) { IType type1 = a.AcceptVisitor(normalizeTypeVisitor); IType type2 = b.AcceptVisitor(normalizeTypeVisitor); return type1.Equals(type2); } static bool CompareSignatures(IReadOnlyList<IParameter> parameters, ImmutableArray<IType> parameterTypes) { if (parameterTypes.Length != parameters.Count) return false; for (int i = 0; i < parameterTypes.Length; i++) { if (!CompareTypes(parameterTypes[i], parameters[i].Type)) return false; } return true; } /// <summary> /// Create a dummy IMethod from the specified MethodReference /// </summary> IMethod CreateFakeMethod(IType declaringType, string name, MethodSignature<IType> signature) { SymbolKind symbolKind = SymbolKind.Method; if (name == ".ctor" || name == ".cctor") symbolKind = SymbolKind.Constructor; var m = new FakeMethod(Compilation, symbolKind); m.DeclaringType = declaringType; m.Name = name; m.ReturnType = signature.ReturnType; m.IsStatic = !signature.Header.IsInstance; TypeParameterSubstitution substitution = null; if (signature.GenericParameterCount > 0) { var typeParameters = new List<ITypeParameter>(); for (int i = 0; i < signature.GenericParameterCount; i++) { typeParameters.Add(new DefaultTypeParameter(m, i)); } m.TypeParameters = typeParameters; substitution = new TypeParameterSubstitution(declaringType.TypeArguments, typeParameters); } else if (declaringType.TypeArguments.Count > 0) { substitution = declaringType.GetSubstitution(); } var parameters = new List<IParameter>(); for (int i = 0; i < signature.RequiredParameterCount; i++) { var type = signature.ParameterTypes[i]; if (substitution != null) { // replace the dummy method type parameters with the owned instances we just created type = type.AcceptVisitor(substitution); } parameters.Add(new DefaultParameter(type, "")); } m.Parameters = parameters; GuessFakeMethodAccessor(declaringType, name, signature, m, parameters); return m; } private void GuessFakeMethodAccessor(IType declaringType, string name, MethodSignature<IType> signature, FakeMethod m, List<IParameter> parameters) { if (signature.GenericParameterCount > 0) return; var guessedGetter = name.StartsWith("get_", StringComparison.Ordinal); var guessedSetter = name.StartsWith("set_", StringComparison.Ordinal); if (guessedGetter || guessedSetter) { var propertyName = name.Substring(4); var fakeProperty = new FakeProperty(Compilation) { Name = propertyName, DeclaringType = declaringType, IsStatic = m.IsStatic, }; if (guessedGetter) { if (signature.ReturnType.Kind == TypeKind.Void) return; m.AccessorKind = MethodSemanticsAttributes.Getter; m.AccessorOwner = fakeProperty; fakeProperty.Getter = m; fakeProperty.ReturnType = signature.ReturnType; fakeProperty.IsIndexer = parameters.Count > 0; fakeProperty.Parameters = parameters; return; } if (guessedSetter) { if (parameters.Count < 1 || signature.ReturnType.Kind != TypeKind.Void) return; m.AccessorKind = MethodSemanticsAttributes.Setter; m.AccessorOwner = fakeProperty; fakeProperty.Setter = m; fakeProperty.ReturnType = parameters.Last().Type; fakeProperty.IsIndexer = parameters.Count > 1; fakeProperty.Parameters = parameters.SkipLast(1).ToArray(); return; } } const string addPrefix = "add_"; const string removePrefix = "remove_"; const string raisePrefix = "raise_"; var guessedAdd = name.StartsWith(addPrefix, StringComparison.Ordinal); var guessedRemove = name.StartsWith(removePrefix, StringComparison.Ordinal); var guessedRaise = name.StartsWith(raisePrefix, StringComparison.Ordinal); if (guessedAdd || guessedRemove || guessedRaise) { var fakeEvent = new FakeEvent(Compilation) { DeclaringType = declaringType, IsStatic = m.IsStatic, }; if (guessedAdd) { if (parameters.Count != 1) return; m.AccessorKind = MethodSemanticsAttributes.Adder; m.AccessorOwner = fakeEvent; fakeEvent.Name = name.Substring(addPrefix.Length); fakeEvent.AddAccessor = m; fakeEvent.ReturnType = parameters.Single().Type; return; } if (guessedRemove) { if (parameters.Count != 1) return; m.AccessorKind = MethodSemanticsAttributes.Remover; m.AccessorOwner = fakeEvent; fakeEvent.Name = name.Substring(removePrefix.Length); fakeEvent.RemoveAccessor = m; fakeEvent.ReturnType = parameters.Single().Type; return; } if (guessedRaise) { fakeEvent.Name = name.Substring(raisePrefix.Length); fakeEvent.InvokeAccessor = m; m.AccessorKind = MethodSemanticsAttributes.Raiser; m.AccessorOwner = fakeEvent; return; } } } #endregion #region Resolve Entity /// <summary> /// Resolves a symbol. /// </summary> /// <remarks> /// * Types are resolved to their definition, as IType does not implement ISymbol. /// * types without definition will resolve to <c>null</c> /// * use ResolveType() to properly resolve types /// * When resolving methods, varargs signatures are not expanded. /// * use ResolveMethod() instead to get an IMethod instance suitable for call-sites /// * May return specialized members, where generics are involved. /// * Other types of handles that don't correspond to TS entities, will return <c>null</c>. /// </remarks> public IEntity ResolveEntity(EntityHandle entityHandle, GenericContext context = default) { switch (entityHandle.Kind) { case HandleKind.TypeReference: case HandleKind.TypeDefinition: case HandleKind.TypeSpecification: case HandleKind.ExportedType: // Using ResolveDeclaringType() here because ResolveType() might return // nint/nuint which are SpecialTypes without a definition. return ResolveDeclaringType(entityHandle, context).GetDefinition(); case HandleKind.MemberReference: var memberReferenceHandle = (MemberReferenceHandle)entityHandle; switch (metadata.GetMemberReference(memberReferenceHandle).GetKind()) { case MemberReferenceKind.Method: // for consistency with the MethodDefinition case, never expand varargs return ResolveMethodReference(memberReferenceHandle, context, expandVarArgs: false); case MemberReferenceKind.Field: return ResolveFieldReference(memberReferenceHandle, context); default: throw new BadImageFormatException("Unknown MemberReferenceKind"); } case HandleKind.MethodDefinition: return GetDefinition((MethodDefinitionHandle)entityHandle); case HandleKind.MethodSpecification: return ResolveMethodSpecification((MethodSpecificationHandle)entityHandle, context, expandVarArgs: false); case HandleKind.FieldDefinition: return GetDefinition((FieldDefinitionHandle)entityHandle); case HandleKind.EventDefinition: return GetDefinition((EventDefinitionHandle)entityHandle); case HandleKind.PropertyDefinition: return GetDefinition((PropertyDefinitionHandle)entityHandle); default: return null; } } IField ResolveFieldReference(MemberReferenceHandle memberReferenceHandle, GenericContext context) { var memberRef = metadata.GetMemberReference(memberReferenceHandle); var declaringType = ResolveDeclaringType(memberRef.Parent, context); var declaringTypeDefinition = declaringType.GetDefinition(); string name = metadata.GetString(memberRef.Name); // field signature is for the definition, not the generic instance var signature = memberRef.DecodeFieldSignature(TypeProvider, new GenericContext(declaringTypeDefinition?.TypeParameters)); // 'f' in the predicate is also the definition, even if declaringType is a ParameterizedType var field = declaringType.GetFields(f => f.Name == name && CompareTypes(f.ReturnType, signature), GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault(); if (field == null) { // If it's a field in a generic type, we need to substitute the type arguments: if (declaringType.TypeArguments.Count > 0) { signature = signature.AcceptVisitor(declaringType.GetSubstitution()); } field = new FakeField(Compilation) { ReturnType = signature, Name = name, DeclaringType = declaringType, }; } return field; } #endregion #region Decode Standalone Signature public (SignatureHeader, FunctionPointerType) DecodeMethodSignature(StandaloneSignatureHandle handle, GenericContext genericContext) { var standaloneSignature = metadata.GetStandaloneSignature(handle); if (standaloneSignature.GetKind() != StandaloneSignatureKind.Method) throw new BadImageFormatException("Expected Method signature"); var sig = standaloneSignature.DecodeMethodSignature(TypeProvider, genericContext); var fpt = FunctionPointerType.FromSignature(sig, this); return (sig.Header, (FunctionPointerType)IntroduceTupleTypes(fpt)); } public ImmutableArray<IType> DecodeLocalSignature(StandaloneSignatureHandle handle, GenericContext genericContext) { var standaloneSignature = metadata.GetStandaloneSignature(handle); if (standaloneSignature.GetKind() != StandaloneSignatureKind.LocalVariables) throw new BadImageFormatException("Expected LocalVariables signature"); var types = standaloneSignature.DecodeLocalSignature(TypeProvider, genericContext); return ImmutableArray.CreateRange(types, IntroduceTupleTypes); } #endregion #region Module / Assembly attributes /// <summary> /// Gets the list of all assembly attributes in the project. /// </summary> public IEnumerable<IAttribute> GetAssemblyAttributes() { var b = new AttributeListBuilder(this); if (metadata.IsAssembly) { var assembly = metadata.GetAssemblyDefinition(); b.Add(metadata.GetCustomAttributes(Handle.AssemblyDefinition), SymbolKind.Module); b.AddSecurityAttributes(assembly.GetDeclarativeSecurityAttributes()); // AssemblyVersionAttribute if (assembly.Version != null) { b.Add(KnownAttribute.AssemblyVersion, KnownTypeCode.String, assembly.Version.ToString()); } AddTypeForwarderAttributes(ref b); } return b.Build(); } /// <summary> /// Gets the list of all module attributes in the project. /// </summary> public IEnumerable<IAttribute> GetModuleAttributes() { var b = new AttributeListBuilder(this); b.Add(metadata.GetCustomAttributes(Handle.ModuleDefinition), SymbolKind.Module); if (!metadata.IsAssembly) { AddTypeForwarderAttributes(ref b); } return b.Build(); } void AddTypeForwarderAttributes(ref AttributeListBuilder b) { foreach (ExportedTypeHandle t in metadata.ExportedTypes) { var type = metadata.GetExportedType(t); if (type.IsForwarder) { b.Add(KnownAttribute.TypeForwardedTo, KnownTypeCode.Type, ResolveForwardedType(type)); } } } IType ResolveForwardedType(ExportedType forwarder) { IModule module = ResolveModule(forwarder); var typeName = forwarder.GetFullTypeName(metadata); if (module == null) return new UnknownType(typeName); using (var busyLock = BusyManager.Enter(this)) { if (busyLock.Success) { var td = module.GetTypeDefinition(typeName); if (td != null) { return td; } } } return new UnknownType(typeName); IModule ResolveModule(ExportedType type) { switch (type.Implementation.Kind) { case HandleKind.AssemblyFile: // TODO : Resolve assembly file (module)... return this; case HandleKind.ExportedType: var outerType = metadata.GetExportedType((ExportedTypeHandle)type.Implementation); return ResolveModule(outerType); case HandleKind.AssemblyReference: var asmRef = metadata.GetAssemblyReference((AssemblyReferenceHandle)type.Implementation); string shortName = metadata.GetString(asmRef.Name); foreach (var asm in Compilation.Modules) { if (string.Equals(asm.AssemblyName, shortName, StringComparison.OrdinalIgnoreCase)) { return asm; } } return null; default: throw new BadImageFormatException("Expected implementation to be either an AssemblyFile, ExportedType or AssemblyReference."); } } } #endregion #region Attribute Helpers /// <summary> /// Cache for parameterless known attribute types. /// </summary> readonly IType[] knownAttributeTypes = new IType[KnownAttributes.Count]; internal IType GetAttributeType(KnownAttribute attr) { var ty = LazyInit.VolatileRead(ref knownAttributeTypes[(int)attr]); if (ty != null) return ty; ty = Compilation.FindType(attr.GetTypeName()); return LazyInit.GetOrSet(ref knownAttributeTypes[(int)attr], ty); } /// <summary> /// Cache for parameterless known attributes. /// </summary> readonly IAttribute[] knownAttributes = new IAttribute[KnownAttributes.Count]; /// <summary> /// Construct a builtin attribute. /// </summary> internal IAttribute MakeAttribute(KnownAttribute type) { var attr = LazyInit.VolatileRead(ref knownAttributes[(int)type]); if (attr != null) return attr; attr = new DefaultAttribute(GetAttributeType(type), ImmutableArray.Create<CustomAttributeTypedArgument<IType>>(), ImmutableArray.Create<CustomAttributeNamedArgument<IType>>()); return LazyInit.GetOrSet(ref knownAttributes[(int)type], attr); } #endregion #region Visibility Filter internal bool IncludeInternalMembers => (options & TypeSystemOptions.OnlyPublicAPI) == 0; internal bool IsVisible(FieldAttributes att) { att &= FieldAttributes.FieldAccessMask; return IncludeInternalMembers || att == FieldAttributes.Public || att == FieldAttributes.Family || att == FieldAttributes.FamORAssem; } internal bool IsVisible(MethodAttributes att) { att &= MethodAttributes.MemberAccessMask; return IncludeInternalMembers || att == MethodAttributes.Public || att == MethodAttributes.Family || att == MethodAttributes.FamORAssem; } #endregion #region Nullability Reference Type Support readonly Accessibility minAccessibilityForNRT; static Accessibility FindMinimumAccessibilityForNRT(MetadataReader metadata, CustomAttributeHandleCollection customAttributes) { // Determine the minimum effective accessibility an entity must have, so that the metadata stores the nullability for its type. foreach (var handle in customAttributes) { var customAttribute = metadata.GetCustomAttribute(handle); if (customAttribute.IsKnownAttribute(metadata, KnownAttribute.NullablePublicOnly)) { CustomAttributeValue<IType> value; try { value = customAttribute.DecodeValue(Metadata.MetadataExtensions.MinimalAttributeTypeProvider); } catch (BadImageFormatException) { continue; } catch (EnumUnderlyingTypeResolveException) { continue; } if (value.FixedArguments.Length == 1 && value.FixedArguments[0].Value is bool includesInternals) { return includesInternals ? Accessibility.ProtectedAndInternal : Accessibility.Protected; } } } return Accessibility.None; } internal bool ShouldDecodeNullableAttributes(IEntity entity) { if ((options & TypeSystemOptions.NullabilityAnnotations) == 0) return false; if (minAccessibilityForNRT == Accessibility.None || entity == null) return true; return minAccessibilityForNRT.LessThanOrEqual(entity.EffectiveAccessibility()); } internal TypeSystemOptions OptionsForEntity(IEntity entity) { var opt = this.options; if ((opt & TypeSystemOptions.NullabilityAnnotations) != 0) { if (!ShouldDecodeNullableAttributes(entity)) { opt &= ~TypeSystemOptions.NullabilityAnnotations; } } return opt; } #endregion } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs", "repo_id": "ILSpy", "token_count": 12538 }
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. namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// . /// </summary> public enum TypeKind : byte { /// <summary>Language-specific type that is not part of NRefactory.TypeSystem itself.</summary> Other, /// <summary>A <see cref="ITypeDefinition"/> or <see cref="ParameterizedType"/> that is a class.</summary> Class, /// <summary>A <see cref="ITypeDefinition"/> or <see cref="ParameterizedType"/> that is an interface.</summary> Interface, /// <summary>A <see cref="ITypeDefinition"/> or <see cref="ParameterizedType"/> that is a struct.</summary> Struct, /// <summary>A <see cref="ITypeDefinition"/> or <see cref="ParameterizedType"/> that is a delegate.</summary> /// <remarks><c>System.Delegate</c> itself is TypeKind.Class</remarks> Delegate, /// <summary>A <see cref="ITypeDefinition"/> that is an enum.</summary> /// <remarks><c>System.Enum</c> itself is TypeKind.Class</remarks> Enum, /// <summary>The <c>System.Void</c> type.</summary> /// <see cref="KnownTypeCode.Void"/> Void, /// <summary>Type used for invalid expressions and for types whose definition could not be found.</summary> /// <see cref="SpecialType.UnknownType"/> Unknown, /// <summary>The type of the null literal.</summary> /// <see cref="SpecialType.NullType"/> Null, /// <summary>The type of expressions without type (except for null literals, which have <c>TypeKind.Null</c>).</summary> /// <see cref="SpecialType.NoType"/> None, /// <summary>Type representing the C# 'dynamic' type.</summary> /// <see cref="SpecialType.Dynamic"/> Dynamic, /// <summary>Represents missing type arguments in partially parameterized types.</summary> /// <see cref="SpecialType.UnboundTypeArgument"/> /// <see cref="IType">IType.GetNestedTypes(Predicate{ITypeDefinition}, GetMemberOptions)</see> UnboundTypeArgument, /// <summary>The type is a type parameter.</summary> /// <see cref="ITypeParameter"/> TypeParameter, /// <summary>An array type</summary> /// <see cref="ArrayType"/> Array, /// <summary>A pointer type</summary> /// <see cref="PointerType"/> Pointer, /// <summary>A managed reference type</summary> /// <see cref="ByReferenceType"/> ByReference, /// <summary>Intersection of several types</summary> /// <see cref="IntersectionType"/> Intersection, /// <see cref="SpecialType.ArgList"/> ArgList, /// <summary>A C# 7 tuple type. /// E.g. <code>(string, int)</code> /// Note: <code>System.ValueTuple&lt;string, int&gt;</code> is not considered a tuple type. /// </summary> /// <see cref="TupleType"/> Tuple, /// <summary> /// Modified type, with optional modifier. /// </summary> ModOpt, /// <summary> /// Modified type, with required modifier. /// </summary> ModReq, /// <summary> /// C# 9 <c>nint</c> /// </summary> NInt, /// <summary> /// C# 9 <c>nuint</c> /// </summary> NUInt, /// <summary> /// C# 9 <c>delegate*</c> /// </summary> FunctionPointer, } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeKind.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeKind.cs", "repo_id": "ILSpy", "token_count": 1358 }
220
// 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. #nullable enable using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; namespace ICSharpCode.Decompiler.Util { static class FileUtility { /// <summary> /// Gets the normalized version of fileName. /// Slashes are replaced with backslashes, backreferences "." and ".." are 'evaluated'. /// </summary> [return: NotNullIfNotNull("fileName")] public static string? NormalizePath(string? fileName) { if (fileName == null || fileName.Length == 0) return fileName; int i; bool isWeb = false; for (i = 0; i < fileName.Length; i++) { if (fileName[i] == '/' || fileName[i] == '\\') break; if (fileName[i] == ':') { if (i > 1) isWeb = true; break; } } char outputSeparator = '/'; bool isRelative; bool isAbsoluteUnixPath = false; StringBuilder result = new StringBuilder(); if (isWeb == false && IsUNCPath(fileName)) { // UNC path i = 2; outputSeparator = '\\'; result.Append(outputSeparator); isRelative = false; } else { i = 0; isAbsoluteUnixPath = fileName[0] == '/'; isRelative = !isWeb && !isAbsoluteUnixPath && (fileName.Length < 2 || fileName[1] != ':'); if (fileName.Length >= 2 && fileName[1] == ':') { outputSeparator = '\\'; } } int levelsBack = 0; int segmentStartPos = i; for (; i <= fileName.Length; i++) { if (i == fileName.Length || fileName[i] == '/' || fileName[i] == '\\') { int segmentLength = i - segmentStartPos; switch (segmentLength) { case 0: // ignore empty segment (if not in web mode) if (isWeb) { result.Append(outputSeparator); } break; case 1: // ignore /./ segment, but append other one-letter segments if (fileName[segmentStartPos] != '.') { if (result.Length > 0) result.Append(outputSeparator); result.Append(fileName[segmentStartPos]); } break; case 2: if (fileName[segmentStartPos] == '.' && fileName[segmentStartPos + 1] == '.') { // remove previous segment int j; for (j = result.Length - 1; j >= 0 && result[j] != outputSeparator; j--) { } if (j > 0) { result.Length = j; } else if (isAbsoluteUnixPath) { result.Length = 0; } else if (isRelative) { if (result.Length == 0) levelsBack++; else result.Length = 0; } break; } else { // append normal segment goto default; } default: if (result.Length > 0) result.Append(outputSeparator); result.Append(fileName, segmentStartPos, segmentLength); break; } segmentStartPos = i + 1; // remember start position for next segment } } if (isWeb == false) { if (isRelative) { for (int j = 0; j < levelsBack; j++) { result.Insert(0, ".." + outputSeparator); } } if (result.Length > 0 && result[result.Length - 1] == outputSeparator) { result.Length -= 1; } if (isAbsoluteUnixPath) { result.Insert(0, '/'); } if (result.Length == 2 && result[1] == ':') { result.Append(outputSeparator); } if (result.Length == 0) return "."; } return result.ToString(); } static bool IsUNCPath(string fileName) { return fileName.Length > 2 && (fileName[0] == '\\' || fileName[0] == '/') && (fileName[1] == '\\' || fileName[1] == '/'); } public static bool IsEqualFileName(string? fileName1, string? fileName2) { return string.Equals(NormalizePath(fileName1), NormalizePath(fileName2), StringComparison.OrdinalIgnoreCase); } public static bool IsBaseDirectory(string? baseDirectory, string? testDirectory) { if (baseDirectory == null || testDirectory == null) return false; baseDirectory = NormalizePath(baseDirectory); if (baseDirectory == "." || baseDirectory == "") return !Path.IsPathRooted(testDirectory); baseDirectory = AddTrailingSeparator(baseDirectory); testDirectory = AddTrailingSeparator(NormalizePath(testDirectory)); return testDirectory.StartsWith(baseDirectory, StringComparison.OrdinalIgnoreCase); } [return: NotNullIfNotNull("input")] static string? AddTrailingSeparator(string? input) { if (input == null || input.Length == 0) return input; if (input[input.Length - 1] == Path.DirectorySeparatorChar || input[input.Length - 1] == Path.AltDirectorySeparatorChar) return input; else return input + GetSeparatorForPath(input).ToString(); } static char GetSeparatorForPath(string input) { if (input.Length > 2 && input[1] == ':' || IsUNCPath(input)) return '\\'; return '/'; } readonly static char[] separators = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; /// <summary> /// Converts a given absolute path and a given base path to a path that leads /// from the base path to the absoulte path. (as a relative path) /// </summary> public static string GetRelativePath(string? baseDirectoryPath, string absPath) { if (baseDirectoryPath == null || baseDirectoryPath.Length == 0) { return absPath; } baseDirectoryPath = NormalizePath(baseDirectoryPath); absPath = NormalizePath(absPath); string[] bPath = baseDirectoryPath != "." ? baseDirectoryPath.TrimEnd(separators).Split(separators) : new string[0]; string[] aPath = absPath != "." ? absPath.TrimEnd(separators).Split(separators) : new string[0]; int indx = 0; for (; indx < Math.Min(bPath.Length, aPath.Length); ++indx) { if (!bPath[indx].Equals(aPath[indx], StringComparison.OrdinalIgnoreCase)) break; } if (indx == 0 && (Path.IsPathRooted(baseDirectoryPath) || Path.IsPathRooted(absPath))) { return absPath; } if (indx == bPath.Length && indx == aPath.Length) { return "."; } StringBuilder erg = new StringBuilder(); for (int i = indx; i < bPath.Length; ++i) { erg.Append(".."); erg.Append(Path.DirectorySeparatorChar); } erg.Append(String.Join(Path.DirectorySeparatorChar.ToString(), aPath, indx, aPath.Length - indx)); if (erg[erg.Length - 1] == Path.DirectorySeparatorChar) erg.Length -= 1; return erg.ToString(); } [return: NotNullIfNotNull("path")] public static string? TrimPath(string? path, int max_chars) { const char ellipsis = '\u2026'; // HORIZONTAL ELLIPSIS const int ellipsisLength = 2; if (path == null || path.Length <= max_chars) return path; char sep = Path.DirectorySeparatorChar; if (path.IndexOf(Path.AltDirectorySeparatorChar) >= 0 && path.IndexOf(Path.DirectorySeparatorChar) < 0) { sep = Path.AltDirectorySeparatorChar; } string[] parts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); int len = ellipsisLength; // For initial ellipsis int index = parts.Length; // From the end of the path, fit as many parts as possible: while (index > 1 && len + parts[index - 1].Length < max_chars) { len += parts[index - 1].Length + 1; index--; } StringBuilder result = new StringBuilder(); result.Append(ellipsis); // If there's 5 chars left, partially fit another part: if (index > 1 && len + 5 <= max_chars) { if (index == 2 && parts[0].Length <= ellipsisLength) { // If the partial part is part #1, // and part #0 is as short as the ellipsis // (e.g. just a drive letter), use part #0 // instead of the ellipsis. result.Clear(); result.Append(parts[0]); } result.Append(sep); result.Append(parts[index - 1], 0, max_chars - len - 3); result.Append(ellipsis); } while (index < parts.Length) { result.Append(sep); result.Append(parts[index]); index++; } return result.ToString(); } } }
ILSpy/ICSharpCode.Decompiler/Util/FileUtility.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Util/FileUtility.cs", "repo_id": "ILSpy", "token_count": 3789 }
221
#nullable enable // // UnicodeNewline.cs // // Author: // Mike Krüger <mkrueger@xamarin.com> // // Copyright (c) 2013 Xamarin Inc. (http://xamarin.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; namespace ICSharpCode.Decompiler.Util { public enum UnicodeNewline { Unknown, /// <summary> /// Line Feed, U+000A /// </summary> LF = 0x0A, CRLF = 0x0D0A, /// <summary> /// Carriage Return, U+000D /// </summary> CR = 0x0D, /// <summary> /// Next Line, U+0085 /// </summary> NEL = 0x85, /// <summary> /// Vertical Tab, U+000B /// </summary> VT = 0x0B, /// <summary> /// Form Feed, U+000C /// </summary> FF = 0x0C, /// <summary> /// Line Separator, U+2028 /// </summary> LS = 0x2028, /// <summary> /// Paragraph Separator, U+2029 /// </summary> PS = 0x2029 } /// <summary> /// Defines unicode new lines according to Unicode Technical Report #13 /// http://www.unicode.org/standard/reports/tr13/tr13-5.html /// </summary> public static class NewLine { /// <summary> /// Carriage Return, U+000D /// </summary> public const char CR = (char)0x0D; /// <summary> /// Line Feed, U+000A /// </summary> public const char LF = (char)0x0A; /// <summary> /// Next Line, U+0085 /// </summary> public const char NEL = (char)0x85; /// <summary> /// Vertical Tab, U+000B /// </summary> public const char VT = (char)0x0B; /// <summary> /// Form Feed, U+000C /// </summary> public const char FF = (char)0x0C; /// <summary> /// Line Separator, U+2028 /// </summary> public const char LS = (char)0x2028; /// <summary> /// Paragraph Separator, U+2029 /// </summary> public const char PS = (char)0x2029; /// <summary> /// Determines if a char is a new line delimiter. /// </summary> /// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns> /// <param name="curChar">The current character.</param> /// <param name="nextChar">A callback getting the next character (may be null).</param> public static int GetDelimiterLength(char curChar, Func<char>? nextChar = null) { if (curChar == CR) { if (nextChar != null && nextChar() == LF) return 2; return 1; } if (curChar == LF || curChar == NEL || curChar == VT || curChar == FF || curChar == LS || curChar == PS) return 1; return 0; } /// <summary> /// Determines if a char is a new line delimiter. /// </summary> /// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns> /// <param name="curChar">The current character.</param> /// <param name="nextChar">The next character (if != LF then length will always be 0 or 1).</param> public static int GetDelimiterLength(char curChar, char nextChar) { if (curChar == CR) { if (nextChar == LF) return 2; return 1; } if (curChar == LF || curChar == NEL || curChar == VT || curChar == FF || curChar == LS || curChar == PS) return 1; return 0; } /// <summary> /// Determines if a char is a new line delimiter. /// </summary> /// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns> /// <param name="curChar">The current character.</param> /// <param name = "length">The length of the delimiter</param> /// <param name = "type">The type of the delimiter</param> /// <param name="nextChar">A callback getting the next character (may be null).</param> public static bool TryGetDelimiterLengthAndType(char curChar, out int length, out UnicodeNewline type, Func<char>? nextChar = null) { if (curChar == CR) { if (nextChar != null && nextChar() == LF) { length = 2; type = UnicodeNewline.CRLF; } else { length = 1; type = UnicodeNewline.CR; } return true; } switch (curChar) { case LF: type = UnicodeNewline.LF; length = 1; return true; case NEL: type = UnicodeNewline.NEL; length = 1; return true; case VT: type = UnicodeNewline.VT; length = 1; return true; case FF: type = UnicodeNewline.FF; length = 1; return true; case LS: type = UnicodeNewline.LS; length = 1; return true; case PS: type = UnicodeNewline.PS; length = 1; return true; } length = -1; type = UnicodeNewline.Unknown; return false; } /// <summary> /// Determines if a char is a new line delimiter. /// </summary> /// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns> /// <param name="curChar">The current character.</param> /// <param name = "length">The length of the delimiter</param> /// <param name = "type">The type of the delimiter</param> /// <param name="nextChar">The next character (if != LF then length will always be 0 or 1).</param> public static bool TryGetDelimiterLengthAndType(char curChar, out int length, out UnicodeNewline type, char nextChar) { if (curChar == CR) { if (nextChar == LF) { length = 2; type = UnicodeNewline.CRLF; } else { length = 1; type = UnicodeNewline.CR; } return true; } switch (curChar) { case LF: type = UnicodeNewline.LF; length = 1; return true; case NEL: type = UnicodeNewline.NEL; length = 1; return true; case VT: type = UnicodeNewline.VT; length = 1; return true; case FF: type = UnicodeNewline.FF; length = 1; return true; case LS: type = UnicodeNewline.LS; length = 1; return true; case PS: type = UnicodeNewline.PS; length = 1; return true; } length = -1; type = UnicodeNewline.Unknown; return false; } /// <summary> /// Gets the new line type of a given char/next char. /// </summary> /// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns> /// <param name="curChar">The current character.</param> /// <param name="nextChar">A callback getting the next character (may be null).</param> public static UnicodeNewline GetDelimiterType(char curChar, Func<char>? nextChar = null) { switch (curChar) { case CR: if (nextChar != null && nextChar() == LF) return UnicodeNewline.CRLF; return UnicodeNewline.CR; case LF: return UnicodeNewline.LF; case NEL: return UnicodeNewline.NEL; case VT: return UnicodeNewline.VT; case FF: return UnicodeNewline.FF; case LS: return UnicodeNewline.LS; case PS: return UnicodeNewline.PS; } return UnicodeNewline.Unknown; } /// <summary> /// Gets the new line type of a given char/next char. /// </summary> /// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns> /// <param name="curChar">The current character.</param> /// <param name="nextChar">The next character (if != LF then length will always be 0 or 1).</param> public static UnicodeNewline GetDelimiterType(char curChar, char nextChar) { switch (curChar) { case CR: if (nextChar == LF) return UnicodeNewline.CRLF; return UnicodeNewline.CR; case LF: return UnicodeNewline.LF; case NEL: return UnicodeNewline.NEL; case VT: return UnicodeNewline.VT; case FF: return UnicodeNewline.FF; case LS: return UnicodeNewline.LS; case PS: return UnicodeNewline.PS; } return UnicodeNewline.Unknown; } /// <summary> /// Determines if a char is a new line delimiter. /// /// Note that the only 2 char wide new line is CR LF and both chars are new line /// chars on their own. For most cases GetDelimiterLength is the better choice. /// </summary> public static bool IsNewLine(char ch) { return ch == NewLine.CR || ch == NewLine.LF || ch == NewLine.NEL || ch == NewLine.VT || ch == NewLine.FF || ch == NewLine.LS || ch == NewLine.PS; } /// <summary> /// Gets the new line as a string. /// </summary> public static string GetString(UnicodeNewline newLine) { switch (newLine) { case UnicodeNewline.Unknown: return ""; case UnicodeNewline.LF: return "\n"; case UnicodeNewline.CRLF: return "\r\n"; case UnicodeNewline.CR: return "\r"; case UnicodeNewline.NEL: return "\u0085"; case UnicodeNewline.VT: return "\u000B"; case UnicodeNewline.FF: return "\u000C"; case UnicodeNewline.LS: return "\u2028"; case UnicodeNewline.PS: return "\u2029"; default: throw new ArgumentOutOfRangeException(); } } } }
ILSpy/ICSharpCode.Decompiler/Util/UnicodeNewline.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Util/UnicodeNewline.cs", "repo_id": "ILSpy", "token_count": 3927 }
222
// 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.ObjectModel; using System.IO; using System.Linq; using System.Xml.Linq; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.ILSpyX.Settings; namespace ICSharpCode.ILSpyX { /// <summary> /// Manages the available assembly lists. /// /// Contains the list of list names; and provides methods for loading/saving and creating/deleting lists. /// </summary> public sealed class AssemblyListManager { public const string DotNet4List = ".NET 4 (WPF)"; public const string DotNet35List = ".NET 3.5"; public const string ASPDotNetMVC3List = "ASP.NET (MVC3)"; private ISettingsProvider settingsProvider; public AssemblyListManager(ISettingsProvider settingsProvider) { this.settingsProvider = settingsProvider; XElement doc = this.settingsProvider["AssemblyLists"]; foreach (var list in doc.Elements("List")) { var name = (string?)list.Attribute("name"); if (name != null) { AssemblyLists.Add(name); } } } public bool ApplyWinRTProjections { get; set; } public bool UseDebugSymbols { get; set; } public ObservableCollection<string> AssemblyLists { get; } = new ObservableCollection<string>(); /// <summary> /// Loads an assembly list from the ILSpySettings. /// If no list with the specified name is found, the default list is loaded instead. /// </summary> public AssemblyList LoadList(string listName) { this.settingsProvider = this.settingsProvider.Load(); AssemblyList list = DoLoadList(listName); if (!AssemblyLists.Contains(list.ListName)) AssemblyLists.Add(list.ListName); return list; } AssemblyList DoLoadList(string listName) { XElement doc = this.settingsProvider["AssemblyLists"]; if (listName != null) { foreach (var list in doc.Elements("List")) { if ((string?)list.Attribute("name") == listName) { return new AssemblyList(this, list); } } } return new AssemblyList(this, listName ?? DefaultListName); } public bool CloneList(string selectedAssemblyList, string newListName) { var list = DoLoadList(selectedAssemblyList); var newList = new AssemblyList(list, newListName); return AddListIfNotExists(newList); } public bool RenameList(string selectedAssemblyList, string newListName) { var list = DoLoadList(selectedAssemblyList); var newList = new AssemblyList(list, newListName); return DeleteList(selectedAssemblyList) && AddListIfNotExists(newList); } public const string DefaultListName = "(Default)"; /// <summary> /// Saves the specified assembly list into the config file. /// </summary> public void SaveList(AssemblyList list) { this.settingsProvider.Update( delegate (XElement root) { XElement? doc = root.Element("AssemblyLists"); if (doc == null) { doc = new XElement("AssemblyLists"); root.Add(doc); } XElement? listElement = doc.Elements("List").FirstOrDefault(e => (string?)e.Attribute("name") == list.ListName); if (listElement != null) listElement.ReplaceWith(list.SaveAsXml()); else doc.Add(list.SaveAsXml()); }); } public bool AddListIfNotExists(AssemblyList list) { if (!AssemblyLists.Contains(list.ListName)) { AssemblyLists.Add(list.ListName); SaveList(list); return true; } return false; } public bool DeleteList(string Name) { if (AssemblyLists.Remove(Name)) { this.settingsProvider.Update( delegate (XElement root) { XElement? doc = root.Element("AssemblyLists"); if (doc == null) { return; } XElement? listElement = doc.Elements("List").FirstOrDefault(e => (string?)e.Attribute("name") == Name); if (listElement != null) listElement.Remove(); }); return true; } return false; } public void ClearAll() { AssemblyLists.Clear(); this.settingsProvider.Update( delegate (XElement root) { XElement? doc = root.Element("AssemblyLists"); if (doc == null) { return; } doc.Remove(); }); } public void CreateDefaultAssemblyLists() { if (AssemblyLists.Count > 0) return; if (!AssemblyLists.Contains(DotNet4List)) { AssemblyList dotnet4 = CreateDefaultList(DotNet4List); if (dotnet4.Count > 0) { AddListIfNotExists(dotnet4); } } if (!AssemblyLists.Contains(DotNet35List)) { AssemblyList dotnet35 = CreateDefaultList(DotNet35List); if (dotnet35.Count > 0) { AddListIfNotExists(dotnet35); } } if (!AssemblyLists.Contains(ASPDotNetMVC3List)) { AssemblyList mvc = CreateDefaultList(ASPDotNetMVC3List); if (mvc.Count > 0) { AddListIfNotExists(mvc); } } } public AssemblyList CreateList(string name) { return new AssemblyList(this, name); } public AssemblyList CreateDefaultList(string name, string? path = null, string? newName = null) { var list = new AssemblyList(this, newName ?? name); switch (name) { case DotNet4List: AddToListFromGAC("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); AddToListFromGAC("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); break; case DotNet35List: AddToListFromGAC("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); break; case ASPDotNetMVC3List: AddToListFromGAC("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); AddToListFromGAC("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); AddToListFromGAC("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); AddToListFromGAC("System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); AddToListFromGAC("System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Web.DynamicData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); AddToListFromGAC("System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); AddToListFromGAC("System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddToListFromGAC("Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); break; case object _ when path != null: foreach (var file in Directory.GetFiles(path, "*.dll")) { var dllname = Path.GetFileName(file); if (DoIncludeFile(dllname)) AddToListFromDirectory(file); } break; } return list; void AddToListFromGAC(string fullName) { AssemblyNameReference reference = AssemblyNameReference.Parse(fullName); string? file = UniversalAssemblyResolver.GetAssemblyInGac(reference); if (file != null) list.OpenAssembly(file); } void AddToListFromDirectory(string file) { if (File.Exists(file)) list.OpenAssembly(file); } bool DoIncludeFile(string fileName) { if (fileName == "Microsoft.DiaSymReader.Native.amd64.dll") return false; if (fileName.EndsWith("_cor3.dll", StringComparison.OrdinalIgnoreCase)) return false; if (char.IsUpper(fileName[0])) return true; if (fileName == "netstandard.dll") return true; if (fileName == "mscorlib.dll") return true; return false; } } } }
ILSpy/ICSharpCode.ILSpyX/AssemblyListManager.cs/0
{ "file_path": "ILSpy/ICSharpCode.ILSpyX/AssemblyListManager.cs", "repo_id": "ILSpy", "token_count": 4960 }
223
// Copyright (c) 2014 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 disable using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace ICSharpCode.ILSpyX.Search { class LATextReader : TextReader { List<int> buffer; TextReader reader; public LATextReader(TextReader reader) { this.buffer = new List<int>(); this.reader = reader; } public override int Peek() { return Peek(0); } public override int Read() { int c = Peek(); buffer.RemoveAt(0); return c; } public int Peek(int step) { while (step >= buffer.Count) { buffer.Add(reader.Read()); } if (step < 0) return -1; return buffer[step]; } protected override void Dispose(bool disposing) { if (disposing) reader.Dispose(); base.Dispose(disposing); } } enum TokenKind : byte { EOF, Literal, Identifier, Symbol, } enum LiteralFormat : byte { None, DecimalNumber, HexadecimalNumber, OctalNumber, StringLiteral, VerbatimStringLiteral, CharLiteral } class Literal { internal readonly TokenKind tokenKind; internal readonly LiteralFormat literalFormat; internal readonly object literalValue; internal readonly string val; internal Literal next; public TokenKind TokenKind { get { return tokenKind; } } public LiteralFormat LiteralFormat { get { return literalFormat; } } public object LiteralValue { get { return literalValue; } } public string Value { get { return val; } } public Literal(string val, TokenKind tokenKind) { this.val = val; this.tokenKind = tokenKind; } public Literal(string val, object literalValue, LiteralFormat literalFormat) { this.val = val; this.literalValue = literalValue; this.literalFormat = literalFormat; this.tokenKind = TokenKind.Literal; } } internal abstract class AbstractLexer : IDisposable { LATextReader reader; int col = 1; int line = 1; protected Literal lastToken = null; protected Literal curToken = null; protected Literal peekToken = null; protected StringBuilder sb = new StringBuilder(); // used for the original value of strings (with escape sequences). protected StringBuilder originalValue = new StringBuilder(); protected int Line { get { return line; } } protected int Col { get { return col; } } protected bool recordRead = false; protected StringBuilder recordedText = new StringBuilder(); protected int ReaderRead() { int val = reader.Read(); if (recordRead && val >= 0) recordedText.Append((char)val); if ((val == '\r' && reader.Peek() != '\n') || val == '\n') { ++line; col = 1; LineBreak(); } else if (val >= 0) { col++; } return val; } protected int ReaderPeek() { return reader.Peek(); } protected int ReaderPeek(int step) { return reader.Peek(step); } protected void ReaderSkip(int steps) { for (int i = 0; i < steps; i++) { ReaderRead(); } } protected string ReaderPeekString(int length) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < length; i++) { int peek = ReaderPeek(i); if (peek != -1) builder.Append((char)peek); } return builder.ToString(); } /// <summary> /// The current Token. <seealso cref="ICSharpCode.NRefactory.Parser.Token"/> /// </summary> public Literal Token { get { return lastToken; } } /// <summary> /// The next Token (The <see cref="Token"/> after <see cref="NextToken"/> call) . <seealso cref="ICSharpCode.NRefactory.Parser.Token"/> /// </summary> public Literal LookAhead { get { return curToken; } } /// <summary> /// Constructor for the abstract lexer class. /// </summary> protected AbstractLexer(TextReader reader) { this.reader = new LATextReader(reader); } #region System.IDisposable interface implementation public virtual void Dispose() { reader.Close(); reader = null; lastToken = curToken = peekToken = null; sb = originalValue = null; } #endregion /// <summary> /// Must be called before a peek operation. /// </summary> public void StartPeek() { peekToken = curToken; } /// <summary> /// Gives back the next token. A second call to Peek() gives the next token after the last call for Peek() and so on. /// </summary> /// <returns>An <see cref="Token"/> object.</returns> public Literal Peek() { // Console.WriteLine("Call to Peek"); if (peekToken.next == null) { peekToken.next = Next(); } peekToken = peekToken.next; return peekToken; } /// <summary> /// Reads the next token and gives it back. /// </summary> /// <returns>An <see cref="Token"/> object.</returns> public virtual Literal NextToken() { if (curToken == null) { curToken = Next(); //Console.WriteLine(ICSharpCode.NRefactory.Parser.CSharp.Tokens.GetTokenString(curToken.kind) + " -- " + curToken.val + "(" + curToken.kind + ")"); return curToken; } lastToken = curToken; if (curToken.next == null) { curToken.next = Next(); } curToken = curToken.next; //Console.WriteLine(ICSharpCode.NRefactory.Parser.CSharp.Tokens.GetTokenString(curToken.kind) + " -- " + curToken.val + "(" + curToken.kind + ")"); return curToken; } protected abstract Literal Next(); protected static bool IsIdentifierPart(int ch) { if (ch == 95) return true; // 95 = '_' if (ch == -1) return false; return char.IsLetterOrDigit((char)ch); // accept unicode letters } protected static bool IsHex(char digit) { return Char.IsDigit(digit) || ('A' <= digit && digit <= 'F') || ('a' <= digit && digit <= 'f'); } protected int GetHexNumber(char digit) { if (Char.IsDigit(digit)) { return digit - '0'; } if ('A' <= digit && digit <= 'F') { return digit - 'A' + 0xA; } if ('a' <= digit && digit <= 'f') { return digit - 'a' + 0xA; } return 0; } protected void LineBreak() { } protected bool HandleLineEnd(char ch) { // Handle MS-DOS or MacOS line ends. if (ch == '\r') { if (reader.Peek() == '\n') { // MS-DOS line end '\r\n' ReaderRead(); // LineBreak (); called by ReaderRead (); return true; } else { // assume MacOS line end which is '\r' LineBreak(); return true; } } if (ch == '\n') { LineBreak(); return true; } return false; } protected void SkipToEndOfLine() { int nextChar; while ((nextChar = reader.Read()) != -1) { if (nextChar == '\r') { if (reader.Peek() == '\n') reader.Read(); nextChar = '\n'; } if (nextChar == '\n') { ++line; col = 1; break; } } } protected string ReadToEndOfLine() { sb.Length = 0; int nextChar; while ((nextChar = reader.Read()) != -1) { char ch = (char)nextChar; if (nextChar == '\r') { if (reader.Peek() == '\n') reader.Read(); nextChar = '\n'; } // Return read string, if EOL is reached if (nextChar == '\n') { ++line; col = 1; return sb.ToString(); } sb.Append(ch); } // Got EOF before EOL string retStr = sb.ToString(); col += retStr.Length; return retStr; } } internal sealed class Lexer : AbstractLexer { public Lexer(TextReader reader) : base(reader) { } protected override Literal Next() { char ch; while (true) { int nextChar = ReaderRead(); if (nextChar == -1) break; Literal token = null; switch (nextChar) { case ' ': case '\t': continue; case '\r': case '\n': HandleLineEnd((char)nextChar); continue; case '"': token = ReadString(); break; case '\'': token = ReadChar(); break; case '@': int next = ReaderRead(); if (next == -1) { Error(Line, Col, String.Format("EOF after @")); continue; } else { int x = Col - 1; int y = Line; ch = (char)next; if (ch == '"') { token = ReadVerbatimString(); } else if (Char.IsLetterOrDigit(ch) || ch == '_') { string s = ReadIdent(ch, out _); return new Literal(s, TokenKind.Identifier); } else { HandleLineEnd(ch); Error(y, x, String.Format("Unexpected char in Lexer.Next() : {0}", ch)); continue; } } break; default: // non-ws chars are handled here ch = (char)nextChar; if (Char.IsLetter(ch) || ch == '_' || ch == '\\') { int x = Col - 1; // Col was incremented above, but we want the start of the identifier int y = Line; string s = ReadIdent(ch, out _); return new Literal(s, TokenKind.Identifier); } else if (Char.IsDigit(ch)) { token = ReadDigit(ch, Col - 1); } break; } // try error recovery (token = null -> continue with next char) if (token != null) { return token; } } return new Literal(null, TokenKind.EOF); } // The C# compiler has a fixed size length therefore we'll use a fixed size char array for identifiers // it's also faster than using a string builder. const int MAX_IDENTIFIER_LENGTH = 512; char[] identBuffer = new char[MAX_IDENTIFIER_LENGTH]; string ReadIdent(char ch, out bool canBeKeyword) { int peek; int curPos = 0; canBeKeyword = true; while (true) { if (ch == '\\') { peek = ReaderPeek(); if (peek != 'u' && peek != 'U') { Error(Line, Col, "Identifiers can only contain unicode escape sequences"); } canBeKeyword = false; string surrogatePair; ReadEscapeSequence(out ch, out surrogatePair); if (surrogatePair != null) { if (!char.IsLetterOrDigit(surrogatePair, 0)) { Error(Line, Col, "Unicode escape sequences in identifiers cannot be used to represent characters that are invalid in identifiers"); } for (int i = 0; i < surrogatePair.Length - 1; i++) { if (curPos < MAX_IDENTIFIER_LENGTH) { identBuffer[curPos++] = surrogatePair[i]; } } ch = surrogatePair[surrogatePair.Length - 1]; } else { if (!IsIdentifierPart(ch)) { Error(Line, Col, "Unicode escape sequences in identifiers cannot be used to represent characters that are invalid in identifiers"); } } } if (curPos < MAX_IDENTIFIER_LENGTH) { if (ch != '\0') // only add character, if it is valid // prevents \ from being added identBuffer[curPos++] = ch; } else { Error(Line, Col, String.Format("Identifier too long")); while (IsIdentifierPart(ReaderPeek())) { ReaderRead(); } break; } peek = ReaderPeek(); if (IsIdentifierPart(peek) || peek == '\\') { ch = (char)ReaderRead(); } else { break; } } return new String(identBuffer, 0, curPos); } Literal ReadDigit(char ch, int x) { unchecked { // prevent exception when ReaderPeek() = -1 is cast to char int y = Line; sb.Length = 0; sb.Append(ch); string prefix = null; string suffix = null; bool ishex = false; bool isunsigned = false; bool islong = false; bool isfloat = false; bool isdouble = false; bool isdecimal = false; char peek = (char)ReaderPeek(); if (ch == '.') { isdouble = true; while (Char.IsDigit((char)ReaderPeek())) { // read decimal digits beyond the dot sb.Append((char)ReaderRead()); } peek = (char)ReaderPeek(); } else if (ch == '0' && (peek == 'x' || peek == 'X')) { ReaderRead(); // skip 'x' sb.Length = 0; // Remove '0' from 0x prefix from the stringvalue while (IsHex((char)ReaderPeek())) { sb.Append((char)ReaderRead()); } if (sb.Length == 0) { sb.Append('0'); // dummy value to prevent exception Error(y, x, "Invalid hexadecimal integer literal"); } ishex = true; prefix = "0x"; peek = (char)ReaderPeek(); } else { while (Char.IsDigit((char)ReaderPeek())) { sb.Append((char)ReaderRead()); } peek = (char)ReaderPeek(); } Literal nextToken = null; // if we accidently read a 'dot' if (peek == '.') { // read floating point number ReaderRead(); peek = (char)ReaderPeek(); if (!Char.IsDigit(peek)) { nextToken = new Literal(".", TokenKind.Symbol); peek = '.'; } else { isdouble = true; // double is default if (ishex) { Error(y, x, "No hexadecimal floating point values allowed"); } sb.Append('.'); while (Char.IsDigit((char)ReaderPeek())) { // read decimal digits beyond the dot sb.Append((char)ReaderRead()); } peek = (char)ReaderPeek(); } } if (peek == 'e' || peek == 'E') { // read exponent isdouble = true; sb.Append((char)ReaderRead()); peek = (char)ReaderPeek(); if (peek == '-' || peek == '+') { sb.Append((char)ReaderRead()); } while (Char.IsDigit((char)ReaderPeek())) { // read exponent value sb.Append((char)ReaderRead()); } isunsigned = true; peek = (char)ReaderPeek(); } if (peek == 'f' || peek == 'F') { // float value ReaderRead(); suffix = "f"; isfloat = true; } else if (peek == 'd' || peek == 'D') { // double type suffix (obsolete, double is default) ReaderRead(); suffix = "d"; isdouble = true; } else if (peek == 'm' || peek == 'M') { // decimal value ReaderRead(); suffix = "m"; isdecimal = true; } else if (!isdouble) { if (peek == 'u' || peek == 'U') { ReaderRead(); suffix = "u"; isunsigned = true; peek = (char)ReaderPeek(); } if (peek == 'l' || peek == 'L') { ReaderRead(); peek = (char)ReaderPeek(); islong = true; if (!isunsigned && (peek == 'u' || peek == 'U')) { ReaderRead(); suffix = "Lu"; isunsigned = true; } else { suffix = isunsigned ? "uL" : "L"; } } } string digit = sb.ToString(); string stringValue = prefix + digit + suffix; if (isfloat) { float num; if (float.TryParse(digit, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { return new Literal(stringValue, num, LiteralFormat.DecimalNumber); } else { Error(y, x, String.Format("Can't parse float {0}", digit)); return new Literal(stringValue, 0f, LiteralFormat.DecimalNumber); } } if (isdecimal) { decimal num; if (decimal.TryParse(digit, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { return new Literal(stringValue, num, LiteralFormat.DecimalNumber); } else { Error(y, x, String.Format("Can't parse decimal {0}", digit)); return new Literal(stringValue, 0m, LiteralFormat.DecimalNumber); } } if (isdouble) { double num; if (double.TryParse(digit, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { return new Literal(stringValue, num, LiteralFormat.DecimalNumber); } else { Error(y, x, String.Format("Can't parse double {0}", digit)); return new Literal(stringValue, 0d, LiteralFormat.DecimalNumber); } } // Try to determine a parsable value using ranges. ulong result; if (ishex) { if (!ulong.TryParse(digit, NumberStyles.HexNumber, null, out result)) { Error(y, x, String.Format("Can't parse hexadecimal constant {0}", digit)); return new Literal(stringValue.ToString(), 0, LiteralFormat.HexadecimalNumber); } } else { if (!ulong.TryParse(digit, NumberStyles.Integer, null, out result)) { Error(y, x, String.Format("Can't parse integral constant {0}", digit)); return new Literal(stringValue.ToString(), 0, LiteralFormat.DecimalNumber); } } if (result > long.MaxValue) { islong = true; isunsigned = true; } else if (result > uint.MaxValue) { islong = true; } else if (islong == false && result > int.MaxValue) { isunsigned = true; } Literal token; LiteralFormat literalFormat = ishex ? LiteralFormat.HexadecimalNumber : LiteralFormat.DecimalNumber; if (islong) { if (isunsigned) { ulong num; if (ulong.TryParse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number, CultureInfo.InvariantCulture, out num)) { token = new Literal(stringValue, num, literalFormat); } else { Error(y, x, String.Format("Can't parse unsigned long {0}", digit)); token = new Literal(stringValue, 0UL, literalFormat); } } else { long num; if (long.TryParse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number, CultureInfo.InvariantCulture, out num)) { token = new Literal(stringValue, num, literalFormat); } else { Error(y, x, String.Format("Can't parse long {0}", digit)); token = new Literal(stringValue, 0L, literalFormat); } } } else { if (isunsigned) { uint num; if (uint.TryParse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number, CultureInfo.InvariantCulture, out num)) { token = new Literal(stringValue, num, literalFormat); } else { Error(y, x, String.Format("Can't parse unsigned int {0}", digit)); token = new Literal(stringValue, (uint)0, literalFormat); } } else { int num; if (int.TryParse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number, CultureInfo.InvariantCulture, out num)) { token = new Literal(stringValue, num, literalFormat); } else { Error(y, x, String.Format("Can't parse int {0}", digit)); token = new Literal(stringValue, 0, literalFormat); } } } token.next = nextToken; return token; } } Literal ReadString() { int x = Col - 1; int y = Line; sb.Length = 0; originalValue.Length = 0; originalValue.Append('"'); bool doneNormally = false; int nextChar; while ((nextChar = ReaderRead()) != -1) { char ch = (char)nextChar; if (ch == '"') { doneNormally = true; originalValue.Append('"'); break; } if (ch == '\\') { originalValue.Append('\\'); string surrogatePair; originalValue.Append(ReadEscapeSequence(out ch, out surrogatePair)); if (surrogatePair != null) { sb.Append(surrogatePair); } else { sb.Append(ch); } } else if (HandleLineEnd(ch)) { // call HandleLineEnd to ensure line numbers are still correct after the error Error(y, x, "No new line is allowed inside a string literal"); break; } else { originalValue.Append(ch); sb.Append(ch); } } if (!doneNormally) { Error(y, x, "End of file reached inside string literal"); } return new Literal(originalValue.ToString(), sb.ToString(), LiteralFormat.StringLiteral); } Literal ReadVerbatimString() { sb.Length = 0; originalValue.Length = 0; originalValue.Append("@\""); int nextChar; while ((nextChar = ReaderRead()) != -1) { char ch = (char)nextChar; if (ch == '"') { if (ReaderPeek() != '"') { originalValue.Append('"'); break; } originalValue.Append("\"\""); sb.Append('"'); ReaderRead(); } else if (HandleLineEnd(ch)) { sb.Append("\r\n"); originalValue.Append("\r\n"); } else { sb.Append(ch); originalValue.Append(ch); } } if (nextChar == -1) { Error(Line, Col, "End of file reached inside verbatim string literal"); } return new Literal(originalValue.ToString(), sb.ToString(), LiteralFormat.VerbatimStringLiteral); } readonly char[] escapeSequenceBuffer = new char[12]; /// <summary> /// reads an escape sequence /// </summary> /// <param name="ch">The character represented by the escape sequence, /// or '\0' if there was an error or the escape sequence represents a character that /// can be represented only be a suggorate pair</param> /// <param name="surrogatePair">Null, except when the character represented /// by the escape sequence can only be represented by a surrogate pair (then the string /// contains the surrogate pair)</param> /// <returns>The escape sequence</returns> string ReadEscapeSequence(out char ch, out string surrogatePair) { surrogatePair = null; int nextChar = ReaderRead(); if (nextChar == -1) { Error(Line, Col, "End of file reached inside escape sequence"); ch = '\0'; return String.Empty; } int number; char c = (char)nextChar; int curPos = 1; escapeSequenceBuffer[0] = c; switch (c) { case '\'': ch = '\''; break; case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case '0': ch = '\0'; break; case 'a': ch = '\a'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case 'v': ch = '\v'; break; case 'u': case 'x': // 16 bit unicode character c = (char)ReaderRead(); number = GetHexNumber(c); escapeSequenceBuffer[curPos++] = c; if (number < 0) { Error(Line, Col - 1, String.Format("Invalid char in literal : {0}", c)); } for (int i = 0; i < 3; ++i) { if (IsHex((char)ReaderPeek())) { c = (char)ReaderRead(); int idx = GetHexNumber(c); escapeSequenceBuffer[curPos++] = c; number = 16 * number + idx; } else { break; } } ch = (char)number; break; case 'U': // 32 bit unicode character number = 0; for (int i = 0; i < 8; ++i) { if (IsHex((char)ReaderPeek())) { c = (char)ReaderRead(); int idx = GetHexNumber(c); escapeSequenceBuffer[curPos++] = c; number = 16 * number + idx; } else { Error(Line, Col - 1, String.Format("Invalid char in literal : {0}", (char)ReaderPeek())); break; } } if (number > 0xffff) { ch = '\0'; surrogatePair = char.ConvertFromUtf32(number); } else { ch = (char)number; } break; default: Error(Line, Col, String.Format("Unexpected escape sequence : {0}", c)); ch = '\0'; break; } return new String(escapeSequenceBuffer, 0, curPos); } Literal ReadChar() { int x = Col - 1; int y = Line; int nextChar = ReaderRead(); if (nextChar == -1 || HandleLineEnd((char)nextChar)) { return null; } char ch = (char)nextChar; char chValue = ch; string escapeSequence = String.Empty; if (ch == '\\') { string surrogatePair; escapeSequence = ReadEscapeSequence(out chValue, out surrogatePair); if (surrogatePair != null) { Error(y, x, "The unicode character must be represented by a surrogate pair and does not fit into a System.Char"); } } unchecked { if ((char)ReaderRead() != '\'') { Error(y, x, "Char not terminated"); } } return new Literal("'" + ch + escapeSequence + "'", chValue, LiteralFormat.CharLiteral); } void Error(int y, int x, string message) { } } }
ILSpy/ICSharpCode.ILSpyX/Search/CSharpLexer.cs/0
{ "file_path": "ILSpy/ICSharpCode.ILSpyX/Search/CSharpLexer.cs", "repo_id": "ILSpy", "token_count": 11459 }
224
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EnvDTE; using Microsoft.VisualStudio.Shell; using VSLangProj; namespace ICSharpCode.ILSpy.AddIn.Commands { /// <summary> /// Represents a NuGet package item in Solution Explorer, which can be opened in ILSpy. /// </summary> class NuGetReferenceForILSpy { ProjectItem projectItem; NuGetReferenceForILSpy(ProjectItem projectItem) { this.projectItem = projectItem; } /// <summary> /// Detects whether the given selected item represents a supported project. /// </summary> /// <param name="itemData">Data object of selected item to check.</param> /// <returns><see cref="NuGetReferenceForILSpy"/> instance or <c>null</c>, if item is not a supported project.</returns> public static NuGetReferenceForILSpy Detect(object itemData) { ThreadHelper.ThrowIfNotOnUIThread(); if (itemData is ProjectItem projectItem) { var properties = Utils.GetProperties(projectItem.Properties, "Type", "ExtenderCATID"); if (((properties[0] as string) == "Package") || ((properties[1] as string) == PrjBrowseObjectCATID.prjCATIDCSharpReferenceBrowseObject)) { return new NuGetReferenceForILSpy(projectItem); } } return null; } /// <summary> /// If possible retrieves parameters to use for launching ILSpy instance. /// </summary> /// <returns>Parameters object or <c>null, if not applicable.</c></returns> public ILSpyParameters GetILSpyParameters() { ThreadHelper.ThrowIfNotOnUIThread(); var properties = Utils.GetProperties(projectItem.Properties, "Name", "Version", "Path"); if (properties[0] != null && properties[1] != null && properties[2] != null) { return new ILSpyParameters(new[] { $"{properties[2]}\\{properties[0]}.{properties[1]}.nupkg" }); } return null; } } }
ILSpy/ILSpy.AddIn.Shared/Commands/NuGetReferenceForILSpy.cs/0
{ "file_path": "ILSpy/ILSpy.AddIn.Shared/Commands/NuGetReferenceForILSpy.cs", "repo_id": "ILSpy", "token_count": 664 }
225
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace ICSharpCode.ILSpy.AddIn { static class SyntaxNodeExtensions { public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxNode node) { var current = node.Parent; while (current != null) { yield return current; current = current is IStructuredTriviaSyntax ? ((IStructuredTriviaSyntax)current).ParentTrivia.Token.Parent : current.Parent; } } public static IEnumerable<TNode> GetAncestors<TNode>(this SyntaxNode node) where TNode : SyntaxNode { var current = node.Parent; while (current != null) { if (current is TNode) { yield return (TNode)current; } current = current is IStructuredTriviaSyntax ? ((IStructuredTriviaSyntax)current).ParentTrivia.Token.Parent : current.Parent; } } public static TNode GetAncestor<TNode>(this SyntaxNode node) where TNode : SyntaxNode { if (node == null) { return default(TNode); } return node.GetAncestors<TNode>().FirstOrDefault(); } public static TNode GetAncestorOrThis<TNode>(this SyntaxNode node) where TNode : SyntaxNode { if (node == null) { return default(TNode); } return node.GetAncestorsOrThis<TNode>().FirstOrDefault(); } public static IEnumerable<TNode> GetAncestorsOrThis<TNode>(this SyntaxNode node) where TNode : SyntaxNode { var current = node; while (current != null) { if (current is TNode) { yield return (TNode)current; } current = current is IStructuredTriviaSyntax ? ((IStructuredTriviaSyntax)current).ParentTrivia.Token.Parent : current.Parent; } } public static bool HasAncestor<TNode>(this SyntaxNode node) where TNode : SyntaxNode { return node.GetAncestors<TNode>().Any(); } public static bool CheckParent<T>(this SyntaxNode node, Func<T, bool> valueChecker) where T : SyntaxNode { if (node == null) { return false; } var parentNode = node.Parent as T; if (parentNode == null) { return false; } return valueChecker(parentNode); } /// <summary> /// Returns true if is a given token is a child token of of a certain type of parent node. /// </summary> /// <typeparam name="TParent">The type of the parent node.</typeparam> /// <param name="node">The node that we are testing.</param> /// <param name="childGetter">A function that, when given the parent node, returns the child token we are interested in.</param> public static bool IsChildNode<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode> childGetter) where TParent : SyntaxNode { var ancestor = node.GetAncestor<TParent>(); if (ancestor == null) { return false; } var ancestorNode = childGetter(ancestor); return node == ancestorNode; } /// <summary> /// Returns true if this node is found underneath the specified child in the given parent. /// </summary> public static bool IsFoundUnder<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode> childGetter) where TParent : SyntaxNode { var ancestor = node.GetAncestor<TParent>(); if (ancestor == null) { return false; } var child = childGetter(ancestor); // See if node passes through child on the way up to ancestor. return node.GetAncestorsOrThis<SyntaxNode>().Contains(child); } public static SyntaxNode GetCommonRoot(this SyntaxNode node1, SyntaxNode node2) { //Contract.ThrowIfTrue(node1.RawKind == 0 || node2.RawKind == 0); // find common starting node from two nodes. // as long as two nodes belong to same tree, there must be at least one common root (Ex, compilation unit) var ancestors = node1.GetAncestorsOrThis<SyntaxNode>(); var set = new HashSet<SyntaxNode>(node2.GetAncestorsOrThis<SyntaxNode>()); return ancestors.First(set.Contains); } public static int Width(this SyntaxNode node) { return node.Span.Length; } public static int FullWidth(this SyntaxNode node) { return node.FullSpan.Length; } public static SyntaxNode FindInnermostCommonNode( this IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, bool> predicate) { IEnumerable<SyntaxNode> blocks = null; foreach (var node in nodes) { blocks = blocks == null ? node.AncestorsAndSelf().Where(predicate) : blocks.Intersect(node.AncestorsAndSelf().Where(predicate)); } return blocks == null ? null : blocks.First(); } public static TSyntaxNode FindInnermostCommonNode<TSyntaxNode>(this IEnumerable<SyntaxNode> nodes) where TSyntaxNode : SyntaxNode { return (TSyntaxNode)nodes.FindInnermostCommonNode(n => n is TSyntaxNode); } /// <summary> /// create a new root node from the given root after adding annotations to the tokens /// /// tokens should belong to the given root /// </summary> public static SyntaxNode AddAnnotations(this SyntaxNode root, IEnumerable<Tuple<SyntaxToken, SyntaxAnnotation>> pairs) { // Contract.ThrowIfNull(root); // Contract.ThrowIfNull(pairs); var tokenMap = pairs.GroupBy(p => p.Item1, p => p.Item2).ToDictionary(g => g.Key, g => g.ToArray()); return root.ReplaceTokens(tokenMap.Keys, (o, n) => o.WithAdditionalAnnotations(tokenMap[o])); } /// <summary> /// create a new root node from the given root after adding annotations to the nodes /// /// nodes should belong to the given root /// </summary> public static SyntaxNode AddAnnotations(this SyntaxNode root, IEnumerable<Tuple<SyntaxNode, SyntaxAnnotation>> pairs) { // Contract.ThrowIfNull(root); // Contract.ThrowIfNull(pairs); var tokenMap = pairs.GroupBy(p => p.Item1, p => p.Item2).ToDictionary(g => g.Key, g => g.ToArray()); return root.ReplaceNodes(tokenMap.Keys, (o, n) => o.WithAdditionalAnnotations(tokenMap[o])); } public static TextSpan GetContainedSpan(this IEnumerable<SyntaxNode> nodes) { // Contract.ThrowIfNull(nodes); // Contract.ThrowIfFalse(nodes.Any()); TextSpan fullSpan = nodes.First().Span; foreach (var node in nodes) { fullSpan = TextSpan.FromBounds( Math.Min(fullSpan.Start, node.SpanStart), Math.Max(fullSpan.End, node.Span.End)); } return fullSpan; } public static IEnumerable<TextSpan> GetContiguousSpans( this IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxToken> getLastToken = null) { SyntaxNode lastNode = null; TextSpan? textSpan = null; foreach (var node in nodes) { if (lastNode == null) { textSpan = node.Span; } else { var lastToken = getLastToken == null ? lastNode.GetLastToken() : getLastToken(lastNode); if (lastToken.GetNextToken(includeDirectives: true) == node.GetFirstToken()) { // Expand the span textSpan = TextSpan.FromBounds(textSpan.Value.Start, node.Span.End); } else { // Return the last span, and start a new one yield return textSpan.Value; textSpan = node.Span; } } lastNode = node; } if (textSpan.HasValue) { yield return textSpan.Value; } } //public static bool OverlapsHiddenPosition(this SyntaxNode node, CancellationToken cancellationToken) //{ // return node.OverlapsHiddenPosition(node.Span, cancellationToken); //} //public static bool OverlapsHiddenPosition(this SyntaxNode node, TextSpan span, CancellationToken cancellationToken) //{ // return node.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken); //} //public static bool OverlapsHiddenPosition(this SyntaxNode declaration, SyntaxNode startNode, SyntaxNode endNode, CancellationToken cancellationToken) //{ // var start = startNode.Span.End; // var end = endNode.SpanStart; // var textSpan = TextSpan.FromBounds(start, end); // return declaration.OverlapsHiddenPosition(textSpan, cancellationToken); //} public static IEnumerable<T> GetAnnotatedNodes<T>(this SyntaxNode node, SyntaxAnnotation syntaxAnnotation) where T : SyntaxNode { return node.GetAnnotatedNodesAndTokens(syntaxAnnotation).Select(n => n.AsNode()).OfType<T>(); } public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2; } public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3; } public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4; } public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5; } /// <summary> /// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in /// top down order. /// </summary> public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node) { return node.GetAncestorOrThis<CompilationUnitSyntax>().Usings .Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>() .Reverse() .SelectMany(n => n.Usings)); } public static bool IsUnsafeContext(this SyntaxNode node) { if (node.GetAncestor<UnsafeStatementSyntax>() != null) { return true; } return node.GetAncestors<MemberDeclarationSyntax>().Any( m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)); } public static bool IsInStaticContext(this SyntaxNode node) { // this/base calls are always static. if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null) { return true; } var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>(); if (memberDeclaration == null) { return false; } switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword); case SyntaxKind.FieldDeclaration: // Inside a field one can only access static members of a type. return true; case SyntaxKind.DestructorDeclaration: return false; } // Global statements are not a static context. if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null) { return false; } // any other location is considered static return true; } public static NamespaceDeclarationSyntax GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode) { var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>(); if (usingDirectiveAncestor == null) { return contextNode.GetAncestorsOrThis<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0); } else { // We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings. var containingNamespace = usingDirectiveAncestor.GetAncestor<NamespaceDeclarationSyntax>(); if (containingNamespace == null) { // We are inside a top level using directive (i.e. one that's directly in the compilation unit). return null; } else { return containingNamespace.GetAncestors<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0); } } } /// <summary> /// Returns all of the trivia to the left of this token up to the previous token (concatenates /// the previous token's trailing trivia and this token's leading trivia). /// </summary> public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(this SyntaxToken token) { var prevToken = token.GetPreviousToken(includeSkipped: true); if (prevToken.Kind() == SyntaxKind.None) { return token.LeadingTrivia; } return prevToken.TrailingTrivia.Concat(token.LeadingTrivia); } public static bool IsBreakableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: return true; } return false; } public static bool IsContinuableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: return true; } return false; } public static bool IsReturnableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; } return false; } public static bool IsAnyArgumentList(this SyntaxNode node) { return node.IsKind(SyntaxKind.ArgumentList) || node.IsKind(SyntaxKind.AttributeArgumentList) || node.IsKind(SyntaxKind.BracketedArgumentList) || node.IsKind(SyntaxKind.TypeArgumentList); } public static bool IsAnyLambda(this SyntaxNode node) { return node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) || node.IsKind(SyntaxKind.SimpleLambdaExpression); } public static bool IsAnyLambdaOrAnonymousMethod(this SyntaxNode node) { return node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression); } public static bool IsAnyAssignExpression(this SyntaxNode node) { return SyntaxFacts.IsAssignmentExpression(node.Kind()); } public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind) { return node != null && node.Parent.IsKind(kind); } public static bool IsParentKind(this SyntaxToken node, SyntaxKind kind) { return node.Parent != null && node.Parent.IsKind(kind); } public static bool IsCompoundAssignExpression(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: return true; } return false; } public static bool IsLeftSideOfAssignExpression(this SyntaxNode node) { return node.IsParentKind(SyntaxKind.SimpleAssignmentExpression) && ((AssignmentExpressionSyntax)node.Parent).Left == node; } public static bool IsLeftSideOfAnyAssignExpression(this SyntaxNode node) { return node.Parent.IsAnyAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Left == node; } public static bool IsRightSideOfAnyAssignExpression(this SyntaxNode node) { return node.Parent.IsAnyAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Right == node; } public static bool IsVariableDeclaratorValue(this SyntaxNode node) { return node.IsParentKind(SyntaxKind.EqualsValueClause) && node.Parent.IsParentKind(SyntaxKind.VariableDeclarator) && ((EqualsValueClauseSyntax)node.Parent).Value == node; } public static BlockSyntax FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes) { return nodes.FindInnermostCommonNode<BlockSyntax>(); } public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode node, Func<SyntaxNode, bool> predicate) { var current = node; while (current != null) { if (predicate(current)) { yield return current; } current = current.Parent; } } public static SyntaxNode GetParent(this SyntaxNode node) { return node != null ? node.Parent : null; } public static ValueTuple<SyntaxToken, SyntaxToken> GetBraces(this SyntaxNode node) { var namespaceNode = node as NamespaceDeclarationSyntax; if (namespaceNode != null) { return ValueTuple.Create(namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken); } var baseTypeNode = node as BaseTypeDeclarationSyntax; if (baseTypeNode != null) { return ValueTuple.Create(baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken); } var accessorListNode = node as AccessorListSyntax; if (accessorListNode != null) { return ValueTuple.Create(accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken); } var blockNode = node as BlockSyntax; if (blockNode != null) { return ValueTuple.Create(blockNode.OpenBraceToken, blockNode.CloseBraceToken); } var switchStatementNode = node as SwitchStatementSyntax; if (switchStatementNode != null) { return ValueTuple.Create(switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken); } var anonymousObjectCreationExpression = node as AnonymousObjectCreationExpressionSyntax; if (anonymousObjectCreationExpression != null) { return ValueTuple.Create(anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken); } var initializeExpressionNode = node as InitializerExpressionSyntax; if (initializeExpressionNode != null) { return ValueTuple.Create(initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken); } return new ValueTuple<SyntaxToken, SyntaxToken>(); } public static SyntaxTokenList GetModifiers(this SyntaxNode member) { if (member != null) { switch (member.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)member).Modifiers; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return ((TypeDeclarationSyntax)member).Modifiers; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).Modifiers; case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)member).Modifiers; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)member).Modifiers; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)member).Modifiers; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)member).Modifiers; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)member).Modifiers; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)member).Modifiers; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)member).Modifiers; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)member).Modifiers; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)member).Modifiers; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).Modifiers; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)member).Modifiers; } } return default(SyntaxTokenList); } public static SyntaxNode WithModifiers(this SyntaxNode member, SyntaxTokenList modifiers) { if (member != null) { switch (member.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return ((TypeDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).WithModifiers(modifiers); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)member).WithModifiers(modifiers); } } return null; } public static TypeDeclarationSyntax WithModifiers( this TypeDeclarationSyntax node, SyntaxTokenList modifiers) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: return ((ClassDeclarationSyntax)node).WithModifiers(modifiers); case SyntaxKind.InterfaceDeclaration: return ((InterfaceDeclarationSyntax)node).WithModifiers(modifiers); case SyntaxKind.StructDeclaration: return ((StructDeclarationSyntax)node).WithModifiers(modifiers); } throw new InvalidOperationException(); } public static bool CheckTopLevel(this SyntaxNode node, TextSpan span) { var block = node as BlockSyntax; if (block != null) { return block.ContainsInBlockBody(span); } var field = node as FieldDeclarationSyntax; if (field != null) { foreach (var variable in field.Declaration.Variables) { if (variable.Initializer != null && variable.Initializer.Span.Contains(span)) { return true; } } } var global = node as GlobalStatementSyntax; if (global != null) { return true; } var constructorInitializer = node as ConstructorInitializerSyntax; if (constructorInitializer != null) { return constructorInitializer.ContainsInArgument(span); } return false; } public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan) { if (initializer == null) { return false; } return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan)); } public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan) { if (block == null) { return false; } var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart); return blockSpan.Contains(textSpan); } public static bool IsDelegateOrConstructorOrMethodParameterList(this SyntaxNode node) { if (!node.IsKind(SyntaxKind.ParameterList)) { return false; } return node.IsParentKind(SyntaxKind.MethodDeclaration) || node.IsParentKind(SyntaxKind.ConstructorDeclaration) || node.IsParentKind(SyntaxKind.DelegateDeclaration); } } }
ILSpy/ILSpy.AddIn.Shared/SyntaxNodeExtensions.cs/0
{ "file_path": "ILSpy/ILSpy.AddIn.Shared/SyntaxNodeExtensions.cs", "repo_id": "ILSpy", "token_count": 9245 }
226
<UserControl x:Class="ILSpy.BamlDecompiler.Tests.Cases.Issue2116" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:ILSpy.BamlDecompiler.Tests.Cases" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <FrameworkElement.Resources> <ResourceDictionary> <Style x:Key="TestStyle1" /> <Style x:Key="TestStyle2" BasedOn="{StaticResource TestStyle1}" /> <Style x:Key="TestStyle2" BasedOn="{StaticResource {x:Type local:Issue2116}}" /> <Style x:Key="TestStyle2" BasedOn="{StaticResource {x:Static local:Issue2116.StyleKey1}}" /> </ResourceDictionary> </FrameworkElement.Resources> <Grid> <Grid Style="{StaticResource TestStyle1}" /> <Grid Style="{StaticResource {x:Type local:Issue2116}}" /> <Grid Style="{StaticResource {x:Static local:Issue2116.StyleKey1}}" /> </Grid> </UserControl>
ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue2116.xaml/0
{ "file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue2116.xaml", "repo_id": "ILSpy", "token_count": 373 }
227
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; [assembly: TargetPlatform("Windows10.0")] [assembly: SupportedOSPlatform("Windows7.0")] // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: NeutralResourcesLanguage("en-US")]
ILSpy/ILSpy.ReadyToRun/Properties/AssemblyInfo.cs/0
{ "file_path": "ILSpy/ILSpy.ReadyToRun/Properties/AssemblyInfo.cs", "repo_id": "ILSpy", "token_count": 125 }
228
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.7.33808.371 MinimumVisualStudioVersion = 10.0.40219.1 Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ILSpy.AddIn.Shared", "ILSpy.AddIn.Shared\ILSpy.AddIn.Shared.shproj", "{ACAB1E5D-B3DF-4092-AA72-692F8341E520}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILSpy.AddIn", "ILSpy.AddIn\ILSpy.AddIn.csproj", "{A1B6B501-15D4-4237-A4C3-5EFCB71B0F74}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILSpy.AddIn.VS2022", "ILSpy.AddIn.VS2022\ILSpy.AddIn.VS2022.csproj", "{31E6E2B0-24B4-4D2C-AC17-3B44DAACC9D4}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A1B6B501-15D4-4237-A4C3-5EFCB71B0F74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B6B501-15D4-4237-A4C3-5EFCB71B0F74}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B6B501-15D4-4237-A4C3-5EFCB71B0F74}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B6B501-15D4-4237-A4C3-5EFCB71B0F74}.Release|Any CPU.Build.0 = Release|Any CPU {31E6E2B0-24B4-4D2C-AC17-3B44DAACC9D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {31E6E2B0-24B4-4D2C-AC17-3B44DAACC9D4}.Debug|Any CPU.Build.0 = Debug|Any CPU {31E6E2B0-24B4-4D2C-AC17-3B44DAACC9D4}.Release|Any CPU.ActiveCfg = Release|Any CPU {31E6E2B0-24B4-4D2C-AC17-3B44DAACC9D4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {84D734FE-9E9C-4593-8927-6F45FE3E460A} EndGlobalSection GlobalSection(SharedMSBuildProjectFiles) = preSolution ILSpy.AddIn.Shared\ILSpy.AddIn.Shared.projitems*{31e6e2b0-24b4-4d2c-ac17-3b44daacc9d4}*SharedItemsImports = 5 ILSpy.AddIn.Shared\ILSpy.AddIn.Shared.projitems*{a1b6b501-15d4-4237-a4c3-5efcb71b0f74}*SharedItemsImports = 5 ILSpy.AddIn.Shared\ILSpy.AddIn.Shared.projitems*{acab1e5d-b3df-4092-aa72-692f8341e520}*SharedItemsImports = 13 EndGlobalSection EndGlobal
ILSpy/ILSpy.VSExtensions.sln/0
{ "file_path": "ILSpy/ILSpy.VSExtensions.sln", "repo_id": "ILSpy", "token_count": 1064 }
229
// 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; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Disassembler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpy.Analyzers; using ILOpCode = System.Reflection.Metadata.ILOpCode; namespace ICSharpCode.ILSpy.Analyzers.Builtin { /// <summary> /// Finds methods where this field is read. /// </summary> [ExportAnalyzer(Header = "Assigned By", Order = 20)] class AssignedByFieldAccessAnalyzer : FieldAccessAnalyzer { public AssignedByFieldAccessAnalyzer() : base(true) { } } /// <summary> /// Finds methods where this field is written. /// </summary> [ExportAnalyzer(Header = "Read By", Order = 10)] class ReadByFieldAccessAnalyzer : FieldAccessAnalyzer { public ReadByFieldAccessAnalyzer() : base(false) { } } /// <summary> /// Finds methods where this field is read or written. /// </summary> class FieldAccessAnalyzer : IAnalyzer { const GetMemberOptions Options = GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions; readonly bool showWrites; // true: show writes; false: show read access public FieldAccessAnalyzer(bool showWrites) { this.showWrites = showWrites; } public bool Show(ISymbol symbol) { return symbol is IField field && (!showWrites || !field.IsConst); } public IEnumerable<ISymbol> Analyze(ISymbol analyzedSymbol, AnalyzerContext context) { Debug.Assert(analyzedSymbol is IField); var scope = context.GetScopeOf((IEntity)analyzedSymbol); foreach (var type in scope.GetTypesInScope(context.CancellationToken)) { var mappingInfo = context.Language.GetCodeMappingInfo(type.ParentModule.PEFile, type.MetadataToken); var methods = type.GetMembers(m => m is IMethod, Options).OfType<IMethod>(); foreach (var method in methods) { if (IsUsedInMethod((IField)analyzedSymbol, method, mappingInfo, context)) yield return method; } foreach (var property in type.Properties) { if (property.CanGet && IsUsedInMethod((IField)analyzedSymbol, property.Getter, mappingInfo, context)) { yield return property; continue; } if (property.CanSet && IsUsedInMethod((IField)analyzedSymbol, property.Setter, mappingInfo, context)) { yield return property; continue; } } foreach (var @event in type.Events) { if (@event.CanAdd && IsUsedInMethod((IField)analyzedSymbol, @event.AddAccessor, mappingInfo, context)) { yield return @event; continue; } if (@event.CanRemove && IsUsedInMethod((IField)analyzedSymbol, @event.RemoveAccessor, mappingInfo, context)) { yield return @event; continue; } if (@event.CanInvoke && IsUsedInMethod((IField)analyzedSymbol, @event.InvokeAccessor, mappingInfo, context)) { yield return @event; continue; } } } } bool IsUsedInMethod(IField analyzedField, IMethod method, CodeMappingInfo mappingInfo, AnalyzerContext context) { if (method.MetadataToken.IsNil) return false; var module = method.ParentModule.PEFile; foreach (var part in mappingInfo.GetMethodParts((MethodDefinitionHandle)method.MetadataToken)) { var md = module.Metadata.GetMethodDefinition(part); if (!md.HasBody()) continue; MethodBodyBlock body; try { body = module.Reader.GetMethodBody(md.RelativeVirtualAddress); } catch (BadImageFormatException) { return false; } if (ScanMethodBody(analyzedField, method, body)) return true; } return false; } bool ScanMethodBody(IField analyzedField, IMethod method, MethodBodyBlock methodBody) { if (methodBody == null) return false; var mainModule = (MetadataModule)method.ParentModule; var blob = methodBody.GetILReader(); var genericContext = new Decompiler.TypeSystem.GenericContext(); // type parameters don't matter for this analyzer while (blob.RemainingBytes > 0) { ILOpCode opCode; try { opCode = blob.DecodeOpCode(); if (!CanBeReference(opCode)) { blob.SkipOperand(opCode); continue; } } catch (BadImageFormatException) { return false; } EntityHandle fieldHandle = MetadataTokenHelpers.EntityHandleOrNil(blob.ReadInt32()); if (!fieldHandle.Kind.IsMemberKind()) continue; IField field; try { field = mainModule.ResolveEntity(fieldHandle, genericContext) as IField; } catch (BadImageFormatException) { continue; } if (field == null) continue; if (field.MetadataToken == analyzedField.MetadataToken && field.ParentModule.PEFile == analyzedField.ParentModule.PEFile) return true; } return false; } bool CanBeReference(ILOpCode code) { switch (code) { case ILOpCode.Ldfld: case ILOpCode.Ldsfld: return !showWrites; case ILOpCode.Stfld: case ILOpCode.Stsfld: return showWrites; case ILOpCode.Ldflda: case ILOpCode.Ldsflda: return true; // always show address-loading default: return false; } } } }
ILSpy/ILSpy/Analyzers/Builtin/FieldAccessAnalyzer.cs/0
{ "file_path": "ILSpy/ILSpy/Analyzers/Builtin/FieldAccessAnalyzer.cs", "repo_id": "ILSpy", "token_count": 2396 }
230
// Copyright (c) 2014 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.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace ICSharpCode.ILSpy.Controls { public class ZoomScrollViewer : ScrollViewer { static ZoomScrollViewer() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ZoomScrollViewer), new FrameworkPropertyMetadata(typeof(ZoomScrollViewer))); } public static readonly DependencyProperty CurrentZoomProperty = DependencyProperty.Register("CurrentZoom", typeof(double), typeof(ZoomScrollViewer), new FrameworkPropertyMetadata(1.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, CalculateZoomButtonCollapsed, CoerceZoom)); public double CurrentZoom { get { return (double)GetValue(CurrentZoomProperty); } set { SetValue(CurrentZoomProperty, value); } } static object CoerceZoom(DependencyObject d, object baseValue) { var zoom = (double)baseValue; ZoomScrollViewer sv = (ZoomScrollViewer)d; return Math.Max(sv.MinimumZoom, Math.Min(sv.MaximumZoom, zoom)); } public static readonly DependencyProperty MinimumZoomProperty = DependencyProperty.Register("MinimumZoom", typeof(double), typeof(ZoomScrollViewer), new FrameworkPropertyMetadata(0.2)); public double MinimumZoom { get { return (double)GetValue(MinimumZoomProperty); } set { SetValue(MinimumZoomProperty, value); } } public static readonly DependencyProperty MaximumZoomProperty = DependencyProperty.Register("MaximumZoom", typeof(double), typeof(ZoomScrollViewer), new FrameworkPropertyMetadata(5.0)); public double MaximumZoom { get { return (double)GetValue(MaximumZoomProperty); } set { SetValue(MaximumZoomProperty, value); } } public static readonly DependencyProperty MouseWheelZoomProperty = DependencyProperty.Register("MouseWheelZoom", typeof(bool), typeof(ZoomScrollViewer), new FrameworkPropertyMetadata(true)); public bool MouseWheelZoom { get { return (bool)GetValue(MouseWheelZoomProperty); } set { SetValue(MouseWheelZoomProperty, value); } } public static readonly DependencyProperty AlwaysShowZoomButtonsProperty = DependencyProperty.Register("AlwaysShowZoomButtons", typeof(bool), typeof(ZoomScrollViewer), new FrameworkPropertyMetadata(false, CalculateZoomButtonCollapsed)); public bool AlwaysShowZoomButtons { get { return (bool)GetValue(AlwaysShowZoomButtonsProperty); } set { SetValue(AlwaysShowZoomButtonsProperty, value); } } static readonly DependencyPropertyKey ComputedZoomButtonCollapsedPropertyKey = DependencyProperty.RegisterReadOnly("ComputedZoomButtonCollapsed", typeof(bool), typeof(ZoomScrollViewer), new FrameworkPropertyMetadata(true)); public static readonly DependencyProperty ComputedZoomButtonCollapsedProperty = ComputedZoomButtonCollapsedPropertyKey.DependencyProperty; public bool ComputedZoomButtonCollapsed { get { return (bool)GetValue(ComputedZoomButtonCollapsedProperty); } private set { SetValue(ComputedZoomButtonCollapsedPropertyKey, value); } } static void CalculateZoomButtonCollapsed(DependencyObject d, DependencyPropertyChangedEventArgs e) { ZoomScrollViewer z = d as ZoomScrollViewer; if (z != null) z.ComputedZoomButtonCollapsed = (z.AlwaysShowZoomButtons == false) && (z.CurrentZoom == 1.0); } protected override void OnMouseWheel(MouseWheelEventArgs e) { if (!e.Handled && Keyboard.Modifiers == ModifierKeys.Control && MouseWheelZoom) { double oldZoom = CurrentZoom; double newZoom = RoundToOneIfClose(CurrentZoom * Math.Pow(1.001, e.Delta)); newZoom = Math.Max(this.MinimumZoom, Math.Min(this.MaximumZoom, newZoom)); // adjust scroll position so that mouse stays over the same virtual coordinate ContentPresenter presenter = Template.FindName("PART_Presenter", this) as ContentPresenter; Vector relMousePos; if (presenter != null) { Point mousePos = e.GetPosition(presenter); relMousePos = new Vector(mousePos.X / presenter.ActualWidth, mousePos.Y / presenter.ActualHeight); } else { relMousePos = new Vector(0.5, 0.5); } Point scrollOffset = new Point(this.HorizontalOffset, this.VerticalOffset); Vector oldHalfViewport = new Vector(this.ViewportWidth / 2, this.ViewportHeight / 2); Vector newHalfViewport = oldHalfViewport / newZoom * oldZoom; Point oldCenter = scrollOffset + oldHalfViewport; Point virtualMousePos = scrollOffset + new Vector(relMousePos.X * this.ViewportWidth, relMousePos.Y * this.ViewportHeight); // As newCenter, we want to choose a point between oldCenter and virtualMousePos. The more we zoom in, the closer // to virtualMousePos. We'll create the line x = oldCenter + lambda * (virtualMousePos-oldCenter). // On this line, we need to choose lambda between -1 and 1: // -1 = zoomed out completely // 0 = zoom unchanged // +1 = zoomed in completely // But the zoom factor (newZoom/oldZoom) we have is in the range [0,+Infinity]. // Basically, I just played around until I found a function that maps this to [-1,1] and works well. // "f" is squared because otherwise the mouse simply stays over virtualMousePos, but I wanted virtualMousePos // to move towards the middle -> squaring f causes lambda to be closer to 1, giving virtualMousePos more weight // then oldCenter. double f = Math.Min(newZoom, oldZoom) / Math.Max(newZoom, oldZoom); double lambda = 1 - f * f; if (oldZoom > newZoom) lambda = -lambda; Debug.Print("old: " + oldZoom + ", new: " + newZoom); Point newCenter = oldCenter + lambda * (virtualMousePos - oldCenter); scrollOffset = newCenter - newHalfViewport; SetCurrentValue(CurrentZoomProperty, newZoom); this.ScrollToHorizontalOffset(scrollOffset.X); this.ScrollToVerticalOffset(scrollOffset.Y); e.Handled = true; } base.OnMouseWheel(e); } internal static double RoundToOneIfClose(double val) { if (Math.Abs(val - 1.0) < 0.001) return 1.0; else return val; } } sealed class IsNormalZoomConverter : IValueConverter { public static readonly IsNormalZoomConverter Instance = new IsNormalZoomConverter(); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (parameter is bool && (bool)parameter) return true; return ((double)value) == 1.0; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
ILSpy/ILSpy/Controls/ZoomScrollViewer.cs/0
{ "file_path": "ILSpy/ILSpy/Controls/ZoomScrollViewer.cs", "repo_id": "ILSpy", "token_count": 2620 }
231
// Copyright (c) 2014 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 System.Threading; using ICSharpCode.ILSpy.Controls; namespace ICSharpCode.ILSpy { class ILSpyTraceListener : DefaultTraceListener { [Conditional("DEBUG")] public static void Install() { Trace.Listeners.Clear(); Trace.Listeners.Add(new ILSpyTraceListener()); } public ILSpyTraceListener() { base.AssertUiEnabled = false; } HashSet<string> ignoredStacks = new HashSet<string>(); bool dialogIsOpen; public override void Fail(string message) { this.Fail(message, null); } public override void Fail(string message, string detailMessage) { base.Fail(message, detailMessage); // let base class write the assert to the debug console string topFrame = ""; string stackTrace = ""; try { stackTrace = new StackTrace(true).ToString(); var frames = stackTrace.Split('\r', '\n') .Where(f => f.Length > 0) .SkipWhile(f => f.Contains("ILSpyTraceListener") || f.Contains("System.Diagnostics")) .ToList(); topFrame = frames[0]; stackTrace = string.Join(Environment.NewLine, frames); } catch { } lock (ignoredStacks) { if (ignoredStacks.Contains(topFrame)) return; if (dialogIsOpen) return; dialogIsOpen = true; } // We might be unable to display a dialog here, e.g. because // we're on the UI thread but dispatcher processing is disabled. // In any case, we don't want to pump messages while the dialog is displaying, // so we create a separate UI thread for the dialog: int result = 0; var thread = new Thread(() => result = ShowAssertionDialog(message, detailMessage, stackTrace)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); if (result == 0) { // throw throw new AssertionFailedException(message); } else if (result == 1) { // debug Debugger.Break(); } else if (result == 2) { // ignore } else if (result == 3) { lock (ignoredStacks) { ignoredStacks.Add(topFrame); } } } int ShowAssertionDialog(string message, string detailMessage, string stackTrace) { message = message + Environment.NewLine + detailMessage + Environment.NewLine + stackTrace; string[] buttonTexts = { "Throw", "Debug", "Ignore", "Ignore All" }; CustomDialog inputBox = new CustomDialog("Assertion Failed", message.TakeStartEllipsis(750), -1, 2, buttonTexts); inputBox.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; inputBox.ShowInTaskbar = true; // make this window more visible, because it effectively interrupts the decompilation process. try { inputBox.ShowDialog(); return inputBox.Result; } finally { dialogIsOpen = false; inputBox.Dispose(); } } } class AssertionFailedException : Exception { public AssertionFailedException(string message) : base(message) { } } }
ILSpy/ILSpy/ILSpyTraceListener.cs/0
{ "file_path": "ILSpy/ILSpy/ILSpyTraceListener.cs", "repo_id": "ILSpy", "token_count": 1418 }
232
<!-- This file was generated by the AiToXaml tool.--> <!-- Tool Version: 14.0.22307.0 --> <DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <DrawingGroup.Children> <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" /> <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M8.0001,5.1721L3.4571,0.6291 0.629099999999999,3.4571 5.1721,8.0001 0.629099999999999,12.5431 3.4571,15.3711 8.0001,10.8281 12.5431,15.3711 15.3711,12.5431 10.8281,8.0001 15.3711,3.4571 12.5431,0.6291z" /> <GeometryDrawing Brush="#FF424242" Geometry="F1M9.4141,8L13.9571,12.543 12.5431,13.957 8.0001,9.414 3.4571,13.957 2.0431,12.543 6.5861,8 2.0431,3.457 3.4571,2.043 8.0001,6.586 12.5431,2.043 13.9571,3.457z" /> </DrawingGroup.Children> </DrawingGroup>
ILSpy/ILSpy/Images/Close.xaml/0
{ "file_path": "ILSpy/ILSpy/Images/Close.xaml", "repo_id": "ILSpy", "token_count": 378 }
233
<!-- This file was generated by the AiToXaml tool.--> <!-- Tool Version: 14.0.22307.0 --> <DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <DrawingGroup.Children> <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" /> <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M6.3819,-0.000199999999999534L1.9999,8.7638 1.9999,9.9998 5.3709,9.9998 2.9999,14.7648 2.9999,15.9998 5.4149,15.9998 13.9999,7.4138 13.9999,5.9998 9.4139,5.9998 13.9999,1.4138 13.9999,-0.000199999999999534z" /> <GeometryDrawing Brush="#FFC17C1A" Geometry="F1M7,7L13,7 5,15 4,15 6.985,9 3,9 7,1 13,1z" /> </DrawingGroup.Children> </DrawingGroup>
ILSpy/ILSpy/Images/Event.xaml/0
{ "file_path": "ILSpy/ILSpy/Images/Event.xaml", "repo_id": "ILSpy", "token_count": 309 }
234
<!-- This file was generated by the AiToXaml tool.--> <!-- Tool Version: 14.0.22307.0 --> <DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <DrawingGroup.Children> <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" /> <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M15,8C15,11.866 11.866,15 8,15 4.134,15 1,11.866 1,8 1,4.134 4.134,1 8,1 11.866,1 15,4.134 15,8" /> <GeometryDrawing Brush="#FF00539C" Geometry="F1M9,11L7,11 9,9 4,9 4,7 9,7 7,5 9,5 12,8z M8,2C4.755,2 2,4.756 2,8 2,11.247 4.755,14 8,14 11.245,14 14,11.247 14,8 14,4.756 11.245,2 8,2" /> <GeometryDrawing Brush="#FFF0EFF1" Geometry="F1M9,11L7,11 9,9 4,9 4,7 9,7 7,5 9,5 12,8z" /> </DrawingGroup.Children> </DrawingGroup>
ILSpy/ILSpy/Images/Forward.xaml/0
{ "file_path": "ILSpy/ILSpy/Images/Forward.xaml", "repo_id": "ILSpy", "token_count": 367 }
235
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg viewBox="0 0 16 16" version="1.1" id="svg4" sodipodi:docname="TypeReference.svg" inkscape:version="1.3.2 (091e20e, 2023-11-25, custom)" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <defs id="defs4" /> <sodipodi:namedview id="namedview4" pagecolor="#ffffff" bordercolor="#000000" borderopacity="0.25" inkscape:showpageshadow="2" inkscape:pageopacity="0.0" inkscape:pagecheckerboard="0" inkscape:deskcolor="#d1d1d1" inkscape:zoom="51.3125" inkscape:cx="3.6930572" inkscape:cy="9.3057247" inkscape:window-width="1920" inkscape:window-height="1017" inkscape:window-x="2552" inkscape:window-y="-8" inkscape:window-maximized="1" inkscape:current-layer="svg4" /> <style id="style1">.st0{opacity:0}.st0,.st1{fill:#f6f6f6}.st2{fill:#424242}.st3{fill:#f0eff1}</style> <g id="outline" style="display:inline"> <path class="st0" d="M 0,0 H 16 V 16 H 0 Z" id="path1" /> <path class="st1" d="m 9,9 v 7 h 7 V 9 Z" id="path2" sodipodi:nodetypes="ccccc" /> </g> <path class="st2" d="M10 10v5h5v-5h-5zm4 3l-1 1v-1.5L11.5 14l-.5-.5 1.5-1.5H11l1-1h2v2z" id="not_x5F_bg" /> <path class="st3" d="M14 11v2l-1 1v-1.5L11.5 14l-.5-.5 1.5-1.5H11l1-1z" id="not_x5F_fg" /> </svg>
ILSpy/ILSpy/Images/ReferenceOverlay.svg/0
{ "file_path": "ILSpy/ILSpy/Images/ReferenceOverlay.svg", "repo_id": "ILSpy", "token_count": 881 }
236
// 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.Buffers.Binary; using System.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; namespace ICSharpCode.ILSpy.Metadata { class ClassLayoutTableTreeNode : MetadataTableTreeNode { public ClassLayoutTableTreeNode(MetadataFile metadataFile) : base((HandleKind)0x0F, metadataFile) { } public override object Text => $"0F ClassLayout ({metadataFile.Metadata.GetTableRowCount(TableIndex.ClassLayout)})"; public override bool View(ViewModels.TabPageModel tabPage) { tabPage.Title = Text.ToString(); tabPage.SupportsLanguageSwitching = false; var view = Helpers.PrepareDataGrid(tabPage, this); var list = new List<ClassLayoutEntry>(); var length = metadataFile.Metadata.GetTableRowCount(TableIndex.ClassLayout); ReadOnlySpan<byte> ptr = metadataFile.Metadata.AsReadOnlySpan(); ClassLayoutEntry scrollTargetEntry = default; for (int rid = 1; rid <= length; rid++) { ClassLayoutEntry entry = new ClassLayoutEntry(metadataFile, ptr, rid); if (scrollTarget == rid) { scrollTargetEntry = entry; } list.Add(entry); } view.ItemsSource = list; tabPage.Content = view; if (scrollTargetEntry.RID > 0) { ScrollItemIntoView(view, scrollTargetEntry); } return true; } readonly struct ClassLayout { public readonly ushort PackingSize; public readonly EntityHandle Parent; public readonly uint ClassSize; public ClassLayout(ReadOnlySpan<byte> ptr, int typeDefSize) { PackingSize = BinaryPrimitives.ReadUInt16LittleEndian(ptr); ClassSize = BinaryPrimitives.ReadUInt32LittleEndian(ptr.Slice(2, 4)); Parent = MetadataTokens.TypeDefinitionHandle(Helpers.GetValueLittleEndian(ptr.Slice(6, typeDefSize))); } } struct ClassLayoutEntry { readonly MetadataFile metadataFile; readonly ClassLayout classLayout; public int RID { get; } public int Token => 0x0F000000 | RID; public int Offset { get; } [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Parent => MetadataTokens.GetToken(classLayout.Parent); public void OnParentClick() { MainWindow.Instance.JumpToReference(new EntityReference("metadata", classLayout.Parent)); } string parentTooltip; public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, classLayout.Parent); [ColumnInfo("X4", Kind = ColumnKind.Other)] public ushort PackingSize => classLayout.PackingSize; [ColumnInfo("X8", Kind = ColumnKind.Other)] public uint ClassSize => classLayout.ClassSize; public ClassLayoutEntry(MetadataFile metadataFile, ReadOnlySpan<byte> ptr, int row) { this.metadataFile = metadataFile; this.RID = row; var metadata = metadataFile.Metadata; var rowOffset = metadata.GetTableMetadataOffset(TableIndex.ClassLayout) + metadata.GetTableRowSize(TableIndex.ClassLayout) * (row - 1); this.Offset = metadataFile.MetadataOffset + rowOffset; this.classLayout = new ClassLayout(ptr.Slice(rowOffset), metadata.GetTableRowCount(TableIndex.TypeDef) < ushort.MaxValue ? 2 : 4); this.parentTooltip = null; } } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, "ClassLayouts"); } } }
ILSpy/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs", "repo_id": "ILSpy", "token_count": 1490 }
237
// 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.Reflection.PortableExecutable; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.ILSpy.TreeNodes; namespace ICSharpCode.ILSpy.Metadata { class DataDirectoriesTreeNode : ILSpyTreeNode { private PEFile module; public DataDirectoriesTreeNode(PEFile module) { this.module = module; } public override object Text => "Data Directories"; public override object Icon => Images.ListFolder; public override object ExpandedIcon => Images.ListFolderOpen; public override bool View(ViewModels.TabPageModel tabPage) { tabPage.Title = Text.ToString(); tabPage.SupportsLanguageSwitching = false; var dataGrid = Helpers.PrepareDataGrid(tabPage, this); //dataGrid.AutoGenerateColumns = false; //dataGrid.Columns.Add(new DataGridTextColumn { IsReadOnly = true, Header = "Name", Binding = new Binding("Name") }); //dataGrid.Columns.Add(new DataGridTextColumn { IsReadOnly = true, Header = "RVA", Binding = new Binding("RVA") { StringFormat = "X8" } }); //dataGrid.Columns.Add(new DataGridTextColumn { IsReadOnly = true, Header = "Size", Binding = new Binding("Size") { StringFormat = "X8" } }); //dataGrid.Columns.Add(new DataGridTextColumn { IsReadOnly = true, Header = "Section", Binding = new Binding("Section") }); var headers = module.Reader.PEHeaders; var header = headers.PEHeader; var entries = new DataDirectoryEntry[] { new DataDirectoryEntry(headers, "Export Table", header.ExportTableDirectory), new DataDirectoryEntry(headers, "Import Table", header.ImportTableDirectory), new DataDirectoryEntry(headers, "Resource Table", header.ResourceTableDirectory), new DataDirectoryEntry(headers, "Exception Table", header.ExceptionTableDirectory), new DataDirectoryEntry(headers, "Certificate Table", header.CertificateTableDirectory), new DataDirectoryEntry(headers, "Base Relocation Table", header.BaseRelocationTableDirectory), new DataDirectoryEntry(headers, "Debug Table", header.DebugTableDirectory), new DataDirectoryEntry(headers, "Copyright Table", header.CopyrightTableDirectory), new DataDirectoryEntry(headers, "Global Pointer Table", header.GlobalPointerTableDirectory), new DataDirectoryEntry(headers, "Thread Local Storage Table", header.ThreadLocalStorageTableDirectory), new DataDirectoryEntry(headers, "Load Config", header.LoadConfigTableDirectory), new DataDirectoryEntry(headers, "Bound Import", header.BoundImportTableDirectory), new DataDirectoryEntry(headers, "Import Address Table", header.ImportAddressTableDirectory), new DataDirectoryEntry(headers, "Delay Import Descriptor", header.DelayImportTableDirectory), new DataDirectoryEntry(headers, "CLI Header", header.CorHeaderTableDirectory), }; dataGrid.ItemsSource = entries; tabPage.Content = dataGrid; return true; } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, "Data Directories"); } class DataDirectoryEntry { public string Name { get; set; } public int RVA { get; set; } public int Size { get; set; } public string Section { get; set; } public DataDirectoryEntry(string name, int rva, int size, string section) { this.Name = name; this.RVA = rva; this.Size = size; this.Section = section; } public DataDirectoryEntry(PEHeaders headers, string name, DirectoryEntry entry) : this(name, entry.RelativeVirtualAddress, entry.Size, (headers.GetContainingSectionIndex(entry.RelativeVirtualAddress) >= 0) ? headers.SectionHeaders[headers.GetContainingSectionIndex(entry.RelativeVirtualAddress)].Name : "") { } } } }
ILSpy/ILSpy/Metadata/DataDirectoriesTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/DataDirectoriesTreeNode.cs", "repo_id": "ILSpy", "token_count": 1450 }
238
using System; using System.Linq; using System.Windows; using System.Windows.Controls; using DataGridExtensions; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.ILSpy.Metadata { /// <summary> /// Interaction logic for FlagsFilterControl.xaml /// </summary> public partial class FlagsFilterControl { ListBox listBox; public FlagsFilterControl() { InitializeComponent(); } public FlagsContentFilter Filter { get { return (FlagsContentFilter)GetValue(FilterProperty); } set { SetValue(FilterProperty, value); } } public Type FlagsType { get; set; } /// <summary> /// Identifies the Filter dependency property /// </summary> public static readonly DependencyProperty FilterProperty = DependencyProperty.Register("Filter", typeof(FlagsContentFilter), typeof(FlagsFilterControl), new FrameworkPropertyMetadata(new FlagsContentFilter(-1), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (sender, e) => ((FlagsFilterControl)sender).Filter_Changed())); /// <summary>When overridden in a derived class, is invoked whenever application code or internal processes call <see cref="M:System.Windows.FrameworkElement.ApplyTemplate" />.</summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); listBox = Template.FindName("ListBox", this) as ListBox; if (listBox != null) { listBox.ItemsSource = FlagGroup.GetFlags(FlagsType, neutralItem: "<All>"); } var filter = Filter; if (filter == null || filter.Mask == -1) { listBox?.SelectAll(); } } private void Filter_Changed() { var filter = Filter; if (filter == null || filter.Mask == -1) { listBox?.SelectAll(); return; } if (listBox?.SelectedItems.Count != 0) return; foreach (var item in listBox.Items.Cast<Flag>()) { if ((item.Value & filter.Mask) != 0 || item.Value == 0) { listBox.SelectedItems.Add(item); } } } private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.RemovedItems?.OfType<Flag>().Any(f => f.Value == -1) == true) { Filter = new FlagsContentFilter(0); listBox.UnselectAll(); return; } if (e.AddedItems?.OfType<Flag>().Any(f => f.Value == -1) == true) { Filter = new FlagsContentFilter(-1); listBox.SelectAll(); return; } bool deselectAny = e.RemovedItems?.OfType<Flag>().Any(f => f.Value != -1) == true; int mask = 0; foreach (var item in listBox.SelectedItems.Cast<Flag>()) { if (deselectAny && item.Value == -1) continue; mask |= item.Value; } Filter = new FlagsContentFilter(mask); } } public class FlagsContentFilter : IContentFilter { public int Mask { get; } public FlagsContentFilter(int mask) { this.Mask = mask; } public bool IsMatch(object value) { if (value == null) return true; return Mask == -1 || (Mask & (int)value) != 0; } } }
ILSpy/ILSpy/Metadata/FlagsFilterControl.xaml.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/FlagsFilterControl.xaml.cs", "repo_id": "ILSpy", "token_count": 1106 }
239
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ICSharpCode.ILSpy.Metadata { /// <summary> /// Interaction logic for MetadataTableViews.xaml /// </summary> public partial class MetadataTableViews : ResourceDictionary { public MetadataTableViews() { InitializeComponent(); } static MetadataTableViews instance; public static MetadataTableViews Instance { get { if (instance == null) { instance = new MetadataTableViews(); } return instance; } } private void DataGrid_AutoGeneratedColumns(object sender, EventArgs e) { Helpers.View_AutoGeneratedColumns(sender, e); } private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { Helpers.View_AutoGeneratingColumn(sender, e); } } }
ILSpy/ILSpy/Metadata/MetadataTableViews.xaml.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/MetadataTableViews.xaml.cs", "repo_id": "ILSpy", "token_count": 393 }
240
<Window x:Class="ICSharpCode.ILSpy.Options.OptionsDialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:properties="clr-namespace:ICSharpCode.ILSpy.Properties" xmlns:options="clr-namespace:ICSharpCode.ILSpy.Options" Style="{DynamicResource DialogWindow}" WindowStartupLocation="CenterOwner" ResizeMode="CanResizeWithGrip" Title="{x:Static properties:Resources.Options}" Height="500" Width="600"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="1*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TabControl Name="tabControl" SelectedValuePath="Content"> <TabControl.ItemTemplate> <DataTemplate DataType="options:TabItemViewModel"> <TextBlock Text="{Binding Header}" /> </DataTemplate> </TabControl.ItemTemplate> <TabControl.ContentTemplate> <DataTemplate DataType="options:TabItemViewModel"> <ContentPresenter Content="{Binding Content}" /> </DataTemplate> </TabControl.ContentTemplate> </TabControl> <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Margin="12,8"> <Button Margin="2,0" Name="defaultsButton" Click="DefaultsButton_Click" Content="{x:Static properties:Resources.ResetToDefaults}" /> <Button IsDefault="True" Margin="2,0" Name="okButton" Click="OKButton_Click" Content="{x:Static properties:Resources.OK}" /> <Button IsCancel="True" Margin="2,0" Content="{x:Static properties:Resources.Cancel}" /> </StackPanel> </Grid> </Window>
ILSpy/ILSpy/Options/OptionsDialog.xaml/0
{ "file_path": "ILSpy/ILSpy/Options/OptionsDialog.xaml", "repo_id": "ILSpy", "token_count": 600 }
241
// 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.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Text; using System.Windows; using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Folding; using ICSharpCode.AvalonEdit.Highlighting; using ICSharpCode.AvalonEdit.Rendering; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using TextLocation = ICSharpCode.Decompiler.CSharp.Syntax.TextLocation; namespace ICSharpCode.ILSpy.TextView { /// <summary> /// A text segment that references some object. Used for hyperlinks in the editor. /// </summary> public sealed class ReferenceSegment : TextSegment { public object Reference; public bool IsLocal; public bool IsDefinition; } /// <summary> /// Stores the positions of the definitions that were written to the text output. /// </summary> sealed class DefinitionLookup { internal Dictionary<object, int> definitions = new Dictionary<object, int>(); public int GetDefinitionPosition(object definition) { int val; if (definitions.TryGetValue(definition, out val)) return val; else return -1; } public void AddDefinition(object definition, int offset) { definitions[definition] = offset; } } /// <summary> /// Text output implementation for AvalonEdit. /// </summary> public sealed class AvalonEditTextOutput : ISmartTextOutput { int lastLineStart = 0; int lineNumber = 1; readonly StringBuilder b = new StringBuilder(); /// <summary>Current indentation level</summary> int indent; /// <summary>Whether indentation should be inserted on the next write</summary> bool needsIndent; public string IndentationString { get; set; } = "\t"; internal bool IgnoreNewLineAndIndent { get; set; } public string Title { get; set; } = Properties.Resources.NewTab; /// <summary> /// Gets/sets the <see cref="Uri"/> that is displayed by this view. /// Used to identify the AboutPage and other views built into ILSpy in the navigation history. /// </summary> public Uri Address { get; set; } internal readonly List<VisualLineElementGenerator> elementGenerators = new List<VisualLineElementGenerator>(); /// <summary>List of all references that were written to the output</summary> TextSegmentCollection<ReferenceSegment> references = new TextSegmentCollection<ReferenceSegment>(); /// <summary>Stack of the fold markers that are open but not closed yet</summary> Stack<(NewFolding, int startLine)> openFoldings = new Stack<(NewFolding, int startLine)>(); /// <summary>List of all foldings that were written to the output</summary> internal readonly List<NewFolding> Foldings = new List<NewFolding>(); internal readonly DefinitionLookup DefinitionLookup = new DefinitionLookup(); internal bool EnableHyperlinks { get; set; } /// <summary>Embedded UIElements, see <see cref="UIElementGenerator"/>.</summary> internal readonly List<KeyValuePair<int, Lazy<UIElement>>> UIElements = new List<KeyValuePair<int, Lazy<UIElement>>>(); public RichTextModel HighlightingModel { get; } = new RichTextModel(); public AvalonEditTextOutput() { } /// <summary> /// Gets the list of references (hyperlinks). /// </summary> internal TextSegmentCollection<ReferenceSegment> References { get { return references; } } public void AddVisualLineElementGenerator(VisualLineElementGenerator elementGenerator) { elementGenerators.Add(elementGenerator); } /// <summary> /// Controls the maximum length of the text. /// When this length is exceeded, an <see cref="OutputLengthExceededException"/> will be thrown, /// thus aborting the decompilation. /// </summary> public int LengthLimit = int.MaxValue; public int TextLength { get { return b.Length; } } public TextLocation Location { get { return new TextLocation(lineNumber, b.Length - lastLineStart + 1 + (needsIndent ? indent : 0)); } } #region Text Document TextDocument textDocument; /// <summary> /// Prepares the TextDocument. /// This method may be called by the background thread writing to the output. /// Once the document is prepared, it can no longer be written to. /// </summary> /// <remarks> /// Calling this method on the background thread ensures the TextDocument's line tokenization /// runs in the background and does not block the GUI. /// </remarks> public void PrepareDocument() { if (textDocument == null) { textDocument = new TextDocument(b.ToString()); textDocument.SetOwnerThread(null); // release ownership } } /// <summary> /// Retrieves the TextDocument. /// Once the document is retrieved, it can no longer be written to. /// </summary> public TextDocument GetDocument() { PrepareDocument(); textDocument.SetOwnerThread(System.Threading.Thread.CurrentThread); // acquire ownership return textDocument; } #endregion public void Indent() { if (IgnoreNewLineAndIndent) return; indent++; } public void Unindent() { if (IgnoreNewLineAndIndent) return; indent--; } void WriteIndent() { if (IgnoreNewLineAndIndent) return; Debug.Assert(textDocument == null); if (needsIndent) { needsIndent = false; for (int i = 0; i < indent; i++) { b.Append(IndentationString); } } } public void Write(char ch) { WriteIndent(); b.Append(ch); } public void Write(string text) { WriteIndent(); b.Append(text); } public void WriteLine() { Debug.Assert(textDocument == null); if (IgnoreNewLineAndIndent) { b.Append(' '); } else { b.AppendLine(); needsIndent = true; lastLineStart = b.Length; lineNumber++; } if (this.TextLength > LengthLimit) { throw new OutputLengthExceededException(); } } public void WriteReference(Decompiler.Disassembler.OpCodeInfo opCode, bool omitSuffix = false) { WriteIndent(); int start = this.TextLength; if (omitSuffix) { int lastDot = opCode.Name.LastIndexOf('.'); if (lastDot > 0) { b.Append(opCode.Name.Remove(lastDot + 1)); } } else { b.Append(opCode.Name); } int end = this.TextLength - 1; references.Add(new ReferenceSegment { StartOffset = start, EndOffset = end, Reference = opCode }); } public void WriteReference(MetadataFile metadata, Handle handle, string text, string protocol = "decompile", bool isDefinition = false) { WriteIndent(); int start = this.TextLength; b.Append(text); int end = this.TextLength; if (isDefinition) { this.DefinitionLookup.AddDefinition((metadata, handle), this.TextLength); } references.Add(new ReferenceSegment { StartOffset = start, EndOffset = end, Reference = new EntityReference(metadata, handle, protocol), IsDefinition = isDefinition }); } public void WriteReference(IType type, string text, bool isDefinition = false) { WriteIndent(); int start = this.TextLength; b.Append(text); int end = this.TextLength; if (isDefinition) { this.DefinitionLookup.AddDefinition(type, this.TextLength); } references.Add(new ReferenceSegment { StartOffset = start, EndOffset = end, Reference = type, IsDefinition = isDefinition }); } public void WriteReference(IMember member, string text, bool isDefinition = false) { WriteIndent(); int start = this.TextLength; b.Append(text); int end = this.TextLength; if (isDefinition) { this.DefinitionLookup.AddDefinition(member, this.TextLength); } references.Add(new ReferenceSegment { StartOffset = start, EndOffset = end, Reference = member, IsDefinition = isDefinition }); } public void WriteLocalReference(string text, object reference, bool isDefinition = false) { WriteIndent(); int start = this.TextLength; b.Append(text); int end = this.TextLength; if (isDefinition) { this.DefinitionLookup.AddDefinition(reference, this.TextLength); } references.Add(new ReferenceSegment { StartOffset = start, EndOffset = end, Reference = reference, IsLocal = true, IsDefinition = isDefinition }); } public void MarkFoldStart(string collapsedText = "...", bool defaultCollapsed = false, bool isDefinition = false) { WriteIndent(); openFoldings.Push(( new NewFolding { StartOffset = this.TextLength, Name = collapsedText, DefaultClosed = defaultCollapsed, IsDefinition = isDefinition, }, lineNumber)); } public void MarkFoldEnd() { var (f, startLine) = openFoldings.Pop(); f.EndOffset = this.TextLength; if (startLine != lineNumber) this.Foldings.Add(f); } public void AddUIElement(Func<UIElement> element) { if (element != null) { if (this.UIElements.Count > 0 && this.UIElements.Last().Key == this.TextLength) throw new InvalidOperationException("Only one UIElement is allowed for each position in the document"); this.UIElements.Add(new KeyValuePair<int, Lazy<UIElement>>(this.TextLength, new Lazy<UIElement>(element))); } } readonly Stack<HighlightingColor> colorStack = new Stack<HighlightingColor>(); HighlightingColor currentColor = new HighlightingColor(); int currentColorBegin = -1; public void BeginSpan(HighlightingColor highlightingColor) { WriteIndent(); if (currentColorBegin > -1) HighlightingModel.SetHighlighting(currentColorBegin, b.Length - currentColorBegin, currentColor); colorStack.Push(currentColor); currentColor = currentColor.Clone(); currentColorBegin = b.Length; currentColor.MergeWith(highlightingColor); currentColor.Freeze(); } public void EndSpan() { HighlightingModel.SetHighlighting(currentColorBegin, b.Length - currentColorBegin, currentColor); currentColor = colorStack.Pop(); currentColorBegin = b.Length; } } }
ILSpy/ILSpy/TextView/AvalonEditTextOutput.cs/0
{ "file_path": "ILSpy/ILSpy/TextView/AvalonEditTextOutput.cs", "repo_id": "ILSpy", "token_count": 3715 }
242
// 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.Windows.Threading; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.ILSpy.TreeNodes { /// <summary> /// Node within assembly reference list. /// </summary> public sealed class AssemblyReferenceTreeNode : ILSpyTreeNode { readonly MetadataModule module; readonly AssemblyReference r; readonly AssemblyTreeNode parentAssembly; public AssemblyReferenceTreeNode(MetadataModule module, AssemblyReference r, AssemblyTreeNode parentAssembly) { this.module = module ?? throw new ArgumentNullException(nameof(module)); this.r = r ?? throw new ArgumentNullException(nameof(r)); this.parentAssembly = parentAssembly ?? throw new ArgumentNullException(nameof(parentAssembly)); this.LazyLoading = true; } public AssemblyReference AssemblyReference => r; public override object Text { get { return Language.EscapeName(r.Name) + GetSuffixString(r.Handle); } } public override object Icon => Images.Assembly; public override bool ShowExpander { get { // Special case for mscorlib: It likely doesn't have any children so call EnsureLazyChildren to // remove the expander from the node. if (r.Name == "mscorlib") { // See https://github.com/icsharpcode/ILSpy/issues/2548: Adding assemblies to the tree view // while the list of references is updated causes problems with WPF's ListView rendering. // Moving the assembly resolving out of the "add assembly reference"-loop by using the // dispatcher fixes the issue. Dispatcher.CurrentDispatcher.BeginInvoke((Action)EnsureLazyChildren, DispatcherPriority.Normal); } return base.ShowExpander; } } public override void ActivateItem(System.Windows.RoutedEventArgs e) { if (parentAssembly.Parent is AssemblyListTreeNode assemblyListNode) { var resolver = parentAssembly.LoadedAssembly.GetAssemblyResolver(); assemblyListNode.Select(assemblyListNode.FindAssemblyNode(resolver.Resolve(r))); e.Handled = true; } } protected override void LoadChildren() { this.Children.Add(new AssemblyReferenceReferencedTypesTreeNode(module, r)); var resolver = parentAssembly.LoadedAssembly.GetAssemblyResolver(MainWindow.Instance.CurrentDecompilerSettings.AutoLoadAssemblyReferences); var referencedModule = resolver.Resolve(r); if (referencedModule != null) { var module = (MetadataModule)referencedModule.GetTypeSystemWithCurrentOptionsOrNull().MainModule; foreach (var childRef in referencedModule.AssemblyReferences) this.Children.Add(new AssemblyReferenceTreeNode(module, childRef, parentAssembly)); } } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { var loaded = parentAssembly.LoadedAssembly.LoadedAssemblyReferencesInfo.TryGetInfo(r.FullName, out var info); if (r.IsWindowsRuntime) { language.WriteCommentLine(output, r.FullName + " [WinRT]" + (!loaded ? " (unresolved)" : "")); } else { language.WriteCommentLine(output, r.FullName + (!loaded ? " (unresolved)" : "")); } if (loaded) { output.Indent(); language.WriteCommentLine(output, "Assembly reference loading information:"); if (info.HasErrors) language.WriteCommentLine(output, "There were some problems during assembly reference load, see below for more information!"); foreach (var item in info.Messages) { language.WriteCommentLine(output, $"{item.Item1}: {item.Item2}"); } output.Unindent(); output.WriteLine(); } } } }
ILSpy/ILSpy/TreeNodes/AssemblyReferenceTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/TreeNodes/AssemblyReferenceTreeNode.cs", "repo_id": "ILSpy", "token_count": 1489 }
243
// Copyright (c) 2023 James May // // 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; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.ILSpy.TreeNodes { /// <summary> /// referenced type within assembly reference list. /// </summary> public sealed class TypeReferenceTreeNode : ILSpyTreeNode { readonly MetadataModule module; readonly TypeReferenceMetadata r; readonly IType resolvedType; public TypeReferenceTreeNode(MetadataModule module, TypeReferenceMetadata r) { this.module = module ?? throw new ArgumentNullException(nameof(module)); this.r = r ?? throw new ArgumentNullException(nameof(r)); this.resolvedType = module.ResolveType(r.Handle, default); this.LazyLoading = true; } public override object Text => Language.TypeToString(resolvedType, includeNamespace: false) + GetSuffixString(r.Handle); public override object Icon => Images.TypeReference; protected override void LoadChildren() { foreach (var typeRef in r.TypeReferences) this.Children.Add(new TypeReferenceTreeNode(module, typeRef)); foreach (var memberRef in r.MemberReferences) this.Children.Add(new MemberReferenceTreeNode(module, memberRef)); } public override bool ShowExpander => !r.TypeReferences.IsEmpty || !r.MemberReferences.IsEmpty; public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, Language.TypeToString(resolvedType, includeNamespace: true)); EnsureLazyChildren(); foreach (ILSpyTreeNode child in Children) { output.Indent(); child.Decompile(language, output, options); output.Unindent(); } } } }
ILSpy/ILSpy/TreeNodes/TypeReferenceTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/TreeNodes/TypeReferenceTreeNode.cs", "repo_id": "ILSpy", "token_count": 830 }
244
<Window x:Class="ICSharpCode.ILSpy.CreateListDialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:properties="clr-namespace:ICSharpCode.ILSpy.Properties" Style="{DynamicResource DialogWindow}" WindowStartupLocation="CenterOwner" ResizeMode="NoResize" Width="300" Height="150" FocusManager.FocusedElement="{Binding ElementName=ListNameBox}"> <Grid Margin="12,8"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <StackPanel> <Label Content="{x:Static properties:Resources.EnterListName}"/> <TextBox Margin="8,8" Name="ListNameBox" TextChanged="TextBox_TextChanged"></TextBox> </StackPanel> <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Margin="8,0"> <Button IsDefault="True" Margin="2,0" IsEnabled="False" Name="okButton" Click="OKButton_Click" Content="{x:Static properties:Resources.Create}"/> <Button IsCancel="True" Margin="2,0" Content="{x:Static properties:Resources.Cancel}"/> </StackPanel> </Grid> </Window>
ILSpy/ILSpy/Views/CreateListDialog.xaml/0
{ "file_path": "ILSpy/ILSpy/Views/CreateListDialog.xaml", "repo_id": "ILSpy", "token_count": 411 }
245
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <UseWpf>true</UseWpf> <GenerateAssemblyInfo>False</GenerateAssemblyInfo> <SignAssembly>True</SignAssembly> <TargetFramework>net8.0-windows</TargetFramework> <AssemblyOriginatorKeyFile>..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.snk</AssemblyOriginatorKeyFile> <EnableWindowsTargeting>true</EnableWindowsTargeting> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' == 'Debug'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' == 'Release'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <ItemGroup> <PackageReference Include="TomsToolbox.Wpf.Styles" /> </ItemGroup> </Project>
ILSpy/SharpTreeView/ICSharpCode.TreeView.csproj/0
{ "file_path": "ILSpy/SharpTreeView/ICSharpCode.TreeView.csproj", "repo_id": "ILSpy", "token_count": 313 }
246
ILAst Pattern Matching ================= Some IL instructions are classified as "patterns". ```c# abstract class PatternMatchILInstruction : IStoreInstruction { public ILInstruction TestedOperand { get; } public ILVariable Variable { get; } // variable that receives the match result; may also be a temporary } public bool IsPattern(this ILInstruction inst, out ILInstruction testedOperand) => inst switch { PatternMatchILInstruction pm => testedOperand = pm.TestedOperand; return true; LogicNot logicNot => IsPattern(logicNot.Operand, out testedOperand), Comp comp => testedOperand = comp.Left; return IsConstant(comp.Right); } ``` Every `match.*` instruction has the following properties: * The `TestedOperand` specifies what gets matched against the pattern. * The `Variable` stores the value of `TestedOperand` (after converting to the matched type, if appropriate). * If this variable is also used outside the `match.*` node, it corresponds to the C# `single_variable_designation`. * Otherwise it's a temporary used for pattern matching. * I think in both cases it should have VariableKind.PatternVar * The match instruction evaluates to `StackType.I4`: 0 if the pattern was matched, 1 otherwise. Some `match` instructions have a body with `List<ILInstruction> nestedPatterns`. Here every nested pattern must be a pattern according to `IsPattern()`, and the `testedOperand` of each must be a member of the `Variable` of the parent pattern. (members are: field, property, or deconstruction.result). (exception: `match.and`/`match.or`, these instead require the `testedOperand` to be exactly the `Variable` of the parent pattern) Examples -------- 1) `expr is var x` => `match.var(x = expr)` => ``` Block (VarPattern) { stloc x(expr) // single eval expr final: ldc.i4 1 // match always } ``` 2) `expr is T x` => `match.type T(x = expr) {}` => ``` Block (TypePattern) { stloc x(isinst T(expr)) final: x != null } ``` 3) `expr is C { A: var x } z` => ``` match.type C(z = expr) { match.var(x = z.A) } ``` => ``` Block (TypePattern) { stloc z(isinst T(expr)) final: (z != null) && Block(VarPattern) { stloc x(z.A) final: ldc.i4 1 } } ``` 4) `expr is C { A: var x, B: 42, C: { A: 4 } } z` => ``` match.type C(z = expr) { match.var (x = z.A), comp (z.B == 42), match.recursive (temp2 = z.C) { comp (temp2.A == 4) } } ``` => ``` Block (TypePattern) { stloc z(isinst C(expr)) final: (z != null) && Block(VarPattern) { stloc x(z.A) final: ldc.i4 1 } && comp (z.B == 42) && Block(RecursivePattern) { stloc temp2(z.C) final: (temp2 != null) && comp (temp2.A == 4) } } ``` 5) `expr is C(var x, var y, <4) { ... }` => ``` match.recursive.type.deconstruct(C tmp1 = expr) { match.var(x = deconstruct.result0(tmp1)), match.var(y = deconstruct.result1(tmp1)), comp(deconstruct.result2(tmp1) < 4), } ``` 6) `expr is C(1, D(2, 3))` => ``` match.type.deconstruct(C c = expr) { comp(deconstruct.result0(c) == 1), match.type.deconstruct(D d = deconstruct.result1(c)) { comp(deconstruct.result0(d) == 2), comp(deconstruct.result1(d) == 2), } } ``` 7) `x is >= 0 and var y and <= 100` ``` match.and(tmp1 = x) { comp(tmp1 >= 0), match.var(y = tmp1), comp(tmp1 <= 100) } ``` 8) `x is not C _` => ``` logic.not( match.type(C tmp1 = x) {} ) ``` 9) `expr is (var a, var b)` (when expr is object) => ``` match.type.deconstruct(ITuple tmp = expr) { match.var(a = deconstruct.result0(tmp)), match.var(b = deconstruct.result1(tmp)), } ``` 10) `expr is (var a, var b)` (when expr is ValueTuple<int, int>) => ``` match.recursive(tmp = expr) { match.var(a = tmp.Item1), match.var(b = tmp.Item2), } ```
ILSpy/doc/ILAst Pattern Matching.md/0
{ "file_path": "ILSpy/doc/ILAst Pattern Matching.md", "repo_id": "ILSpy", "token_count": 1939 }
247
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.U2D; using UnityEngine.Bindings; using System; namespace UnityEditor.U2D { [NativeHeader("Runtime/2D/SpriteAtlas/SpriteAtlas.h")] [NativeHeader("Editor/Src/2D/SpriteAtlas/SpriteAtlasPackingUtilities.h")] public class SpriteAtlasUtility { [FreeFunction("SpriteAtlasExtensions::EnableV2Import")] extern internal static void EnableV2Import(bool onOff); [FreeFunction("SpriteAtlasExtensions::CleanupAtlasPacking")] extern public static void CleanupAtlasPacking(); [FreeFunction("CollectAllSpriteAtlasesAndPack")] extern public static void PackAllAtlases(BuildTarget target, bool canCancel = true); [FreeFunction("PackSpriteAtlases")] extern internal static void PackAtlasesInternal(SpriteAtlas[] atlases, BuildTarget target, bool canCancel = true, bool invokedFromImporter = false, bool unloadSprites = false); public static void PackAtlases(SpriteAtlas[] atlases, BuildTarget target, bool canCancel = true) { if (atlases == null) throw new ArgumentNullException("atlases", "Value for parameter atlases is null"); foreach (var atlas in atlases) if (atlas == null) throw new ArgumentNullException("atlases", "One of the elements in atlases is null. Please check your Inputs."); PackAtlasesInternal(atlases, target, canCancel, false, true); } } [StructLayout(LayoutKind.Sequential)] public struct SpriteAtlasTextureSettings { [NativeName("anisoLevel")] private int m_AnisoLevel; [NativeName("compressionQuality")] private int m_CompressionQuality; [NativeName("maxTextureSize")] private int m_MaxTextureSize; [NativeName("textureCompression")] private int m_TextureCompression; [NativeName("filterMode")] private int m_FilterMode; [NativeName("generateMipMaps")] private bool m_GenerateMipMaps; [NativeName("readable")] private bool m_Readable; [NativeName("crunchedCompression")] private bool m_CrunchedCompression; [NativeName("sRGB")] private bool m_sRGB; public int maxTextureSize { get { return m_MaxTextureSize; } } public int anisoLevel { get { return m_AnisoLevel; } set { m_AnisoLevel = value; } } public FilterMode filterMode { get { return (FilterMode)m_FilterMode; } set { m_FilterMode = (int)value; } } public bool generateMipMaps { get { return m_GenerateMipMaps; } set { m_GenerateMipMaps = value; } } public bool readable { get { return m_Readable; } set { m_Readable = value; } } public bool sRGB { get { return m_sRGB; } set { m_sRGB = value; } } } [StructLayout(LayoutKind.Sequential)] public struct SpriteAtlasPackingSettings { [NativeName("blockOffset")] private int m_BlockOffset; [NativeName("padding")] private int m_Padding; [NativeName("allowAlphaSplitting")] private bool m_AllowAlphaSplitting; [NativeName("enableRotation")] private bool m_EnableRotation; [NativeName("enableTightPacking")] private bool m_EnableTightPacking; [NativeName("enableAlphaDilation")] private bool m_EnableAlphaDilation; public int blockOffset { get { return m_BlockOffset; } set { m_BlockOffset = value; } } public int padding { get { return m_Padding; } set { m_Padding = value; } } public bool enableRotation { get { return m_EnableRotation; } set { m_EnableRotation = value; } } public bool enableTightPacking { get { return m_EnableTightPacking; } set { m_EnableTightPacking = value; } } public bool enableAlphaDilation { get { return m_EnableAlphaDilation; } set { m_EnableAlphaDilation = value; } } } [NativeHeader("Editor/Src/AssetPipeline/TextureImporting/TextureImporterTypes.h")] [NativeHeader("Editor/Src/AssetPipeline/TextureImporting/TextureImporter.bindings.h")] [NativeHeader("Editor/Src/2D/SpriteAtlas/SpriteAtlas_EditorTypes.h")] [NativeHeader("Runtime/2D/SpriteAtlas/SpriteAtlas.h")] public static class SpriteAtlasExtensions { extern public static void Add([NotNull] this SpriteAtlas spriteAtlas, UnityEngine.Object[] objects); extern public static void Remove([NotNull] this SpriteAtlas spriteAtlas, UnityEngine.Object[] objects); extern internal static void RemoveAt([NotNull] this SpriteAtlas spriteAtlas, int index); extern public static UnityEngine.Object[] GetPackables([NotNull] this SpriteAtlas spriteAtlas); extern public static SpriteAtlasTextureSettings GetTextureSettings([NotNull] this SpriteAtlas spriteAtlas); extern public static void SetTextureSettings([NotNull] this SpriteAtlas spriteAtlas, SpriteAtlasTextureSettings src); extern public static SpriteAtlasPackingSettings GetPackingSettings([NotNull] this SpriteAtlas spriteAtlas); extern public static void SetPackingSettings([NotNull] this SpriteAtlas spriteAtlas, SpriteAtlasPackingSettings src); extern public static TextureImporterPlatformSettings GetPlatformSettings([NotNull] this SpriteAtlas spriteAtlas, string buildTarget); extern public static void SetPlatformSettings([NotNull] this SpriteAtlas spriteAtlas, TextureImporterPlatformSettings src); extern public static void SetIncludeInBuild([NotNull] this SpriteAtlas spriteAtlas, bool value); extern public static void SetIsVariant([NotNull] this SpriteAtlas spriteAtlas, bool value); extern public static void SetMasterAtlas([NotNull] this SpriteAtlas spriteAtlas, SpriteAtlas value); extern public static void SetVariantScale([NotNull] this SpriteAtlas spriteAtlas, float value); extern public static bool IsIncludeInBuild([NotNull] this SpriteAtlas spriteAtlas); extern public static SpriteAtlas GetMasterAtlas([NotNull] this SpriteAtlas spriteAtlas); extern internal static void CopyMasterAtlasSettings([NotNull] this SpriteAtlas spriteAtlas); extern internal static string GetHash([NotNull] this SpriteAtlas spriteAtlas); extern internal static Texture2D[] GetPreviewTextures([NotNull] this SpriteAtlas spriteAtlas); extern internal static Texture2D[] GetPreviewAlphaTextures([NotNull] this SpriteAtlas spriteAtlas); extern internal static TextureFormat GetTextureFormat([NotNull] this SpriteAtlas spriteAtlas, BuildTarget target); extern internal static Sprite[] GetPackedSprites([NotNull] this SpriteAtlas spriteAtlas); extern internal static Hash128 GetStoredHash([NotNull] this SpriteAtlas spriteAtlas); extern internal static TextureImporterPlatformSettings GetSecondaryPlatformSettings([NotNull] this SpriteAtlas spriteAtlas, string buildTarget, string secondaryTextureName); extern internal static void SetSecondaryPlatformSettings([NotNull] this SpriteAtlas spriteAtlas, TextureImporterPlatformSettings src, string secondaryTextureName); extern internal static bool GetSecondaryColorSpace([NotNull] this SpriteAtlas spriteAtlas, string secondaryTextureName); extern internal static void SetSecondaryColorSpace([NotNull] this SpriteAtlas spriteAtlas, string secondaryTextureName, bool srGB); extern internal static void DeleteSecondaryPlatformSettings([NotNull] this SpriteAtlas spriteAtlas, string secondaryTextureName); extern internal static string GetSecondaryTextureNameInAtlas(string atlasTextureName); extern internal static string GetPageNumberInAtlas(string atlasTextureName); } }
UnityCsReference/Editor/Mono/2D/SpriteAtlas/EditorSpriteAtlas.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/2D/SpriteAtlas/EditorSpriteAtlas.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2717 }
248
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using System.Collections.Generic; using UnityEditor.ShortcutManagement; using UnityEditorInternal; namespace UnityEditor { internal enum WrapModeFixed { Default = (int)WrapMode.Default, Once = (int)WrapMode.Once, Loop = (int)WrapMode.Loop, ClampForever = (int)WrapMode.ClampForever, PingPong = (int)WrapMode.PingPong } [Serializable] class AnimEditor : ScriptableObject { // Active Animation windows private static List<AnimEditor> s_AnimationWindows = new List<AnimEditor>(); public static List<AnimEditor> GetAllAnimationWindows() { return s_AnimationWindows; } public bool stateDisabled { get { return m_State.disabled; } } [SerializeField] private SplitterState m_HorizontalSplitter; [SerializeReference] private AnimationWindowState m_State; [SerializeReference] private DopeSheetEditor m_DopeSheet; [SerializeReference] private CurveEditor m_CurveEditor; [SerializeField] private AnimationWindowHierarchy m_Hierarchy; [SerializeField] private AnimationWindowClipPopup m_ClipPopup; [SerializeField] private AnimationEventTimeLine m_Events; [SerializeField] private AnimEditorOverlay m_Overlay; [SerializeField] private EditorWindow m_OwnerWindow; [System.NonSerialized] private Rect m_Position; [System.NonSerialized] private bool m_TriggerFraming; [System.NonSerialized] private bool m_Initialized; private float hierarchyWidth { get { return m_HorizontalSplitter.realSizes[0]; } } private float contentWidth { get { return m_HorizontalSplitter.realSizes[1]; } } internal static PrefColor kEulerXColor = new PrefColor("Animation/EulerX", 1.0f, 0.0f, 1.0f, 1.0f); internal static PrefColor kEulerYColor = new PrefColor("Animation/EulerY", 1.0f, 1.0f, 0.0f, 1.0f); internal static PrefColor kEulerZColor = new PrefColor("Animation/EulerZ", 0.0f, 1.0f, 1.0f, 1.0f); static private Color s_SelectionRangeColorLight = new Color32(255, 255, 255, 90); static private Color s_SelectionRangeColorDark = new Color32(200, 200, 200, 40); static private Color selectionRangeColor { get { return EditorGUIUtility.isProSkin ? s_SelectionRangeColorDark : s_SelectionRangeColorLight; } } static private Color s_OutOfRangeColorLight = new Color32(160, 160, 160, 127); static private Color s_OutOfRangeColorDark = new Color32(40, 40, 40, 127); static private Color outOfRangeColor { get { return EditorGUIUtility.isProSkin ? s_OutOfRangeColorDark : s_OutOfRangeColorLight; } } static private Color s_InRangeColorLight = new Color32(211, 211, 211, 255); static private Color s_InRangeColorDark = new Color32(75, 75, 75, 255); static private Color inRangeColor { get { return EditorGUIUtility.isProSkin ? s_InRangeColorDark : s_InRangeColorLight; } } static private Color s_FilterBySelectionColorLight = new Color(0.82f, 0.97f, 1.00f, 1.00f); static private Color s_FilterBySelectionColorDark = new Color(0.54f, 0.85f, 1.00f, 1.00f); static private Color filterBySelectionColor { get { return EditorGUIUtility.isProSkin ? s_FilterBySelectionColorDark : s_FilterBySelectionColorLight; } } internal const int kSliderThickness = 13; internal const int kIntFieldWidth = 35; internal const int kHierarchyMinWidth = 300; internal const int kToggleButtonWidth = 80; internal const float kDisabledRulerAlpha = 0.12f; private int layoutRowHeight { get { return (int)EditorGUI.kWindowToolbarHeight; } } internal struct FrameRateMenuEntry { public FrameRateMenuEntry(GUIContent content, float value) { this.content = content; this.value = value; } public GUIContent content; public float value; } internal static FrameRateMenuEntry[] kAvailableFrameRates = new FrameRateMenuEntry[] { new FrameRateMenuEntry(EditorGUIUtility.TextContent("Set Sample Rate/24"), 24f), new FrameRateMenuEntry(EditorGUIUtility.TextContent("Set Sample Rate/25"), 25f), new FrameRateMenuEntry(EditorGUIUtility.TextContent("Set Sample Rate/30"), 30f), new FrameRateMenuEntry(EditorGUIUtility.TextContent("Set Sample Rate/50"), 50f), new FrameRateMenuEntry(EditorGUIUtility.TextContent("Set Sample Rate/60"), 60f) }; public AnimationWindowState state { get { return m_State; } } public AnimationWindowSelectionItem selection { get { return m_State.selection; } set { m_State.selection = value; } } public IAnimationWindowController controlInterface { get { return state.controlInterface; } } public IAnimationWindowController overrideControlInterface { get { return state.overrideControlInterface; } set { state.overrideControlInterface = value; } } private bool triggerFraming { set { m_TriggerFraming = value; } get { return m_TriggerFraming; } } internal CurveEditor curveEditor { get { return m_CurveEditor; } } internal DopeSheetEditor dopeSheetEditor { get { return m_DopeSheet; } } public void OnAnimEditorGUI(EditorWindow parent, Rect position) { m_DopeSheet.m_Owner = parent; m_OwnerWindow = parent; m_Position = position; if (!m_Initialized) Initialize(); m_State.OnGUI(); if (m_State.disabled && m_State.recording) m_State.recording = false; SynchronizeLayout(); using (new EditorGUI.DisabledScope(m_State.disabled || m_State.animatorIsOptimized)) { int optionsID = GUIUtility.GetControlID(FocusType.Passive); if (Event.current.type != EventType.Repaint) OptionsOnGUI(optionsID); OverlayEventOnGUI(); GUILayout.BeginHorizontal(); SplitterGUILayout.BeginHorizontalSplit(m_HorizontalSplitter); // Left side GUILayout.BeginVertical(); // First row of controls GUILayout.BeginHorizontal(AnimationWindowStyles.animPlayToolBar); PlayControlsOnGUI(); GUILayout.EndHorizontal(); // Second row of controls GUILayout.BeginHorizontal(AnimationWindowStyles.animClipToolBar); LinkOptionsOnGUI(); ClipSelectionDropDownOnGUI(); GUILayout.FlexibleSpace(); FrameRateInputFieldOnGUI(); FilterBySelectionButtonOnGUI(); AddKeyframeButtonOnGUI(); AddEventButtonOnGUI(); GUILayout.EndHorizontal(); HierarchyOnGUI(); // Bottom row of controls using (new GUILayout.HorizontalScope(AnimationWindowStyles.toolbarBottom)) { TabSelectionOnGUI(); } GUILayout.EndVertical(); // Right side GUILayout.BeginVertical(); // Acquire Rects Rect timerulerRect = GUILayoutUtility.GetRect(contentWidth, layoutRowHeight); Rect eventsRect = GUILayoutUtility.GetRect(contentWidth, layoutRowHeight - 1); Rect contentLayoutRect = GUILayoutUtility.GetRect(contentWidth, contentWidth, 0f, float.MaxValue, GUILayout.ExpandHeight(true)); // MainContent must be done first since it resizes the Zoomable area. MainContentOnGUI(contentLayoutRect); TimeRulerOnGUI(timerulerRect); EventLineOnGUI(eventsRect); GUILayout.EndVertical(); SplitterGUILayout.EndHorizontalSplit(); GUILayout.EndHorizontal(); // Overlay OverlayOnGUI(contentLayoutRect); if (Event.current.type == EventType.Repaint) { OptionsOnGUI(optionsID); AnimationWindowStyles.separator.Draw(new Rect(hierarchyWidth, 0, 1, position.height), false, false, false, false); } RenderEventTooltip(); } } void MainContentOnGUI(Rect contentLayoutRect) { // Bail out if the hierarchy in animator is optimized. if (m_State.animatorIsOptimized) { GUI.Label(contentLayoutRect, GUIContent.none, AnimationWindowStyles.dopeSheetBackground); Vector2 textSize = GUI.skin.label.CalcSize(AnimationWindowStyles.animatorOptimizedText); Rect labelRect = new Rect(contentLayoutRect.x + contentLayoutRect.width * .5f - textSize.x * .5f, contentLayoutRect.y + contentLayoutRect.height * .5f - textSize.y * .5f, textSize.x, textSize.y); GUI.Label(labelRect, AnimationWindowStyles.animatorOptimizedText); return; } var mainAreaControlID = 0; if (m_State.disabled) { SetupWizardOnGUI(contentLayoutRect); } else { Event evt = Event.current; if (evt.type == EventType.MouseDown && contentLayoutRect.Contains(evt.mousePosition)) m_Events.ClearSelection(); if (triggerFraming && evt.type == EventType.Repaint) { m_DopeSheet.FrameClip(); m_CurveEditor.FrameClip(true, true); triggerFraming = false; } if (m_State.showCurveEditor) { CurveEditorOnGUI(contentLayoutRect); mainAreaControlID = m_CurveEditor.areaControlID; } else { DopeSheetOnGUI(contentLayoutRect); mainAreaControlID = m_DopeSheet.areaControlID; } } HandleMainAreaCopyPaste(mainAreaControlID); } private void OverlayEventOnGUI() { if (m_State.animatorIsOptimized) return; if (m_State.disabled) return; Rect overlayRect = new Rect(hierarchyWidth - 1, 0f, contentWidth - kSliderThickness, m_Position.height - kSliderThickness); GUI.BeginGroup(overlayRect); m_Overlay.HandleEvents(); GUI.EndGroup(); } private void OverlayOnGUI(Rect contentRect) { if (m_State.animatorIsOptimized) return; if (m_State.disabled) return; if (Event.current.type != EventType.Repaint) return; Rect contentRectNoSliders = new Rect(contentRect.xMin, contentRect.yMin, contentRect.width - kSliderThickness, contentRect.height - kSliderThickness); Rect overlayRectNoSliders = new Rect(hierarchyWidth - 1, 0f, contentWidth - kSliderThickness, m_Position.height - kSliderThickness); GUI.BeginGroup(overlayRectNoSliders); Rect localRect = new Rect(0, 0, overlayRectNoSliders.width, overlayRectNoSliders.height); Rect localContentRect = contentRectNoSliders; localContentRect.position -= overlayRectNoSliders.min; m_Overlay.OnGUI(localRect, localContentRect); GUI.EndGroup(); } public void Update() { if (m_State == null) return; PlaybackUpdate(); } public void OnEnable() { s_AnimationWindows.Add(this); if (m_State == null) { m_State = new AnimationWindowState(); m_State.animEditor = this; InitializeHorizontalSplitter(); InitializeClipSelection(); InitializeDopeSheet(); InitializeEvents(); InitializeCurveEditor(); InitializeOverlay(); } InitializeNonserializedValues(); m_State.timeArea = m_State.showCurveEditor ? (TimeArea)m_CurveEditor : m_DopeSheet; m_DopeSheet.state = m_State; m_ClipPopup.state = m_State; m_Overlay.state = m_State; m_State.OnEnable(); m_CurveEditor.curvesUpdated += SaveChangedCurvesFromCurveEditor; m_CurveEditor.OnEnable(); } public void OnDisable() { s_AnimationWindows.Remove(this); if (m_CurveEditor != null) { m_CurveEditor.curvesUpdated -= SaveChangedCurvesFromCurveEditor; m_CurveEditor.OnDisable(); } m_DopeSheet?.OnDisable(); m_State.OnDisable(); } public void OnDestroy() { m_CurveEditor?.OnDestroy(); m_State?.OnDestroy(); } public void OnSelectionChanged() { triggerFraming = true; // Framing of clip can only be done after Layout. Here we just order it to happen later on. Repaint(); } public void OnSelectionUpdated() { m_State.OnSelectionUpdated(); Repaint(); } public void OnStartLiveEdit() { SaveCurveEditorKeySelection(); } public void OnEndLiveEdit() { UpdateSelectedKeysToCurveEditor(); m_State.ResampleAnimation(); } public void OnLostFocus() { // RenameOverlay might still be active, close before switching to another window. if (m_Hierarchy != null) m_Hierarchy.EndNameEditing(true); // Stop text editing. FrameRate ui or Frame ui may still be in edition mode. EditorGUI.EndEditingActiveTextField(); } private void PlaybackUpdate() { if (m_State.disabled && m_State.playing) m_State.playing = false; if (m_State.PlaybackUpdate()) Repaint(); } private void SetupWizardOnGUI(Rect position) { GUI.Label(position, GUIContent.none, AnimationWindowStyles.dopeSheetBackground); Rect positionWithoutScrollBar = new Rect(position.x, position.y, position.width - kSliderThickness, position.height - kSliderThickness); GUI.BeginClip(positionWithoutScrollBar); GUI.enabled = true; m_State.showCurveEditor = false; m_State.timeArea = m_DopeSheet; m_State.timeArea.SetShownHRangeInsideMargins(0f, 1f); bool animatableObject = m_State.activeGameObject && !EditorUtility.IsPersistent(m_State.activeGameObject); if (animatableObject) { var missingObjects = (!m_State.activeRootGameObject && !m_State.activeAnimationClip) ? AnimationWindowStyles.animatorAndAnimationClip.text : AnimationWindowStyles.animationClip.text; string txt = String.Format(AnimationWindowStyles.formatIsMissing.text, m_State.activeGameObject.name, missingObjects); const float buttonWidth = 70f; const float buttonHeight = 20f; const float buttonPadding = 3f; GUIContent textContent = GUIContent.Temp(txt); Vector2 textSize = GUI.skin.label.CalcSize(textContent); Rect labelRect = new Rect(positionWithoutScrollBar.width * .5f - textSize.x * .5f, positionWithoutScrollBar.height * .5f - textSize.y * .5f, textSize.x, textSize.y); GUI.Label(labelRect, textContent); Rect buttonRect = new Rect(positionWithoutScrollBar.width * .5f - buttonWidth * .5f, labelRect.yMax + buttonPadding, buttonWidth, buttonHeight); if (GUI.Button(buttonRect, AnimationWindowStyles.create)) { if (AnimationWindowUtility.InitializeGameobjectForAnimation(m_State.activeGameObject)) { Component animationPlayer = AnimationWindowUtility.GetClosestAnimationPlayerComponentInParents(m_State.activeGameObject.transform); m_State.activeAnimationClip = AnimationUtility.GetAnimationClips(animationPlayer.gameObject)[0]; } // Layout has changed, bail out now. EditorGUIUtility.ExitGUI(); } } else { Color oldColor = GUI.color; GUI.color = Color.gray; Vector2 textSize = GUI.skin.label.CalcSize(AnimationWindowStyles.noAnimatableObjectSelectedText); Rect labelRect = new Rect(positionWithoutScrollBar.width * .5f - textSize.x * .5f, positionWithoutScrollBar.height * .5f - textSize.y * .5f, textSize.x, textSize.y); GUI.Label(labelRect, AnimationWindowStyles.noAnimatableObjectSelectedText); GUI.color = oldColor; } GUI.EndClip(); GUI.enabled = false; // Reset state to false. It's always false originally for SetupWizardOnGUI. } private void EventLineOnGUI(Rect eventsRect) { eventsRect.width -= kSliderThickness; GUI.Label(eventsRect, GUIContent.none, AnimationWindowStyles.eventBackground); using (new EditorGUI.DisabledScope(!selection.animationIsEditable)) { m_Events.EventLineGUI(eventsRect, m_State); } } private void RenderEventTooltip() { m_Events.DrawInstantTooltip(m_Position); } private void TabSelectionOnGUI() { GUILayout.FlexibleSpace(); EditorGUI.BeginChangeCheck(); GUILayout.Toggle(!m_State.showCurveEditor, AnimationWindowStyles.dopesheet, AnimationWindowStyles.miniToolbarButton, GUILayout.Width(kToggleButtonWidth)); GUILayout.Toggle(m_State.showCurveEditor, AnimationWindowStyles.curves, EditorStyles.toolbarButtonRight, GUILayout.Width(kToggleButtonWidth)); if (EditorGUI.EndChangeCheck()) { SwitchBetweenCurvesAndDopesheet(); } } private void HierarchyOnGUI() { Rect hierarchyLayoutRect = GUILayoutUtility.GetRect(hierarchyWidth, hierarchyWidth, 0f, float.MaxValue, GUILayout.ExpandHeight(true)); if (!m_State.showReadOnly && !m_State.selection.animationIsEditable) { Vector2 labelSize = GUI.skin.label.CalcSize(AnimationWindowStyles.readOnlyPropertiesLabel); const float buttonWidth = 210f; const float buttonHeight = 20f; const float buttonPadding = 3f; Rect labelRect = new Rect(hierarchyLayoutRect.x + hierarchyLayoutRect.width * .5f - labelSize.x * .5f, hierarchyLayoutRect.y + hierarchyLayoutRect.height * .5f - labelSize.y, labelSize.x, labelSize.y); Rect buttonRect = new Rect(hierarchyLayoutRect.x + hierarchyLayoutRect.width * .5f - buttonWidth * .5f, labelRect.yMax + buttonPadding, buttonWidth, buttonHeight); GUI.Label(labelRect, AnimationWindowStyles.readOnlyPropertiesLabel); if (GUI.Button(buttonRect, AnimationWindowStyles.readOnlyPropertiesButton)) { m_State.showReadOnly = true; // Layout has changed, bail out now. EditorGUIUtility.ExitGUI(); } return; } if (!m_State.disabled) m_Hierarchy.OnGUI(hierarchyLayoutRect); } private void FrameRateInputFieldOnGUI() { if (!m_State.showFrameRate) return; using (new EditorGUI.DisabledScope(!selection.animationIsEditable)) { GUILayout.Label(AnimationWindowStyles.samples, EditorStyles.toolbarLabel); EditorGUI.BeginChangeCheck(); int clipFrameRate = EditorGUILayout.DelayedIntField((int)m_State.clipFrameRate, EditorStyles.toolbarTextField, GUILayout.Width(kIntFieldWidth)); if (EditorGUI.EndChangeCheck()) { m_State.clipFrameRate = clipFrameRate; UpdateSelectedKeysToCurveEditor(); } } } private void ClipSelectionDropDownOnGUI() { m_ClipPopup.OnGUI(); } private void DopeSheetOnGUI(Rect position) { Rect noVerticalSliderRect = new Rect(position.xMin, position.yMin, position.width - kSliderThickness, position.height); if (Event.current.type == EventType.Repaint) { m_DopeSheet.rect = noVerticalSliderRect; m_DopeSheet.SetTickMarkerRanges(); m_DopeSheet.RecalculateBounds(); } if (m_State.showCurveEditor) return; Rect noSlidersRect = new Rect(position.xMin, position.yMin, position.width - kSliderThickness, position.height - kSliderThickness); m_DopeSheet.BeginViewGUI(); GUI.Label(position, GUIContent.none, AnimationWindowStyles.dopeSheetBackground); if (!m_State.disabled) { m_DopeSheet.TimeRuler(noSlidersRect, m_State.frameRate, false, true, kDisabledRulerAlpha, m_State.timeFormat); // grid } m_DopeSheet.OnGUI(noSlidersRect, m_State.hierarchyState.scrollPos * -1); m_DopeSheet.EndViewGUI(); Rect verticalScrollBarPosition = new Rect(noVerticalSliderRect.xMax, noVerticalSliderRect.yMin, kSliderThickness, noSlidersRect.height); float visibleHeight = m_Hierarchy.GetTotalRect().height; float contentHeight = Mathf.Max(visibleHeight, m_Hierarchy.GetContentSize().y); m_State.hierarchyState.scrollPos.y = GUI.VerticalScrollbar(verticalScrollBarPosition, m_State.hierarchyState.scrollPos.y, visibleHeight, 0f, contentHeight); if (m_DopeSheet.spritePreviewLoading == true) Repaint(); } private void CurveEditorOnGUI(Rect position) { if (Event.current.type == EventType.Repaint) { m_CurveEditor.rect = position; m_CurveEditor.SetTickMarkerRanges(); } Rect noSlidersRect = new Rect(position.xMin, position.yMin, position.width - kSliderThickness, position.height - kSliderThickness); m_CurveEditor.vSlider = m_State.showCurveEditor; m_CurveEditor.hSlider = m_State.showCurveEditor; // Sync animation curves in curve editor. Do it only once per frame. if (Event.current.type == EventType.Layout) UpdateCurveEditorData(); m_CurveEditor.BeginViewGUI(); if (!m_State.disabled) { GUI.Box(noSlidersRect, GUIContent.none, AnimationWindowStyles.curveEditorBackground); m_CurveEditor.GridGUI(); } EditorGUI.BeginChangeCheck(); m_CurveEditor.CurveGUI(); if (EditorGUI.EndChangeCheck()) { SaveChangedCurvesFromCurveEditor(); } m_CurveEditor.EndViewGUI(); } private void TimeRulerOnGUI(Rect timeRulerRect) { Rect timeRulerRectNoScrollbar = new Rect(timeRulerRect.xMin, timeRulerRect.yMin, timeRulerRect.width - kSliderThickness, timeRulerRect.height); Rect timeRulerBackgroundRect = timeRulerRectNoScrollbar; GUI.Box(timeRulerBackgroundRect, GUIContent.none, AnimationWindowStyles.timeRulerBackground); if (!m_State.disabled) { RenderInRangeOverlay(timeRulerRectNoScrollbar); RenderSelectionOverlay(timeRulerRectNoScrollbar); } m_State.timeArea.TimeRuler(timeRulerRectNoScrollbar, m_State.frameRate, true, false, 1f, m_State.timeFormat); if (!m_State.disabled) RenderOutOfRangeOverlay(timeRulerRectNoScrollbar); } private GenericMenu GenerateOptionsMenu() { GenericMenu menu = new GenericMenu(); menu.AddItem(EditorGUIUtility.TextContent("Seconds"), m_State.timeFormat == TimeArea.TimeFormat.TimeFrame, () => m_State.timeFormat = TimeArea.TimeFormat.TimeFrame); menu.AddItem(EditorGUIUtility.TextContent("Frames"), m_State.timeFormat == TimeArea.TimeFormat.Frame, () => m_State.timeFormat = TimeArea.TimeFormat.Frame); menu.AddSeparator(""); menu.AddItem(EditorGUIUtility.TextContent("Ripple"), m_State.rippleTime, () => m_State.rippleTime = !m_State.rippleTime); menu.AddSeparator(""); menu.AddItem(EditorGUIUtility.TextContent("Show Sample Rate"), m_State.showFrameRate, () => m_State.showFrameRate = !m_State.showFrameRate); bool isAnimatable = selection != null && selection.animationIsEditable; GenericMenu.MenuFunction2 nullMenuFunction2 = null; for (int i = 0; i < kAvailableFrameRates.Length; ++i) { FrameRateMenuEntry entry = kAvailableFrameRates[i]; bool isActive = m_State.clipFrameRate.Equals(entry.value); menu.AddItem(entry.content, isActive, isAnimatable ? SetFrameRate : nullMenuFunction2, entry.value); } menu.AddSeparator(""); menu.AddItem(EditorGUIUtility.TextContent("Show Read-only Properties"), m_State.showReadOnly, () => m_State.showReadOnly = !m_State.showReadOnly); return menu; } private void OptionsOnGUI(int controlID) { Rect layoutRect = new Rect(hierarchyWidth, 0f, contentWidth, layoutRowHeight); GUI.BeginGroup(layoutRect); Vector2 optionsSize = EditorStyles.toolbarButtonRight.CalcSize(AnimationWindowStyles.optionsContent); Rect optionsRect = new Rect(layoutRect.width - kSliderThickness, 0f, optionsSize.x, optionsSize.y); GUI.Box(optionsRect, GUIContent.none, AnimationWindowStyles.animPlayToolBar); if (EditorGUI.DropdownButton(controlID, optionsRect, AnimationWindowStyles.optionsContent, AnimationWindowStyles.optionsButton)) { var menu = GenerateOptionsMenu(); menu.ShowAsContext(); } GUI.EndGroup(); } internal void SetFrameRate(object frameRate) { m_State.clipFrameRate = (float)frameRate; UpdateSelectedKeysToCurveEditor(); } private void FilterBySelectionButtonOnGUI() { Color backupColor = GUI.color; if (m_State.filterBySelection) { Color selectionColor = filterBySelectionColor; selectionColor.a *= GUI.color.a; GUI.color = selectionColor; } EditorGUI.BeginChangeCheck(); bool filterBySelection = GUILayout.Toggle(m_State.filterBySelection, AnimationWindowStyles.filterBySelectionContent, EditorStyles.toolbarButton); if (EditorGUI.EndChangeCheck()) { m_State.filterBySelection = filterBySelection; } GUI.color = backupColor; } private void AddEventButtonOnGUI() { using (new EditorGUI.DisabledScope(!selection.animationIsEditable)) { if (GUILayout.Button(AnimationWindowStyles.addEventContent, AnimationWindowStyles.animClipToolbarButton)) m_Events.AddEvent(m_State.currentTime, selection.rootGameObject, selection.animationClip); } } private void AddKeyframeButtonOnGUI() { bool canAddKey = selection.animationIsEditable && m_State.filteredCurves.Count != 0; using (new EditorGUI.DisabledScope(!canAddKey)) { if (GUILayout.Button(AnimationWindowStyles.addKeyframeContent, AnimationWindowStyles.animClipToolbarButton)) { SaveCurveEditorKeySelection(); var keyTime = AnimationKeyTime.Time(m_State.currentTime, m_State.frameRate); AnimationWindowUtility.AddSelectedKeyframes(m_State, keyTime); UpdateSelectedKeysToCurveEditor(); // data is scheduled for an update, bail out now to avoid using out of date data. EditorGUIUtility.ExitGUI(); } } } private void PlayControlsOnGUI() { using (new EditorGUI.DisabledScope(!m_State.canPreview)) { PreviewButtonOnGUI(); } using (new EditorGUI.DisabledScope(!m_State.canRecord)) { RecordButtonOnGUI(); } if (GUILayout.Button(AnimationWindowStyles.firstKeyContent, EditorStyles.toolbarButton)) { state.GoToFirstKeyframe(); // Stop text editing. User may be editing frame navigation ui which will not update until we exit text editing. EditorGUI.EndEditingActiveTextField(); } if (GUILayout.Button(AnimationWindowStyles.prevKeyContent, EditorStyles.toolbarButton)) { state.GoToPreviousKeyframe(); // Stop text editing. User may be editing frame navigation ui which will not update until we exit text editing. EditorGUI.EndEditingActiveTextField(); } using (new EditorGUI.DisabledScope(!m_State.canPlay)) { PlayButtonOnGUI(); } if (GUILayout.Button(AnimationWindowStyles.nextKeyContent, EditorStyles.toolbarButton)) { state.GoToNextKeyframe(); // Stop text editing. User may be editing frame navigation ui which will not update until we exit text editing. EditorGUI.EndEditingActiveTextField(); } if (GUILayout.Button(AnimationWindowStyles.lastKeyContent, EditorStyles.toolbarButton)) { state.GoToLastKeyframe(); // Stop text editing. User may be editing frame navigation ui which will not update until we exit text editing. EditorGUI.EndEditingActiveTextField(); } GUILayout.FlexibleSpace(); EditorGUI.BeginChangeCheck(); int newFrame = EditorGUILayout.DelayedIntField(m_State.currentFrame, EditorStyles.toolbarTextField, GUILayout.Width(kIntFieldWidth)); if (EditorGUI.EndChangeCheck()) { state.currentFrame = newFrame; } } private void LinkOptionsOnGUI() { if (m_State.linkedWithSequencer) { if (GUILayout.Toggle(true, AnimationWindowStyles.sequencerLinkContent, EditorStyles.toolbarButton) == false) { m_State.linkedWithSequencer = false; m_State.selection = null; m_State.overrideControlInterface = null; // Layout has changed, bail out now. EditorGUIUtility.ExitGUI(); } } } static void ExecuteShortcut(ShortcutArguments args, Action<AnimEditor> exp) { var animationWindow = (AnimationWindow)args.context; var animEditor = animationWindow.animEditor; if (EditorWindow.focusedWindow != animationWindow) return; if (animEditor.stateDisabled || animEditor.state.animatorIsOptimized) return; exp(animEditor); animEditor.Repaint(); } static void ExecuteShortcut(ShortcutArguments args, Action<AnimationWindowState> exp) { ExecuteShortcut(args, animEditor => exp(animEditor.state)); } [FormerlyPrefKeyAs("Animation/Show Curves", "c")] [Shortcut("Animation/Show Curves", typeof(AnimationWindow), KeyCode.C)] static void ShowCurves(ShortcutArguments args) { ExecuteShortcut(args, animEditor => { animEditor.SwitchBetweenCurvesAndDopesheet(); }); } [FormerlyPrefKeyAs("Animation/Play Animation", " ")] [Shortcut("Animation/Play Animation", typeof(AnimationWindow), KeyCode.Space)] static void TogglePlayAnimation(ShortcutArguments args) { ExecuteShortcut(args, state => { state.playing = !state.playing; }); } [FormerlyPrefKeyAs("Animation/Next Frame", ".")] [Shortcut("Animation/Next Frame", typeof(AnimationWindow), KeyCode.Period)] static void NextFrame(ShortcutArguments args) { ExecuteShortcut(args, state => state.GoToNextFrame()); } [FormerlyPrefKeyAs("Animation/Previous Frame", ",")] [Shortcut("Animation/Previous Frame", typeof(AnimationWindow), KeyCode.Comma)] static void PreviousFrame(ShortcutArguments args) { ExecuteShortcut(args, state => state.GoToPreviousFrame()); } [FormerlyPrefKeyAs("Animation/Previous Keyframe", "&,")] [Shortcut("Animation/Previous Keyframe", typeof(AnimationWindow), KeyCode.Comma, ShortcutModifiers.Alt)] static void PreviousKeyFrame(ShortcutArguments args) { ExecuteShortcut(args, state => state.GoToPreviousKeyframe()); } [FormerlyPrefKeyAs("Animation/Next Keyframe", "&.")] [Shortcut("Animation/Next Keyframe", typeof(AnimationWindow), KeyCode.Period, ShortcutModifiers.Alt)] static void NextKeyFrame(ShortcutArguments args) { ExecuteShortcut(args, state => state.GoToNextKeyframe()); } [FormerlyPrefKeyAs("Animation/First Keyframe", "#,")] [Shortcut("Animation/First Keyframe", typeof(AnimationWindow), KeyCode.Comma, ShortcutModifiers.Shift)] static void FirstKeyFrame(ShortcutArguments args) { ExecuteShortcut(args, state => state.GoToFirstKeyframe()); } [FormerlyPrefKeyAs("Animation/Last Keyframe", "#.")] [Shortcut("Animation/Last Keyframe", typeof(AnimationWindow), KeyCode.Period, ShortcutModifiers.Shift)] static void LastKeyFrame(ShortcutArguments args) { ExecuteShortcut(args, state => state.GoToLastKeyframe()); } [FormerlyPrefKeyAs("Animation/Key Selected", "k")] [Shortcut("Animation/Key Selected", null, KeyCode.K)] static void KeySelected(ShortcutArguments args) { AnimationWindow animationWindow = AnimationWindow.GetAllAnimationWindows().Find(aw => (aw.state.previewing || aw == EditorWindow.focusedWindow)); if (animationWindow == null) return; var animEditor = animationWindow.animEditor; animEditor.SaveCurveEditorKeySelection(); AnimationWindowUtility.AddSelectedKeyframes(animEditor.m_State, AnimationKeyTime.Frame(animEditor.state.currentFrame, animEditor.state.frameRate)); animEditor.state.ClearCandidates(); animEditor.UpdateSelectedKeysToCurveEditor(); animEditor.Repaint(); } [FormerlyPrefKeyAs("Animation/Key Modified", "#k")] [Shortcut("Animation/Key Modified", null, KeyCode.K, ShortcutModifiers.Shift)] static void KeyModified(ShortcutArguments args) { AnimationWindow animationWindow = AnimationWindow.GetAllAnimationWindows().Find(aw => (aw.state.previewing || aw == EditorWindow.focusedWindow)); if (animationWindow == null) return; var animEditor = animationWindow.animEditor; animEditor.SaveCurveEditorKeySelection(); animEditor.state.ProcessCandidates(); animEditor.UpdateSelectedKeysToCurveEditor(); animEditor.Repaint(); } [Shortcut("Animation/Toggle Ripple", typeof(AnimationWindow), KeyCode.Alpha2, ShortcutModifiers.Shift)] static void ToggleRipple(ShortcutArguments args) { ExecuteShortcut(args, animEditor => { animEditor.state.rippleTime = !animEditor.state.rippleTime; }); } [ClutchShortcut("Animation/Ripple (Clutch)", typeof(AnimationWindow), KeyCode.Alpha2)] static void ClutchRipple(ShortcutArguments args) { ExecuteShortcut(args, animEditor => { animEditor.state.rippleTimeClutch = args.stage == ShortcutStage.Begin; }); } [Shortcut("Animation/Frame All", typeof(AnimationWindow), KeyCode.A)] static void FrameAll(ShortcutArguments args) { ExecuteShortcut(args, animEditor => { animEditor.triggerFraming = true; }); } private void PlayButtonOnGUI() { EditorGUI.BeginChangeCheck(); bool playbackEnabled = GUILayout.Toggle(m_State.playing, AnimationWindowStyles.playContent, EditorStyles.toolbarButton); if (EditorGUI.EndChangeCheck()) { m_State.playing = playbackEnabled; // Stop text editing. User may be editing frame navigation ui which will not update until we exit text editing. EditorGUI.EndEditingActiveTextField(); } } private void PreviewButtonOnGUI() { EditorGUI.BeginChangeCheck(); bool recordingEnabled = GUILayout.Toggle(m_State.previewing, AnimationWindowStyles.previewContent, EditorStyles.toolbarButton); if (EditorGUI.EndChangeCheck()) { m_State.previewing = recordingEnabled; } } private void RecordButtonOnGUI() { EditorGUI.BeginChangeCheck(); Color backupColor = GUI.color; if (m_State.recording) { Color recordedColor = AnimationMode.recordedPropertyColor; recordedColor.a *= GUI.color.a; GUI.color = recordedColor; } bool recordingEnabled = GUILayout.Toggle(m_State.recording, AnimationWindowStyles.recordContent, EditorStyles.toolbarButton); if (EditorGUI.EndChangeCheck()) { m_State.recording = recordingEnabled; if (!recordingEnabled) { // Force refresh in inspector as stopping recording does not invalidate any data. InspectorWindow.RepaintAllInspectors(); } } GUI.color = backupColor; } private void SwitchBetweenCurvesAndDopesheet() { if (!m_State.showCurveEditor) { SwitchToCurveEditor(); } else { SwitchToDopeSheetEditor(); } } internal void SwitchToCurveEditor() { m_State.showCurveEditor = true; UpdateSelectedKeysToCurveEditor(); AnimationWindowUtility.SyncTimeArea(m_DopeSheet, m_CurveEditor); m_State.timeArea = m_CurveEditor; } internal void SwitchToDopeSheetEditor() { m_State.showCurveEditor = false; UpdateSelectedKeysFromCurveEditor(); AnimationWindowUtility.SyncTimeArea(m_CurveEditor, m_DopeSheet); m_State.timeArea = m_DopeSheet; } private void RenderSelectionOverlay(Rect rect) { if (m_State.showCurveEditor && !m_CurveEditor.hasSelection) return; if (!m_State.showCurveEditor && m_State.selectedKeys.Count == 0) return; const int kOverlayMinWidth = 14; Bounds bounds = m_State.showCurveEditor ? m_CurveEditor.selectionBounds : m_State.selectionBounds; float startPixel = m_State.TimeToPixel(bounds.min.x) + rect.xMin; float endPixel = m_State.TimeToPixel(bounds.max.x) + rect.xMin; if ((endPixel - startPixel) < kOverlayMinWidth) { float centerPixel = (startPixel + endPixel) * 0.5f; startPixel = centerPixel - kOverlayMinWidth * 0.5f; endPixel = centerPixel + kOverlayMinWidth * 0.5f; } AnimationWindowUtility.DrawSelectionOverlay(rect, selectionRangeColor, startPixel, endPixel); } private void RenderInRangeOverlay(Rect rect) { Color color = inRangeColor; if (m_State.recording) color *= AnimationMode.recordedPropertyColor; else if (m_State.previewing) color *= AnimationMode.animatedPropertyColor; else color = Color.clear; Vector2 timeRange = m_State.timeRange; AnimationWindowUtility.DrawInRangeOverlay(rect, color, m_State.TimeToPixel(timeRange.x) + rect.xMin, m_State.TimeToPixel(timeRange.y) + rect.xMin); } private void RenderOutOfRangeOverlay(Rect rect) { Color color = outOfRangeColor; if (m_State.recording) color *= AnimationMode.recordedPropertyColor; else if (m_State.previewing) color *= AnimationMode.animatedPropertyColor; Vector2 timeRange = m_State.timeRange; AnimationWindowUtility.DrawOutOfRangeOverlay(rect, color, m_State.TimeToPixel(timeRange.x) + rect.xMin, m_State.TimeToPixel(timeRange.y) + rect.xMin); } private void SynchronizeLayout() { m_HorizontalSplitter.realSizes[1] = (int)Mathf.Max(Mathf.Min(m_Position.width - m_HorizontalSplitter.realSizes[0], m_HorizontalSplitter.realSizes[1]), 0); // Synchronize frame rate if (selection.animationClip != null) { m_State.frameRate = selection.animationClip.frameRate; } else { m_State.frameRate = AnimationWindowState.kDefaultFrameRate; } } struct ChangedCurvesPerClip { public List<EditorCurveBinding> bindings; public List<AnimationCurve> curves; } // Curve editor changes curves, but we are in charge of saving them into the clip private void SaveChangedCurvesFromCurveEditor() { m_State.SaveKeySelection(AnimationWindowState.kEditCurveUndoLabel); var curvesToUpdate = new Dictionary<AnimationClip, ChangedCurvesPerClip>(); var changedCurves = new ChangedCurvesPerClip(); for (int i = 0; i < m_CurveEditor.animationCurves.Length; ++i) { CurveWrapper curveWrapper = m_CurveEditor.animationCurves[i]; if (curveWrapper.changed) { if (!curveWrapper.animationIsEditable) Debug.LogError("Curve is not editable and shouldn't be saved."); if (curveWrapper.animationClip != null) { if (curvesToUpdate.TryGetValue(curveWrapper.animationClip, out changedCurves)) { changedCurves.bindings.Add(curveWrapper.binding); changedCurves.curves.Add(curveWrapper.curve.length > 0 ? curveWrapper.curve : null); } else { changedCurves.bindings = new List<EditorCurveBinding>(); changedCurves.curves = new List<AnimationCurve>(); changedCurves.bindings.Add(curveWrapper.binding); changedCurves.curves.Add(curveWrapper.curve.length > 0 ? curveWrapper.curve : null); curvesToUpdate.Add(curveWrapper.animationClip, changedCurves); } } curveWrapper.changed = false; } } if (curvesToUpdate.Count > 0) { foreach (var kvp in curvesToUpdate) { Undo.RegisterCompleteObjectUndo(kvp.Key, AnimationWindowState.kEditCurveUndoLabel); AnimationWindowUtility.SaveCurves(kvp.Key, kvp.Value.bindings, kvp.Value.curves); } m_State.ResampleAnimation(); } } // We sync keyframe selection from curve editor to AnimationWindowState private void UpdateSelectedKeysFromCurveEditor() { m_State.ClearKeySelections(); foreach (CurveSelection curveSelection in m_CurveEditor.selectedCurves) { AnimationWindowKeyframe keyFrame = AnimationWindowUtility.CurveSelectionToAnimationWindowKeyframe(curveSelection, m_State.filteredCurves); if (keyFrame != null) m_State.SelectKey(keyFrame); } } // We sync keyframe selection from AnimationWindowState to curve editor private void UpdateSelectedKeysToCurveEditor() { UpdateCurveEditorData(); m_CurveEditor.ClearSelection(); m_CurveEditor.BeginRangeSelection(); foreach (AnimationWindowKeyframe keyframe in m_State.selectedKeys) { CurveSelection curveSelection = AnimationWindowUtility.AnimationWindowKeyframeToCurveSelection(keyframe, m_CurveEditor); if (curveSelection != null) m_CurveEditor.AddSelection(curveSelection); } m_CurveEditor.EndRangeSelection(); } private void SaveCurveEditorKeySelection() { // Synchronize current selection in curve editor and save selection snapshot in undo redo. if (m_State.showCurveEditor) UpdateSelectedKeysFromCurveEditor(); else UpdateSelectedKeysToCurveEditor(); m_CurveEditor.SaveKeySelection(AnimationWindowState.kEditCurveUndoLabel); } public void BeginKeyModification() { SaveCurveEditorKeySelection(); m_State.SaveKeySelection(AnimationWindowState.kEditCurveUndoLabel); m_State.ClearKeySelections(); } public void EndKeyModification() { UpdateSelectedKeysToCurveEditor(); } void HandleMainAreaCopyPaste(int controlID) { var evt = Event.current; var type = evt.GetTypeForControl(controlID); if (type != EventType.ValidateCommand && type != EventType.ExecuteCommand) return; if (evt.commandName == EventCommandNames.Copy) { // If events timeline has selected events right now then bail out; copying of // these will get processed later by AnimationEventTimeLine. if (m_Events.HasSelectedEvents) return; if (type == EventType.ExecuteCommand) { if (m_State.showCurveEditor) UpdateSelectedKeysFromCurveEditor(); m_State.CopyKeys(); } evt.Use(); } else if (evt.commandName == EventCommandNames.Paste) { if (type == EventType.ExecuteCommand) { // If clipboard contains events right now then paste those. if (AnimationWindowEventsClipboard.CanPaste()) { m_Events.PasteEvents(m_State.activeRootGameObject, m_State.activeAnimationClip, m_State.currentTime); } else { SaveCurveEditorKeySelection(); m_State.PasteKeys(); UpdateSelectedKeysToCurveEditor(); } // data is scheduled for an update, bail out now to avoid using out of date data. EditorGUIUtility.ExitGUI(); } evt.Use(); } } internal void UpdateCurveEditorData() { m_CurveEditor.animationCurves = m_State.activeCurveWrappers; } public void Repaint() { if (m_OwnerWindow != null) m_OwnerWindow.Repaint(); } // Called just-in-time by OnGUI private void Initialize() { AnimationWindowStyles.Initialize(); InitializeHierarchy(); m_CurveEditor.state = m_State; // The rect here is only for initialization and will be overriden at layout m_HorizontalSplitter.realSizes[0] = kHierarchyMinWidth; m_HorizontalSplitter.realSizes[1] = (int)Mathf.Max(m_Position.width - kHierarchyMinWidth, kHierarchyMinWidth); m_DopeSheet.rect = new Rect(0, 0, contentWidth, 100); m_Initialized = true; } // Called once during initialization of m_State private void InitializeClipSelection() { m_ClipPopup = new AnimationWindowClipPopup(); } // Called once during initialization of m_State private void InitializeHierarchy() { // The rect here is only for initialization and will be overriden at layout m_Hierarchy = new AnimationWindowHierarchy(m_State, m_OwnerWindow, new Rect(0, 0, hierarchyWidth, 100)); } // Called once during initialization of m_State private void InitializeDopeSheet() { m_DopeSheet = new DopeSheetEditor(m_OwnerWindow); m_DopeSheet.SetTickMarkerRanges(); m_DopeSheet.hSlider = true; m_DopeSheet.shownArea = new Rect(1, 1, 1, 1); // The rect here is only for initialization and will be overriden at layout m_DopeSheet.rect = new Rect(0, 0, contentWidth, 100); m_DopeSheet.hTicks.SetTickModulosForFrameRate(m_State.frameRate); } // Called once during initialization of m_State private void InitializeEvents() { m_Events = new AnimationEventTimeLine(m_OwnerWindow); } // Called once during initialization of m_State private void InitializeCurveEditor() { // The rect here is only for initialization and will be overriden at layout m_CurveEditor = new CurveEditor(new Rect(0, 0, contentWidth, 100), new CurveWrapper[0], false); CurveEditorSettings settings = new CurveEditorSettings(); settings.hTickStyle.distMin = 30; // min distance between vertical lines before they disappear completely settings.hTickStyle.distFull = 80; // distance between vertical lines where they gain full strength settings.hTickStyle.distLabel = 0; // min distance between vertical lines labels if (EditorGUIUtility.isProSkin) { settings.vTickStyle.tickColor.color = new Color(1, 1, 1, settings.vTickStyle.tickColor.color.a); // color and opacity of horizontal lines settings.vTickStyle.labelColor.color = new Color(1, 1, 1, settings.vTickStyle.labelColor.color.a); // color and opacity of horizontal line labels } settings.vTickStyle.distMin = 15; // min distance between horizontal lines before they disappear completely settings.vTickStyle.distFull = 40; // distance between horizontal lines where they gain full strength settings.vTickStyle.distLabel = 30; // min distance between horizontal lines labels settings.vTickStyle.stubs = true; settings.hRangeMin = 0; settings.hRangeLocked = false; settings.vRangeLocked = false; settings.hSlider = true; settings.vSlider = true; settings.allowDeleteLastKeyInCurve = true; settings.rectangleToolFlags = CurveEditorSettings.RectangleToolFlags.FullRectangleTool; settings.undoRedoSelection = true; settings.flushCurveCache = false; // Curve Wrappers are cached in AnimationWindowState. m_CurveEditor.shownArea = new Rect(1, 1, 1, 1); m_CurveEditor.settings = settings; m_CurveEditor.state = m_State; } // Called once during initialization of m_State private void InitializeHorizontalSplitter() { m_HorizontalSplitter = SplitterState.FromRelative(new float[] { kHierarchyMinWidth, kHierarchyMinWidth * 3 }, new float[] { kHierarchyMinWidth, kHierarchyMinWidth }, null); m_HorizontalSplitter.realSizes[0] = kHierarchyMinWidth; m_HorizontalSplitter.realSizes[1] = kHierarchyMinWidth; } // Called once during initialization of m_State private void InitializeOverlay() { m_Overlay = new AnimEditorOverlay(); } // Called during initialization, even when m_State already exists private void InitializeNonserializedValues() { // Since CurveEditor doesn't know about AnimationWindowState, a delegate allows it to reflect frame rate changes m_State.onFrameRateChange += delegate(float newFrameRate) { m_CurveEditor.invSnap = newFrameRate; m_CurveEditor.hTicks.SetTickModulosForFrameRate(newFrameRate); }; m_State.onStartLiveEdit += OnStartLiveEdit; m_State.onEndLiveEdit += OnEndLiveEdit; } } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimEditor.cs", "repo_id": "UnityCsReference", "token_count": 25900 }
249
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor; using UnityEngine; using System.Collections.Generic; using System.Linq; using UnityEditor.IMGUI.Controls; namespace UnityEditorInternal { internal class AnimationWindowHierarchyGUI : TreeViewGUI { public AnimationWindowState state { get; set; } readonly GUIContent k_AnimatePropertyLabel = EditorGUIUtility.TrTextContent("Add Property"); private GUIStyle m_AnimationRowEvenStyle; private GUIStyle m_AnimationRowOddStyle; private GUIStyle m_AnimationSelectionTextField; private GUIStyle m_AnimationCurveDropdown; private bool m_StyleInitialized; private AnimationWindowHierarchyNode m_RenamedNode; private Color m_LightSkinPropertyTextColor = new Color(.35f, .35f, .35f); private Color m_PhantomCurveColor = new Color(0f, 153f / 255f, 153f / 255f); private int[] m_HierarchyItemFoldControlIDs; private int[] m_HierarchyItemValueControlIDs; private int[] m_HierarchyItemButtonControlIDs; private const float k_RowRightOffset = 10; private const float k_ValueFieldDragWidth = 15; private const float k_ValueFieldWidth = 80; private const float k_ValueFieldOffsetFromRightSide = 100; private const float k_ColorIndicatorTopMargin = 3; public static readonly float k_DopeSheetRowHeight = EditorGUI.kSingleLineHeight; public static readonly float k_DopeSheetRowHeightTall = k_DopeSheetRowHeight * 2f; public const float k_AddCurveButtonNodeHeight = 40f; public const float k_RowBackgroundColorBrightness = 0.28f; private const float k_SelectedPhantomCurveColorMultiplier = 1.4f; private const float k_CurveColorIndicatorIconSize = 11; private readonly static Color k_KeyColorInDopesheetMode = new Color(0.7f, 0.7f, 0.7f, 1); private readonly static Color k_KeyColorForNonCurves = new Color(0.7f, 0.7f, 0.7f, 0.5f); private readonly static Color k_LeftoverCurveColor = Color.yellow; private static readonly string k_DefaultValue = L10n.Tr(" (Default Value)"); private static readonly string k_TransformPosition = L10n.Tr("Transform position, rotation and scale can't be partially animated. This value will be animated to the default value"); private static readonly string k_Missing = L10n.Tr(" (Missing!)"); private static readonly string k_GameObjectComponentMissing = L10n.Tr("The GameObject or Component is missing ({0})"); private static readonly string k_DuplicateGameObjectName = L10n.Tr(" (Duplicate GameObject name!)"); private static readonly string k_TargetForCurveIsAmbigous = L10n.Tr("Target for curve is ambiguous since there are multiple GameObjects with same name ({0})"); private static readonly string k_RemoveProperties = L10n.Tr("Remove Properties"); private static readonly string k_RemoveProperty = L10n.Tr("Remove Property"); private static readonly string k_AddKey = L10n.Tr("Add Key"); private static readonly string k_DeleteKey = L10n.Tr("Delete Key"); private static readonly string k_RemoveCurve = L10n.Tr("Remove Curve"); internal static int s_WasInsideValueRectFrame = -1; public AnimationWindowHierarchyGUI(TreeViewController treeView, AnimationWindowState state) : base(treeView) { this.state = state; InitStyles(); } protected void InitStyles() { if (!m_StyleInitialized) { m_AnimationRowEvenStyle = "AnimationRowEven"; m_AnimationRowOddStyle = "AnimationRowOdd"; m_AnimationSelectionTextField = "AnimationSelectionTextField"; lineStyle = Styles.lineStyle; lineStyle.padding.left = 0; m_AnimationCurveDropdown = "AnimPropDropdown"; m_StyleInitialized = true; } } protected void DoNodeGUI(Rect rect, AnimationWindowHierarchyNode node, bool selected, bool focused, int row) { InitStyles(); if (node is AnimationWindowHierarchyMasterNode) return; float indent = k_BaseIndent + (node.depth + node.indent) * k_IndentWidth; if (node is AnimationWindowHierarchyAddButtonNode) { if (Event.current.type == EventType.MouseMove && s_WasInsideValueRectFrame >= 0) { if (s_WasInsideValueRectFrame >= Time.frameCount - 1) Event.current.Use(); else s_WasInsideValueRectFrame = -1; } using (new EditorGUI.DisabledScope(!state.selection.canAddCurves)) { DoAddCurveButton(rect, node, row); } } else { DoRowBackground(rect, row); DoIconAndName(rect, node, selected, focused, indent); DoFoldout(node, rect, indent, row); bool enabled = false; if (node.curves != null) { enabled = !Array.Exists(node.curves, curve => curve.animationIsEditable == false); } using (new EditorGUI.DisabledScope(!enabled)) { DoValueField(rect, node, row); } DoCurveDropdown(rect, node, row, enabled); HandleContextMenu(rect, node, enabled); DoCurveColorIndicator(rect, node); } EditorGUIUtility.SetIconSize(Vector2.zero); } public override void BeginRowGUI() { base.BeginRowGUI(); HandleDelete(); // Reserve unique control ids. // This is required to avoid changing control ids mapping as we scroll in the tree view // and change items visibility. Hopefully, we should be able to remove it entirely if we // isolate the animation window layouts in separate IMGUIContainers... int rowCount = m_TreeView.data.rowCount; m_HierarchyItemFoldControlIDs = new int[rowCount]; m_HierarchyItemValueControlIDs = new int[rowCount]; m_HierarchyItemButtonControlIDs = new int[rowCount]; for (int i = 0; i < rowCount; ++i) { var propertyNode = m_TreeView.data.GetItem(i) as AnimationWindowHierarchyPropertyNode; if (propertyNode != null && !propertyNode.isPptrNode) m_HierarchyItemValueControlIDs[i] = GUIUtility.GetControlID(FocusType.Keyboard); else m_HierarchyItemValueControlIDs[i] = 0; // not needed. m_HierarchyItemFoldControlIDs[i] = GUIUtility.GetControlID(FocusType.Passive); m_HierarchyItemButtonControlIDs[i] = GUIUtility.GetControlID(FocusType.Passive); } } private void DoAddCurveButton(Rect rect, AnimationWindowHierarchyNode node, int row) { const int k_ButtonWidth = 230; float xMargin = (rect.width - k_ButtonWidth) / 2f; float yMargin = 10f; Rect rectWithMargin = new Rect(rect.xMin + xMargin, rect.yMin + yMargin, rect.width - xMargin * 2f, rect.height - yMargin * 2f); // case 767863. // This control id is unique to the hierarchy node it refers to. // The tree view only renders the elements that are visible, and will cause // the control id counter to shift when scrolling through the view. if (DoTreeViewButton(m_HierarchyItemButtonControlIDs[row], rectWithMargin, k_AnimatePropertyLabel, GUI.skin.button)) { if (AddCurvesPopup.ShowAtPosition(rectWithMargin, state, OnNewCurveAdded)) { GUIUtility.ExitGUI(); } } } private void OnNewCurveAdded(AddCurvesPopupPropertyNode node) { } private void DoRowBackground(Rect rect, int row) { if (Event.current.type != EventType.Repaint) return; // Different background for even rows if (row % 2 == 0) m_AnimationRowEvenStyle.Draw(rect, false, false, false, false); else m_AnimationRowOddStyle.Draw(rect, false, false, false, false); } // Draw foldout (after text content above to ensure drop down icon is rendered above selection highlight) private void DoFoldout(AnimationWindowHierarchyNode node, Rect rect, float indent, int row) { if (m_TreeView.data.IsExpandable(node)) { Rect toggleRect = rect; toggleRect.x = indent; toggleRect.width = foldoutStyleWidth; EditorGUI.BeginChangeCheck(); bool newExpandedValue = GUI.Toggle(toggleRect, m_HierarchyItemFoldControlIDs[row], m_TreeView.data.IsExpanded(node), GUIContent.none, foldoutStyle); if (EditorGUI.EndChangeCheck()) { if (Event.current.alt) m_TreeView.data.SetExpandedWithChildren(node, newExpandedValue); else m_TreeView.data.SetExpanded(node, newExpandedValue); } } else { AnimationWindowHierarchyPropertyNode hierarchyPropertyNode = node as AnimationWindowHierarchyPropertyNode; AnimationWindowHierarchyState hierarchyState = m_TreeView.state as AnimationWindowHierarchyState; if (hierarchyPropertyNode != null && hierarchyPropertyNode.isPptrNode) { Rect toggleRect = rect; toggleRect.x = indent; toggleRect.width = foldoutStyleWidth; EditorGUI.BeginChangeCheck(); bool tallMode = hierarchyState.GetTallMode(hierarchyPropertyNode); tallMode = GUI.Toggle(toggleRect, m_HierarchyItemFoldControlIDs[row], tallMode, GUIContent.none, foldoutStyle); if (EditorGUI.EndChangeCheck()) hierarchyState.SetTallMode(hierarchyPropertyNode, tallMode); } } } private void DoIconAndName(Rect rect, AnimationWindowHierarchyNode node, bool selected, bool focused, float indent) { EditorGUIUtility.SetIconSize(new Vector2(13, 13)); // If not set we see icons scaling down if text is being cropped // TODO: All this is horrible. SHAME FIX! if (Event.current.type == EventType.Repaint) { if (selected) selectionStyle.Draw(rect, false, false, true, focused); // Leave some space for the value field that comes after. if (node is AnimationWindowHierarchyPropertyNode) rect.width -= k_ValueFieldOffsetFromRightSide + 2; bool isLeftOverCurve = AnimationWindowUtility.IsNodeLeftOverCurve(state, node); bool isAmbiguous = AnimationWindowUtility.IsNodeAmbiguous(node); bool isPhantom = AnimationWindowUtility.IsNodePhantom(node); string warningText = ""; string tooltipText = ""; if (isPhantom) { warningText = k_DefaultValue; tooltipText = k_TransformPosition; } if (isLeftOverCurve) { warningText = k_Missing; tooltipText = string.Format(k_GameObjectComponentMissing, node.path); } if (isAmbiguous) { warningText = k_DuplicateGameObjectName; tooltipText = string.Format(k_TargetForCurveIsAmbigous, node.path); } Color oldColor = lineStyle.normal.textColor; Color textColor = oldColor; if (node.depth == 0) { string nodePrefix = ""; if (node.curves.Length > 0) { AnimationWindowSelectionItem selectionBinding = node.curves[0].selectionBinding; string gameObjectName = GetGameObjectName(selectionBinding != null ? selectionBinding.rootGameObject : null, node.path); nodePrefix = string.IsNullOrEmpty(gameObjectName) ? "" : gameObjectName + " : "; } Styles.content = new GUIContent(nodePrefix + node.displayName + warningText, GetIconForItem(node), tooltipText); textColor = EditorGUIUtility.isProSkin ? Color.gray * 1.35f : Color.black; } else { Styles.content = new GUIContent(node.displayName + warningText, GetIconForItem(node), tooltipText); textColor = EditorGUIUtility.isProSkin ? Color.gray : m_LightSkinPropertyTextColor; var phantomColor = selected ? m_PhantomCurveColor * k_SelectedPhantomCurveColorMultiplier : m_PhantomCurveColor; textColor = isPhantom ? phantomColor : textColor; } textColor = isLeftOverCurve || isAmbiguous ? k_LeftoverCurveColor : textColor; SetStyleTextColor(lineStyle, textColor); rect.xMin += (int)(indent + foldoutStyleWidth + lineStyle.margin.left); rect.yMin = rect.y + (rect.height - EditorGUIUtility.singleLineHeight) / 2; GUI.Label(rect, Styles.content, lineStyle); SetStyleTextColor(lineStyle, oldColor); } if (IsRenaming(node.id) && Event.current.type != EventType.Layout) GetRenameOverlay().editFieldRect = new Rect(rect.x + k_IndentWidth, rect.y, rect.width - k_IndentWidth - 1, rect.height); } private string GetGameObjectName(GameObject rootGameObject, string path) { if (string.IsNullOrEmpty(path)) return rootGameObject != null ? rootGameObject.name : ""; string[] splits = path.Split('/'); return splits[splits.Length - 1]; } private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row) { bool curvesChanged = false; if (node is AnimationWindowHierarchyPropertyNode) { AnimationWindowCurve[] curves = node.curves; if (curves == null || curves.Length == 0) return; // We do valuefields for dopelines that only have single curve AnimationWindowCurve curve = curves[0]; object value = CurveBindingUtility.GetCurrentValue(state, curve); if (!curve.isPPtrCurve) { Rect valueFieldDragRect = new Rect(rect.xMax - k_ValueFieldOffsetFromRightSide - k_ValueFieldDragWidth, rect.y, k_ValueFieldDragWidth, rect.height); Rect valueFieldRect = new Rect(rect.xMax - k_ValueFieldOffsetFromRightSide, rect.y, k_ValueFieldWidth, rect.height); if (Event.current.type == EventType.MouseMove && valueFieldRect.Contains(Event.current.mousePosition)) s_WasInsideValueRectFrame = Time.frameCount; EditorGUI.BeginChangeCheck(); if (curve.valueType == typeof(bool)) { value = GUI.Toggle(valueFieldRect, m_HierarchyItemValueControlIDs[row], Convert.ToSingle(value) != 0f, GUIContent.none, EditorStyles.toggle) ? 1f : 0f; } else { int id = m_HierarchyItemValueControlIDs[row]; bool enterInTextField = (EditorGUIUtility.keyboardControl == id && EditorGUIUtility.editingTextField && Event.current.type == EventType.KeyDown && (Event.current.character == '\n' || (int)Event.current.character == 3)); // Force back keyboard focus to float field editor when editing it. // TreeView forces keyboard focus on itself at mouse down and we lose focus here. if (EditorGUI.s_RecycledEditor.controlID == id && Event.current.type == EventType.MouseDown && valueFieldRect.Contains(Event.current.mousePosition)) { GUIUtility.keyboardControl = id; } if (curve.isDiscreteCurve) { value = EditorGUI.DoIntField(EditorGUI.s_RecycledEditor, valueFieldRect, valueFieldDragRect, id, Convert.ToInt32(value), EditorGUI.kIntFieldFormatString, m_AnimationSelectionTextField, true, 0); if (enterInTextField) { GUI.changed = true; Event.current.Use(); } } else { value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, valueFieldRect, valueFieldDragRect, id, Convert.ToSingle(value), "g5", m_AnimationSelectionTextField, true); if (enterInTextField) { GUI.changed = true; Event.current.Use(); } var floatValue = Convert.ToSingle(value); if (float.IsInfinity(floatValue) || float.IsNaN(floatValue)) value = 0f; } } if (EditorGUI.EndChangeCheck()) { string undoLabel = "Edit Key"; AnimationKeyTime newAnimationKeyTime = AnimationKeyTime.Time(state.currentTime, curve.clip.frameRate); AnimationWindowUtility.AddKeyframeToCurve(curve, value, curve.valueType, newAnimationKeyTime); state.SaveCurve(curve.clip, curve, undoLabel); curvesChanged = true; } } } if (curvesChanged) { //Fix for case 1382193: Stop recording any candidates if a property value field is modified if (AnimationMode.IsRecordingCandidates()) state.ClearCandidates(); state.ResampleAnimation(); } } private bool DoTreeViewButton(int id, Rect position, GUIContent content, GUIStyle style) { Event evt = Event.current; EventType type = evt.GetTypeForControl(id); switch (type) { case EventType.Repaint: style.Draw(position, content, id, false, position.Contains(evt.mousePosition)); break; case EventType.MouseDown: if (position.Contains(evt.mousePosition) && evt.button == 0) { GUIUtility.hotControl = id; evt.Use(); } break; case EventType.MouseUp: if (GUIUtility.hotControl == id) { GUIUtility.hotControl = 0; evt.Use(); if (position.Contains(evt.mousePosition)) { return true; } } break; } return false; } private void DoCurveDropdown(Rect rect, AnimationWindowHierarchyNode node, int row, bool enabled) { rect = new Rect( rect.xMax - k_RowRightOffset - 12, rect.yMin + 2 + (rect.height - EditorGUIUtility.singleLineHeight) / 2, 22, 12); // case 767863. // This control id is unique to the hierarchy node it refers to. // The tree view only renders the elements that are visible, and will cause // the control id counter to shift when scrolling through the view. if (DoTreeViewButton(m_HierarchyItemButtonControlIDs[row], rect, GUIContent.none, m_AnimationCurveDropdown)) { state.SelectHierarchyItem(node.id, false, false); GenericMenu menu = GenerateMenu(new AnimationWindowHierarchyNode[] { node }.ToList(), enabled); menu.DropDown(rect); Event.current.Use(); } } private void DoCurveColorIndicator(Rect rect, AnimationWindowHierarchyNode node) { if (Event.current.type != EventType.Repaint) return; Color originalColor = GUI.color; if (!state.showCurveEditor) GUI.color = k_KeyColorInDopesheetMode; else if (node.curves.Length == 1 && !node.curves[0].isPPtrCurve) GUI.color = CurveUtility.GetPropertyColor(node.curves[0].binding.propertyName); else GUI.color = k_KeyColorForNonCurves; bool hasKey = false; if (state.previewing) { foreach (var curve in node.curves) { if (curve.keyframes.Any(key => state.time.ContainsTime(key.time))) { hasKey = true; } } } Texture icon = hasKey ? CurveUtility.GetIconKey() : CurveUtility.GetIconCurve(); rect = new Rect(rect.xMax - k_RowRightOffset - (k_CurveColorIndicatorIconSize / 2) - 5, rect.yMin + k_ColorIndicatorTopMargin + (rect.height - EditorGUIUtility.singleLineHeight) / 2, k_CurveColorIndicatorIconSize, k_CurveColorIndicatorIconSize); GUI.DrawTexture(rect, icon, ScaleMode.ScaleToFit, true, 1); GUI.color = originalColor; } private void HandleDelete() { if (m_TreeView.HasFocus()) { switch (Event.current.type) { case EventType.ExecuteCommand: if ((Event.current.commandName == EventCommandNames.SoftDelete || Event.current.commandName == EventCommandNames.Delete)) { if (Event.current.type == EventType.ExecuteCommand) RemoveCurvesFromSelectedNodes(); Event.current.Use(); } break; case EventType.KeyDown: if (Event.current.keyCode == KeyCode.Backspace || Event.current.keyCode == KeyCode.Delete) { RemoveCurvesFromSelectedNodes(); Event.current.Use(); } break; } } } private void HandleContextMenu(Rect rect, AnimationWindowHierarchyNode node, bool enabled) { if (Event.current.type != EventType.ContextClick) return; if (rect.Contains(Event.current.mousePosition)) { state.SelectHierarchyItem(node.id, true, true); //state.animationWindow.RefreshShownCurves (true); GenerateMenu(state.selectedHierarchyNodes, enabled).ShowAsContext(); Event.current.Use(); } } private GenericMenu GenerateMenu(List<AnimationWindowHierarchyNode> interactedNodes, bool enabled) { List<AnimationWindowCurve> curves = GetCurvesAffectedByNodes(interactedNodes, false); // Linked curves are like regular affected curves but always include transform siblings List<AnimationWindowCurve> linkedCurves = GetCurvesAffectedByNodes(interactedNodes, true); bool forceGroupRemove = curves.Count == 1 ? AnimationWindowUtility.ForceGrouping(curves[0].binding) : false; GenericMenu menu = new GenericMenu(); // Remove curves GUIContent removePropertyContent = new GUIContent(curves.Count > 1 || forceGroupRemove ? k_RemoveProperties : k_RemoveProperty); if (!enabled) menu.AddDisabledItem(removePropertyContent); else menu.AddItem(removePropertyContent, false, RemoveCurvesFromSelectedNodes); // Change rotation interpolation bool showInterpolation = true; EditorCurveBinding[] curveBindings = new EditorCurveBinding[linkedCurves.Count]; for (int i = 0; i < linkedCurves.Count; i++) curveBindings[i] = linkedCurves[i].binding; RotationCurveInterpolation.Mode rotationInterpolation = GetRotationInterpolationMode(curveBindings); if (rotationInterpolation == RotationCurveInterpolation.Mode.Undefined) { showInterpolation = false; } else { foreach (var node in interactedNodes) { if (!(node is AnimationWindowHierarchyPropertyGroupNode)) showInterpolation = false; } } if (showInterpolation) { string legacyWarning = state.activeAnimationClip.legacy ? " (Not fully supported in Legacy)" : ""; GenericMenu.MenuFunction2 nullMenuFunction2 = null; menu.AddItem(EditorGUIUtility.TrTextContent("Interpolation/Euler Angles" + legacyWarning), rotationInterpolation == RotationCurveInterpolation.Mode.RawEuler, enabled ? ChangeRotationInterpolation : nullMenuFunction2, RotationCurveInterpolation.Mode.RawEuler); menu.AddItem(EditorGUIUtility.TrTextContent("Interpolation/Euler Angles (Quaternion)"), rotationInterpolation == RotationCurveInterpolation.Mode.Baked, enabled ? ChangeRotationInterpolation : nullMenuFunction2, RotationCurveInterpolation.Mode.Baked); menu.AddItem(EditorGUIUtility.TrTextContent("Interpolation/Quaternion"), rotationInterpolation == RotationCurveInterpolation.Mode.NonBaked, enabled ? ChangeRotationInterpolation : nullMenuFunction2, RotationCurveInterpolation.Mode.NonBaked); } // Menu items that are only applicaple when in animation mode: if (state.previewing) { menu.AddSeparator(""); bool allHaveKeys = true; bool noneHaveKeys = true; foreach (AnimationWindowCurve curve in curves) { bool curveHasKey = curve.HasKeyframe(state.time); if (!curveHasKey) allHaveKeys = false; else noneHaveKeys = false; } string str; str = k_AddKey; if (allHaveKeys || !enabled) menu.AddDisabledItem(new GUIContent(str)); else menu.AddItem(new GUIContent(str), false, AddKeysAtCurrentTime, curves); str = k_DeleteKey; if (noneHaveKeys || !enabled) menu.AddDisabledItem(new GUIContent(str)); else menu.AddItem(new GUIContent(str), false, DeleteKeysAtCurrentTime, curves); } return menu; } private void AddKeysAtCurrentTime(object obj) { AddKeysAtCurrentTime((List<AnimationWindowCurve>)obj); } private void AddKeysAtCurrentTime(List<AnimationWindowCurve> curves) { AnimationWindowUtility.AddKeyframes(state, curves, state.time); } private void DeleteKeysAtCurrentTime(object obj) { DeleteKeysAtCurrentTime((List<AnimationWindowCurve>)obj); } private void DeleteKeysAtCurrentTime(List<AnimationWindowCurve> curves) { AnimationWindowUtility.RemoveKeyframes(state, curves, state.time); } private void ChangeRotationInterpolation(System.Object interpolationMode) { RotationCurveInterpolation.Mode mode = (RotationCurveInterpolation.Mode)interpolationMode; AnimationWindowCurve[] activeCurves = state.activeCurves.ToArray(); EditorCurveBinding[] curveBindings = new EditorCurveBinding[activeCurves.Length]; for (int i = 0; i < activeCurves.Length; i++) { curveBindings[i] = activeCurves[i].binding; } RotationCurveInterpolation.SetInterpolation(state.activeAnimationClip, curveBindings, mode); MaintainTreeviewStateAfterRotationInterpolation(mode); state.hierarchyData.ReloadData(); } private void RemoveCurvesFromSelectedNodes() { RemoveCurvesFromNodes(state.selectedHierarchyNodes); } private void RemoveCurvesFromNodes(List<AnimationWindowHierarchyNode> nodes) { string undoLabel = k_RemoveCurve; state.SaveKeySelection(undoLabel); foreach (var node in nodes) { AnimationWindowHierarchyNode hierarchyNode = (AnimationWindowHierarchyNode)node; if (hierarchyNode.parent is AnimationWindowHierarchyPropertyGroupNode && hierarchyNode.binding != null && AnimationWindowUtility.ForceGrouping((EditorCurveBinding)hierarchyNode.binding)) hierarchyNode = (AnimationWindowHierarchyNode)hierarchyNode.parent; if (hierarchyNode.curves == null) continue; List<AnimationWindowCurve> curves = null; // Property or propertygroup if (hierarchyNode is AnimationWindowHierarchyPropertyGroupNode || hierarchyNode is AnimationWindowHierarchyPropertyNode) curves = AnimationWindowUtility.FilterCurves(hierarchyNode.curves.ToArray(), hierarchyNode.path, hierarchyNode.animatableObjectType, hierarchyNode.propertyName); else curves = AnimationWindowUtility.FilterCurves(hierarchyNode.curves.ToArray(), hierarchyNode.path, hierarchyNode.animatableObjectType); foreach (AnimationWindowCurve animationWindowCurve in curves) state.RemoveCurve(animationWindowCurve, undoLabel); } m_TreeView.ReloadData(); state.controlInterface.ResampleAnimation(); } private List<AnimationWindowCurve> GetCurvesAffectedByNodes(List<AnimationWindowHierarchyNode> nodes, bool includeLinkedCurves) { List<AnimationWindowCurve> curves = new List<AnimationWindowCurve>(); foreach (var node in nodes) { AnimationWindowHierarchyNode hierarchyNode = node; if (hierarchyNode.parent is AnimationWindowHierarchyPropertyGroupNode && includeLinkedCurves) hierarchyNode = (AnimationWindowHierarchyNode)hierarchyNode.parent; if (hierarchyNode.curves == null) continue; if (hierarchyNode.curves.Length > 0) { // Property or propertygroup if (hierarchyNode is AnimationWindowHierarchyPropertyGroupNode || hierarchyNode is AnimationWindowHierarchyPropertyNode) curves.AddRange(AnimationWindowUtility.FilterCurves(hierarchyNode.curves, hierarchyNode.path, hierarchyNode.animatableObjectType, hierarchyNode.propertyName)); else curves.AddRange(AnimationWindowUtility.FilterCurves(hierarchyNode.curves, hierarchyNode.path, hierarchyNode.animatableObjectType)); } } return curves.Distinct().ToList(); } // Changing rotation interpolation will change the propertynames of the curves // Propertynames are used in treeview node IDs, so we need to anticipate the new IDs by injecting them into treeview state // This way treeview state (selection and expanding) will be preserved once the curve data is eventually reloaded private void MaintainTreeviewStateAfterRotationInterpolation(RotationCurveInterpolation.Mode newMode) { List<int> selectedInstaceIDs = state.hierarchyState.selectedIDs; List<int> expandedInstaceIDs = state.hierarchyState.expandedIDs; List<int> oldIDs = new List<int>(); List<int> newIds = new List<int>(); for (int i = 0; i < selectedInstaceIDs.Count; i++) { AnimationWindowHierarchyNode node = state.hierarchyData.FindItem(selectedInstaceIDs[i]) as AnimationWindowHierarchyNode; if (node != null && !node.propertyName.Equals(RotationCurveInterpolation.GetPrefixForInterpolation(newMode))) { string oldPrefix = node.propertyName.Split('.')[0]; string newPropertyName = node.propertyName.Replace(oldPrefix, RotationCurveInterpolation.GetPrefixForInterpolation(newMode)); // old treeview node id oldIDs.Add(selectedInstaceIDs[i]); // and its new replacement newIds.Add((node.path + node.animatableObjectType.Name + newPropertyName).GetHashCode()); } } // Replace old IDs with new ones for (int i = 0; i < oldIDs.Count; i++) { if (selectedInstaceIDs.Contains(oldIDs[i])) { int index = selectedInstaceIDs.IndexOf(oldIDs[i]); selectedInstaceIDs[index] = newIds[i]; } if (expandedInstaceIDs.Contains(oldIDs[i])) { int index = expandedInstaceIDs.IndexOf(oldIDs[i]); expandedInstaceIDs[index] = newIds[i]; } if (state.hierarchyState.lastClickedID == oldIDs[i]) state.hierarchyState.lastClickedID = newIds[i]; } state.hierarchyState.selectedIDs = new List<int>(selectedInstaceIDs); state.hierarchyState.expandedIDs = new List<int>(expandedInstaceIDs); } private RotationCurveInterpolation.Mode GetRotationInterpolationMode(EditorCurveBinding[] curves) { if (curves == null || curves.Length == 0) return RotationCurveInterpolation.Mode.Undefined; RotationCurveInterpolation.Mode mode = RotationCurveInterpolation.GetModeFromCurveData(curves[0]); for (int i = 1; i < curves.Length; i++) { RotationCurveInterpolation.Mode nextMode = RotationCurveInterpolation.GetModeFromCurveData(curves[i]); if (mode != nextMode) return RotationCurveInterpolation.Mode.Undefined; } return mode; } // TODO: Make real styles, not this private void SetStyleTextColor(GUIStyle style, Color color) { style.normal.textColor = color; style.focused.textColor = color; style.active.textColor = color; style.hover.textColor = color; } public override void GetFirstAndLastRowVisible(out int firstRowVisible, out int lastRowVisible) { firstRowVisible = 0; lastRowVisible = m_TreeView.data.rowCount - 1; } public float GetNodeHeight(AnimationWindowHierarchyNode node) { if (node is AnimationWindowHierarchyAddButtonNode) return k_AddCurveButtonNodeHeight; AnimationWindowHierarchyState hierarchyState = m_TreeView.state as AnimationWindowHierarchyState; return hierarchyState.GetTallMode(node) ? k_DopeSheetRowHeightTall : k_DopeSheetRowHeight; } public override Vector2 GetTotalSize() { var rows = m_TreeView.data.GetRows(); float height = 0f; for (int i = 0; i < rows.Count; i++) { AnimationWindowHierarchyNode node = rows[i] as AnimationWindowHierarchyNode; height += GetNodeHeight(node); } return new Vector2(1, height); } float GetTopPixelOfRow(int row, IList<TreeViewItem> rows) { float top = 0f; for (int i = 0; i < row && i < rows.Count; i++) { AnimationWindowHierarchyNode node = rows[i] as AnimationWindowHierarchyNode; top += GetNodeHeight(node); } return top; } public override Rect GetRowRect(int row, float rowWidth) { var rows = m_TreeView.data.GetRows(); AnimationWindowHierarchyNode hierarchyNode = rows[row] as AnimationWindowHierarchyNode; if (hierarchyNode.topPixel == null) hierarchyNode.topPixel = GetTopPixelOfRow(row, rows); float rowHeight = GetNodeHeight(hierarchyNode); return new Rect(0, (float)hierarchyNode.topPixel, rowWidth, rowHeight); } public override void OnRowGUI(Rect rowRect, TreeViewItem node, int row, bool selected, bool focused) { AnimationWindowHierarchyNode hierarchyNode = node as AnimationWindowHierarchyNode; DoNodeGUI(rowRect, hierarchyNode, selected, focused, row); } override public bool BeginRename(TreeViewItem item, float delay) { m_RenamedNode = item as AnimationWindowHierarchyNode; return GetRenameOverlay().BeginRename(m_RenamedNode.path, item.id, delay); } override protected void SyncFakeItem() { //base.SyncFakeItem(); } override protected void RenameEnded() { var renameOverlay = GetRenameOverlay(); if (renameOverlay.userAcceptedRename) { string newName = renameOverlay.name; string oldName = renameOverlay.originalName; if (newName != oldName) { Undo.RecordObject(state.activeAnimationClip, "Rename Curve"); foreach (AnimationWindowCurve curve in m_RenamedNode.curves) { EditorCurveBinding newBinding = AnimationWindowUtility.GetRenamedBinding(curve.binding, newName); if (AnimationWindowUtility.CurveExists(newBinding, state.filteredCurves.ToArray())) { Debug.LogWarning("Curve already exists, renaming cancelled."); continue; } AnimationWindowUtility.RenameCurvePath(curve, newBinding, curve.clip); } } } m_RenamedNode = null; } override protected Texture GetIconForItem(TreeViewItem item) { if (item != null) return item.icon; return null; } } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyGUI.cs", "repo_id": "UnityCsReference", "token_count": 19574 }
250
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEditor; using UnityEditor.ShortcutManagement; using System.Linq; using TangentMode = UnityEditor.AnimationUtility.TangentMode; namespace UnityEditor { internal enum WrapModeFixedCurve { Clamp = (int)WrapMode.ClampForever, Loop = (int)WrapMode.Loop, PingPong = (int)WrapMode.PingPong } [Serializable] internal class CurveEditorWindow : EditorWindow { public enum NormalizationMode { None = 0, Normalize = 1, Denormalize = 2, } //const int kToolbarHeight = 17; const int kPresetsHeight = 46; static CurveEditorWindow s_SharedCurveEditor; internal CurveEditor m_CurveEditor; AnimationCurve m_Curve; Color m_Color; CurvePresetsContentsForPopupWindow m_CurvePresets; GUIContent m_GUIContent = new GUIContent(); [SerializeField] GUIView m_DelegateView; internal GUIView delegateView => m_DelegateView; public const string CurveChangedCommand = "CurveChanged"; public const string CurveChangeCompletedCommand = "CurveChangeCompleted"; public static CurveEditorWindow instance { get { if (!s_SharedCurveEditor) s_SharedCurveEditor = ScriptableObject.CreateInstance<CurveEditorWindow>(); return s_SharedCurveEditor; } } public string currentPresetLibrary { get { InitCurvePresets(); return m_CurvePresets.currentPresetLibrary; } set { InitCurvePresets(); m_CurvePresets.currentPresetLibrary = value; } } public static AnimationCurve curve { get { return visible ? CurveEditorWindow.instance.m_Curve : null; } set { if (value == null) { CurveEditorWindow.instance.m_Curve = null; } else { CurveEditorWindow.instance.m_Curve = value; CurveEditorWindow.instance.RefreshShownCurves(); } } } public static Color color { get { return CurveEditorWindow.instance.m_Color; } set { CurveEditorWindow.instance.m_Color = value; CurveEditorWindow.instance.RefreshShownCurves(); } } public static bool visible { get { return s_SharedCurveEditor != null; } } void OnEnable() { s_SharedCurveEditor = this; Init(null); } // Called by OnEnable to make sure the CurveEditor is not null, // and by Show so we get a fresh CurveEditor when the user clicks a new curve. void Init(CurveEditorSettings settings) { m_CurveEditor = new CurveEditor(GetCurveEditorRect(), GetCurveWrapperArray(), true); m_CurveEditor.curvesUpdated = UpdateCurve; m_CurveEditor.scaleWithWindow = true; m_CurveEditor.margin = 40; if (settings != null) m_CurveEditor.settings = settings; m_CurveEditor.settings.hTickLabelOffset = 10; m_CurveEditor.settings.rectangleToolFlags = CurveEditorSettings.RectangleToolFlags.MiniRectangleTool; // As there is no guarantee animation curve changes are recorded in undo redo, we can't really // handle curve selection in undo redo either. m_CurveEditor.settings.undoRedoSelection = false; m_CurveEditor.settings.showWrapperPopups = true; // For each of horizontal and vertical axis, if we have a finite range for that axis, use that range, // otherwise use framing logic to determine shown range for that axis. bool frameH = true; bool frameV = true; if (m_CurveEditor.settings.hRangeMin != Mathf.NegativeInfinity && m_CurveEditor.settings.hRangeMax != Mathf.Infinity) { m_CurveEditor.SetShownHRangeInsideMargins(m_CurveEditor.settings.hRangeMin, m_CurveEditor.settings.hRangeMax); frameH = false; } if (m_CurveEditor.settings.vRangeMin != Mathf.NegativeInfinity && m_CurveEditor.settings.vRangeMax != Mathf.Infinity) { m_CurveEditor.SetShownVRangeInsideMargins(m_CurveEditor.settings.vRangeMin, m_CurveEditor.settings.vRangeMax); frameV = false; } m_CurveEditor.FrameSelected(frameH, frameV); titleContent = EditorGUIUtility.TrTextContent("Curve"); // deal with window size minSize = new Vector2(240, 240 + kPresetsHeight); maxSize = new Vector2(10000, 10000); } CurveLibraryType curveLibraryType { get { if (m_CurveEditor.settings.hasUnboundedRanges) return CurveLibraryType.Unbounded; return CurveLibraryType.NormalizedZeroToOne; } } // Returns true if a valid normalizationRect is returned (ranges are bounded) static bool GetNormalizationRect(out Rect normalizationRect, CurveEditor curveEditor) { normalizationRect = new Rect(); if (curveEditor.settings.hasUnboundedRanges) return false; normalizationRect = new Rect( curveEditor.settings.hRangeMin, curveEditor.settings.vRangeMin, curveEditor.settings.hRangeMax - curveEditor.settings.hRangeMin, curveEditor.settings.vRangeMax - curveEditor.settings.vRangeMin); return true; } static Keyframe[] CopyAndScaleCurveKeys(Keyframe[] orgKeys, Rect rect, NormalizationMode normalization) { Keyframe[] scaledKeys = new Keyframe[orgKeys.Length]; orgKeys.CopyTo(scaledKeys, 0); if (normalization == NormalizationMode.None) return scaledKeys; if (rect.width == 0f || rect.height == 0f || Single.IsInfinity(rect.width) || Single.IsInfinity(rect.height)) { Debug.LogError("CopyAndScaleCurve: Invalid scale: " + rect); return scaledKeys; } float tangentMultiplier = rect.height / rect.width; switch (normalization) { case NormalizationMode.Normalize: for (int i = 0; i < scaledKeys.Length; ++i) { scaledKeys[i].time = (orgKeys[i].time - rect.xMin) / rect.width; scaledKeys[i].value = (orgKeys[i].value - rect.yMin) / rect.height; if (!Single.IsInfinity(orgKeys[i].inTangent)) scaledKeys[i].inTangent = orgKeys[i].inTangent / tangentMultiplier; if (!Single.IsInfinity(orgKeys[i].outTangent)) scaledKeys[i].outTangent = orgKeys[i].outTangent / tangentMultiplier; } break; case NormalizationMode.Denormalize: // From normalized to real for (int i = 0; i < scaledKeys.Length; ++i) { scaledKeys[i].time = orgKeys[i].time * rect.width + rect.xMin; scaledKeys[i].value = orgKeys[i].value * rect.height + rect.yMin; if (!Single.IsInfinity(orgKeys[i].inTangent)) scaledKeys[i].inTangent = orgKeys[i].inTangent * tangentMultiplier; if (!Single.IsInfinity(orgKeys[i].outTangent)) scaledKeys[i].outTangent = orgKeys[i].outTangent * tangentMultiplier; } break; } return scaledKeys; } void InitCurvePresets() { if (m_CurvePresets == null) { // Selection callback for library window Action<AnimationCurve> presetSelectedCallback = delegate(AnimationCurve presetCurve) { ValidateCurveLibraryTypeAndScale(); // Scale curve up using ranges m_Curve.keys = GetDenormalizedKeys(presetCurve.keys); m_Curve.postWrapMode = presetCurve.postWrapMode; m_Curve.preWrapMode = presetCurve.preWrapMode; m_CurveEditor.SelectNone(); RefreshShownCurves(); SendEvent(CurveChangedCommand, true); }; // We set the curve to save when showing the popup to ensure to scale the current state of the curve AnimationCurve curveToSaveAsPreset = null; m_CurvePresets = new CurvePresetsContentsForPopupWindow(curveToSaveAsPreset, curveLibraryType, presetSelectedCallback); m_CurvePresets.InitIfNeeded(); } } void OnDestroy() { if (m_CurvePresets != null) m_CurvePresets.GetPresetLibraryEditor().UnloadUsedLibraries(); } void OnDisable() { m_CurveEditor.OnDisable(); if (s_SharedCurveEditor == this) s_SharedCurveEditor = null; else if (!this.Equals(s_SharedCurveEditor)) throw new ApplicationException("s_SharedCurveEditor does not equal this"); } private void RefreshShownCurves() { m_CurveEditor.animationCurves = GetCurveWrapperArray(); } public void Show(GUIView viewToUpdate, CurveEditorSettings settings) { m_DelegateView = viewToUpdate; m_OnCurveChanged = null; Init(settings); ShowAuxWindow(); } Action<AnimationCurve> m_OnCurveChanged; public void Show(Action<AnimationCurve> onCurveChanged, CurveEditorSettings settings) { m_OnCurveChanged = onCurveChanged; m_DelegateView = null; Init(settings); ShowAuxWindow(); } public void FrameSelected() { m_CurveEditor.FrameSelected(true, true); } public void FrameClip() { m_CurveEditor.FrameClip(true, true); } internal class Styles { public GUIStyle curveEditorBackground = "PopupCurveEditorBackground"; public GUIStyle miniToolbarButton = "MiniToolbarButtonLeft"; public GUIStyle curveSwatch = "PopupCurveEditorSwatch"; public GUIStyle curveSwatchArea = "PopupCurveSwatchBackground"; } internal static Styles ms_Styles; CurveWrapper[] GetCurveWrapperArray() { if (m_Curve == null) return new CurveWrapper[] {}; CurveWrapper cw = new CurveWrapper(); cw.id = "Curve".GetHashCode(); cw.groupId = -1; cw.color = m_Color; cw.hidden = false; cw.readOnly = false; cw.renderer = new NormalCurveRenderer(m_Curve); cw.renderer.SetWrap(m_Curve.preWrapMode, m_Curve.postWrapMode); return new CurveWrapper[] { cw }; } Rect GetCurveEditorRect() { //return new Rect(0, kToolbarHeight, position.width, position.height-kToolbarHeight); return new Rect(0, 0, position.width, position.height - kPresetsHeight); } static internal Keyframe[] GetLinearKeys() { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, 0, 1, 1); keys[1] = new Keyframe(1, 1, 1, 1); SetSmoothEditable(ref keys, TangentMode.Auto); return keys; } static internal Keyframe[] GetLinearMirrorKeys() { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, 1, -1, -1); keys[1] = new Keyframe(1, 0, -1, -1); SetSmoothEditable(ref keys, TangentMode.Auto); return keys; } static internal Keyframe[] GetEaseInKeys() { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, 0, 0, 0); keys[1] = new Keyframe(1, 1, 2, 2); SetSmoothEditable(ref keys, TangentMode.Free); return keys; } static internal Keyframe[] GetEaseInMirrorKeys() { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, 1, -2, -2); keys[1] = new Keyframe(1, 0, 0, 0); SetSmoothEditable(ref keys, TangentMode.Free); return keys; } static internal Keyframe[] GetEaseOutKeys() { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, 0, 2, 2); keys[1] = new Keyframe(1, 1, 0, 0); SetSmoothEditable(ref keys, TangentMode.Free); return keys; } static internal Keyframe[] GetEaseOutMirrorKeys() { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, 1, 0, 0); keys[1] = new Keyframe(1, 0, -2, -2); SetSmoothEditable(ref keys, TangentMode.Free); return keys; } static internal Keyframe[] GetEaseInOutKeys() { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, 0, 0, 0); keys[1] = new Keyframe(1, 1, 0, 0); SetSmoothEditable(ref keys, TangentMode.Free); return keys; } static internal Keyframe[] GetEaseInOutMirrorKeys() { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, 1, 0, 0); keys[1] = new Keyframe(1, 0, 0, 0); SetSmoothEditable(ref keys, TangentMode.Free); return keys; } static internal Keyframe[] GetConstantKeys(float value) { Keyframe[] keys = new Keyframe[2]; keys[0] = new Keyframe(0, value, 0, 0); keys[1] = new Keyframe(1, value, 0, 0); SetSmoothEditable(ref keys, TangentMode.Auto); return keys; } static internal void SetSmoothEditable(ref Keyframe[] keys, TangentMode tangentMode) { for (int i = 0; i < keys.Length; i++) { AnimationUtility.SetKeyBroken(ref keys[i], false); AnimationUtility.SetKeyLeftTangentMode(ref keys[i], tangentMode); AnimationUtility.SetKeyRightTangentMode(ref keys[i], tangentMode); } } public static Keyframe[] NormalizeKeys(Keyframe[] sourceKeys, NormalizationMode normalization, CurveEditor curveEditor) { Rect normalizationRect; if (!GetNormalizationRect(out normalizationRect, curveEditor)) // No normalization rect, just return a copy of the source keyframes normalization = NormalizationMode.None; return CopyAndScaleCurveKeys(sourceKeys, normalizationRect, normalization); } Keyframe[] GetDenormalizedKeys(Keyframe[] sourceKeys) { return GetDenormalizedKeys(sourceKeys, m_CurveEditor); } public static Keyframe[] GetDenormalizedKeys(Keyframe[] sourceKeys, CurveEditor curveEditor) { return NormalizeKeys(sourceKeys, NormalizationMode.Denormalize, curveEditor); } Keyframe[] GetNormalizedKeys(Keyframe[] sourceKeys) { return GetNormalizedKeys(sourceKeys, m_CurveEditor); } public static Keyframe[] GetNormalizedKeys(Keyframe[] sourceKeys, CurveEditor curveEditor) { return NormalizeKeys(sourceKeys, NormalizationMode.Normalize, curveEditor); } void OnGUI() { bool gotMouseUp = (Event.current.type == EventType.MouseUp); if (m_DelegateView == null && m_OnCurveChanged == null) m_Curve = null; if (ms_Styles == null) ms_Styles = new Styles(); // Curve Editor m_CurveEditor.rect = GetCurveEditorRect(); m_CurveEditor.hRangeLocked = Event.current.shift; m_CurveEditor.vRangeLocked = EditorGUI.actionKey; GUI.changed = false; GUI.Label(m_CurveEditor.drawRect, GUIContent.none, ms_Styles.curveEditorBackground); m_CurveEditor.OnGUI(); // Preset swatch area GUI.Box(new Rect(0, position.height - kPresetsHeight, position.width, kPresetsHeight), "", ms_Styles.curveSwatchArea); Color curveColor = m_Color; curveColor.a *= 0.6f; const float margin = 45f; const float width = 40f; const float height = 25f; float yPos = position.height - kPresetsHeight + (kPresetsHeight - height) * 0.5f; InitCurvePresets(); CurvePresetLibrary curveLibrary = m_CurvePresets.GetPresetLibraryEditor().GetCurrentLib(); if (curveLibrary != null) { for (int i = 0; i < curveLibrary.Count(); i++) { Rect swatchRect = new Rect(margin + (width + 5f) * i, yPos, width, height); m_GUIContent.tooltip = curveLibrary.GetName(i); if (GUI.Button(swatchRect, m_GUIContent, ms_Styles.curveSwatch)) { AnimationCurve animCurve = curveLibrary.GetPreset(i) as AnimationCurve; m_Curve.keys = GetDenormalizedKeys(animCurve.keys); m_Curve.postWrapMode = animCurve.postWrapMode; m_Curve.preWrapMode = animCurve.preWrapMode; m_CurveEditor.SelectNone(); SendEvent(CurveChangedCommand, true); } if (Event.current.type == EventType.Repaint) curveLibrary.Draw(swatchRect, i); if (swatchRect.xMax > position.width - 2 * margin) break; } } Rect presetDropDownButtonRect = new Rect(margin - 20f, yPos + 5f, 20, 20); PresetDropDown(presetDropDownButtonRect); // For adding default preset curves //if (EditorGUI.DropdownButton(new Rect (position.width -26, yPos, 20, 20), GUIContent.none, FocusType.Passive, "OL Plus")) // AddDefaultPresetsToCurrentLib (); if (Event.current.type == EventType.Used && gotMouseUp) { DoUpdateCurve(false); SendEvent(CurveChangeCompletedCommand, true); } else if (Event.current.type != EventType.Layout && Event.current.type != EventType.Repaint) { DoUpdateCurve(true); } } void PresetDropDown(Rect rect) { if (EditorGUI.DropdownButton(rect, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Passive, EditorStyles.inspectorTitlebarText)) { if (m_Curve != null) { if (m_CurvePresets == null) { Debug.LogError("Curve presets error"); return; } ValidateCurveLibraryTypeAndScale(); AnimationCurve copy = new AnimationCurve(GetNormalizedKeys(m_Curve.keys)); copy.postWrapMode = m_Curve.postWrapMode; copy.preWrapMode = m_Curve.preWrapMode; m_CurvePresets.curveToSaveAsPreset = copy; PopupWindow.Show(rect, m_CurvePresets); } } } void ValidateCurveLibraryTypeAndScale() { Rect normalizationRect; if (GetNormalizationRect(out normalizationRect, m_CurveEditor)) { if (curveLibraryType != CurveLibraryType.NormalizedZeroToOne) Debug.LogError("When having a normalize rect we should be using curve library type: NormalizedZeroToOne (normalizationRect: " + normalizationRect + ")"); } else { if (curveLibraryType != CurveLibraryType.Unbounded) Debug.LogError("When NOT having a normalize rect we should be using library type: Unbounded"); } } public void UpdateCurve() { DoUpdateCurve(false); } private void DoUpdateCurve(bool exitGUI) { if (m_CurveEditor.animationCurves.Length > 0 && m_CurveEditor.animationCurves[0] != null && m_CurveEditor.animationCurves[0].changed) { m_CurveEditor.animationCurves[0].changed = false; RefreshShownCurves(); SendEvent(CurveChangedCommand, exitGUI); } } void SendEvent(string eventName, bool exitGUI) { if (m_DelegateView) { Event e = EditorGUIUtility.CommandEvent(eventName); Repaint(); m_DelegateView.SendEvent(e); if (exitGUI) GUIUtility.ExitGUI(); } if (m_OnCurveChanged != null) { m_OnCurveChanged(curve); } GUI.changed = true; } [Shortcut("Curve Editor/Frame All", typeof(CurveEditorWindow), KeyCode.A)] static void FrameClip(ShortcutArguments args) { var curveEditorWindow = (CurveEditorWindow)args.context; if (EditorWindow.focusedWindow != curveEditorWindow) return; curveEditorWindow.FrameClip(); curveEditorWindow.Repaint(); } } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveEditorWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveEditorWindow.cs", "repo_id": "UnityCsReference", "token_count": 11271 }
251
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEditor; namespace UnityEditorInternal { // Required information for animation recording. internal interface IAnimationRecordingState { GameObject activeGameObject { get; } GameObject activeRootGameObject { get; } AnimationClip activeAnimationClip { get; } int currentFrame { get; } bool addZeroFrame { get; } bool DiscardModification(PropertyModification modification); void SaveCurve(AnimationWindowCurve curve); void AddPropertyModification(EditorCurveBinding binding, PropertyModification propertyModification, bool keepPrefabOverride); } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/IAnimationRecordingState.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/IAnimationRecordingState.cs", "repo_id": "UnityCsReference", "token_count": 281 }
252
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System.Collections.Generic; using System.Globalization; namespace UnityEditor { [System.Serializable] class TimeArea : ZoomableArea { [SerializeField] private TickHandler m_HTicks; public TickHandler hTicks { get { return m_HTicks; } set { m_HTicks = value; } } [SerializeField] private TickHandler m_VTicks; static readonly List<float> s_TickCache = new List<float>(1000); public TickHandler vTicks { get { return m_VTicks; } set { m_VTicks = value; } } internal const int kTickRulerDistMin = 3 ; // min distance between ruler tick marks before they disappear completely internal const int kTickRulerDistFull = 80; // distance between ruler tick marks where they gain full strength internal const int kTickRulerDistLabel = 40; // min distance between ruler tick mark labels internal const float kTickRulerHeightMax = 0.7f; // height of the ruler tick marks when they are highest internal const float kTickRulerFatThreshold = 0.5f ; // size of ruler tick marks at which they begin getting fatter public enum TimeFormat { None, // Unformatted time TimeFrame, // Time:Frame Frame // Integer frame } class Styles2 { public GUIStyle timelineTick = "AnimationTimelineTick"; public GUIStyle playhead = "AnimationPlayHead"; } static Styles2 timeAreaStyles; static void InitStyles() { if (timeAreaStyles == null) timeAreaStyles = new Styles2(); } public TimeArea(bool minimalGUI) : this(minimalGUI, true, true) {} public TimeArea(bool minimalGUI, bool enableSliderZoom) : this(minimalGUI, enableSliderZoom, enableSliderZoom) {} public TimeArea(bool minimalGUI, bool enableSliderZoomHorizontal, bool enableSliderZoomVertical) : base(minimalGUI, enableSliderZoomHorizontal, enableSliderZoomVertical) { float[] modulos = new float[] { 0.0000001f, 0.0000005f, 0.000001f, 0.000005f, 0.00001f, 0.00005f, 0.0001f, 0.0005f, 0.001f, 0.005f, 0.01f, 0.05f, 0.1f, 0.5f, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, 500000, 1000000, 5000000, 10000000 }; hTicks = new TickHandler(); hTicks.SetTickModulos(modulos); vTicks = new TickHandler(); vTicks.SetTickModulos(modulos); } public void SetTickMarkerRanges() { hTicks.SetRanges(shownArea.xMin, shownArea.xMax, drawRect.xMin, drawRect.xMax); vTicks.SetRanges(shownArea.yMin, shownArea.yMax, drawRect.yMin, drawRect.yMax); } public void DrawMajorTicks(Rect position, float frameRate) { GUI.BeginGroup(position); if (Event.current.type != EventType.Repaint) { GUI.EndGroup(); return; } InitStyles(); HandleUtility.ApplyWireMaterial(); SetTickMarkerRanges(); hTicks.SetTickStrengths(kTickRulerDistMin, kTickRulerDistFull, true); Color tickColor = timeAreaStyles.timelineTick.normal.textColor; tickColor.a = 0.1f; if (Application.platform == RuntimePlatform.WindowsEditor) GL.Begin(GL.QUADS); else GL.Begin(GL.LINES); // Draw tick markers of various sizes Rect theShowArea = shownArea; for (int l = 0; l < hTicks.tickLevels; l++) { float strength = hTicks.GetStrengthOfLevel(l) * .9f; if (strength > kTickRulerFatThreshold) { s_TickCache.Clear(); hTicks.GetTicksAtLevel(l, true, s_TickCache); for (int i = 0; i < s_TickCache.Count; i++) { if (s_TickCache[i] < 0) continue; int frame = Mathf.RoundToInt(s_TickCache[i] * frameRate); float x = FrameToPixel(frame, frameRate, position, theShowArea); // Draw line DrawVerticalLineFast(x, 0.0f, position.height, tickColor); } } } GL.End(); GUI.EndGroup(); } public void TimeRuler(Rect position, float frameRate) { TimeRuler(position, frameRate, true, false, 1f, TimeFormat.TimeFrame); } public void TimeRuler(Rect position, float frameRate, bool labels, bool useEntireHeight, float alpha, TimeFormat timeFormat) { Color backupCol = GUI.color; GUI.BeginGroup(position); InitStyles(); HandleUtility.ApplyWireMaterial(); Color tempBackgroundColor = GUI.backgroundColor; SetTickMarkerRanges(); hTicks.SetTickStrengths(kTickRulerDistMin, kTickRulerDistFull, true); Color baseColor = timeAreaStyles.timelineTick.normal.textColor; baseColor.a = 0.75f * alpha; if (Event.current.type == EventType.Repaint) { if (Application.platform == RuntimePlatform.WindowsEditor) GL.Begin(GL.QUADS); else GL.Begin(GL.LINES); // Draw tick markers of various sizes Rect cachedShowArea = shownArea; for (int l = 0; l < hTicks.tickLevels; l++) { float strength = hTicks.GetStrengthOfLevel(l) * .9f; s_TickCache.Clear(); hTicks.GetTicksAtLevel(l, true, s_TickCache); for (int i = 0; i < s_TickCache.Count; i++) { if (s_TickCache[i] < hRangeMin || s_TickCache[i] > hRangeMax) continue; int frame = Mathf.RoundToInt(s_TickCache[i] * frameRate); float height = useEntireHeight ? position.height : position.height * Mathf.Min(1, strength) * kTickRulerHeightMax; float x = FrameToPixel(frame, frameRate, position, cachedShowArea); // Draw line DrawVerticalLineFast(x, position.height - height + 0.5f, position.height - 0.5f, new Color(1, 1, 1, strength / kTickRulerFatThreshold) * baseColor); } } GL.End(); } if (labels) { // Draw tick labels int labelLevel = hTicks.GetLevelWithMinSeparation(kTickRulerDistLabel); s_TickCache.Clear(); hTicks.GetTicksAtLevel(labelLevel, false, s_TickCache); for (int i = 0; i < s_TickCache.Count; i++) { if (s_TickCache[i] < hRangeMin || s_TickCache[i] > hRangeMax) continue; int frame = Mathf.RoundToInt(s_TickCache[i] * frameRate); // Important to take floor of positions of GUI stuff to get pixel correct alignment of // stuff drawn with both GUI and Handles/GL. Otherwise things are off by one pixel half the time. float labelpos = Mathf.Floor(FrameToPixel(frame, frameRate, position)); string label = FormatTickTime(s_TickCache[i], frameRate, timeFormat); GUI.Label(new Rect(labelpos + 3, -1, 40, 20), label, timeAreaStyles.timelineTick); } } GUI.EndGroup(); GUI.backgroundColor = tempBackgroundColor; GUI.color = backupCol; } public static void DrawPlayhead(float x, float yMin, float yMax, float thickness, float alpha) { if (Event.current.type != EventType.Repaint) return; InitStyles(); float halfThickness = thickness * 0.5f; Color lineColor = timeAreaStyles.playhead.normal.textColor.AlphaMultiplied(alpha); if (thickness > 1f) { Rect labelRect = Rect.MinMaxRect(x - halfThickness, yMin, x + halfThickness, yMax); EditorGUI.DrawRect(labelRect, lineColor); } else { DrawVerticalLine(x, yMin, yMax, lineColor); } } public static void DrawVerticalLine(float x, float minY, float maxY, Color color) { if (Event.current.type != EventType.Repaint) return; Color backupCol = Handles.color; HandleUtility.ApplyWireMaterial(); if (Application.platform == RuntimePlatform.WindowsEditor) GL.Begin(GL.QUADS); else GL.Begin(GL.LINES); DrawVerticalLineFast(x, minY, maxY, color); GL.End(); Handles.color = backupCol; } public static void DrawVerticalLineFast(float x, float minY, float maxY, Color color) { if (Application.platform == RuntimePlatform.WindowsEditor) { GL.Color(color); GL.Vertex(new Vector3(x - 0.5f, minY, 0)); GL.Vertex(new Vector3(x + 0.5f, minY, 0)); GL.Vertex(new Vector3(x + 0.5f, maxY, 0)); GL.Vertex(new Vector3(x - 0.5f, maxY, 0)); } else { GL.Color(color); GL.Vertex(new Vector3(x, minY, 0)); GL.Vertex(new Vector3(x, maxY, 0)); } } public enum TimeRulerDragMode { None, Start, End, Dragging, Cancel } static float s_OriginalTime; static float s_PickOffset; public TimeRulerDragMode BrowseRuler(Rect position, ref float time, float frameRate, bool pickAnywhere, GUIStyle thumbStyle) { int id = GUIUtility.GetControlID(3126789, FocusType.Passive); return BrowseRuler(position, id, ref time, frameRate, pickAnywhere, thumbStyle); } public TimeRulerDragMode BrowseRuler(Rect position, int id, ref float time, float frameRate, bool pickAnywhere, GUIStyle thumbStyle) { Event evt = Event.current; Rect pickRect = position; if (time != -1) { pickRect.x = Mathf.Round(TimeToPixel(time, position)) - thumbStyle.overflow.left; pickRect.width = thumbStyle.fixedWidth + thumbStyle.overflow.horizontal; } switch (evt.GetTypeForControl(id)) { case EventType.Repaint: if (time != -1) { bool hover = position.Contains(evt.mousePosition); pickRect.x += thumbStyle.overflow.left; thumbStyle.Draw(pickRect, id == GUIUtility.hotControl, hover || id == GUIUtility.hotControl, false, false); } break; case EventType.MouseDown: if (pickRect.Contains(evt.mousePosition)) { GUIUtility.hotControl = id; s_PickOffset = evt.mousePosition.x - TimeToPixel(time, position); evt.Use(); return TimeRulerDragMode.Start; } else if (pickAnywhere && position.Contains(evt.mousePosition)) { GUIUtility.hotControl = id; float newT = SnapTimeToWholeFPS(PixelToTime(evt.mousePosition.x, position), frameRate); s_OriginalTime = time; if (newT != time) GUI.changed = true; time = newT; s_PickOffset = 0; evt.Use(); return TimeRulerDragMode.Start; } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { float newT = SnapTimeToWholeFPS(PixelToTime(evt.mousePosition.x - s_PickOffset, position), frameRate); if (newT != time) GUI.changed = true; time = newT; evt.Use(); return TimeRulerDragMode.Dragging; } break; case EventType.MouseUp: if (GUIUtility.hotControl == id) { GUIUtility.hotControl = 0; evt.Use(); return TimeRulerDragMode.End; } break; case EventType.KeyDown: if (GUIUtility.hotControl == id && evt.keyCode == KeyCode.Escape) { if (time != s_OriginalTime) GUI.changed = true; time = s_OriginalTime; GUIUtility.hotControl = 0; evt.Use(); return TimeRulerDragMode.Cancel; } break; } return TimeRulerDragMode.None; } private float FrameToPixel(float i, float frameRate, Rect rect, Rect theShownArea) { return (i - theShownArea.xMin * frameRate) * rect.width / (theShownArea.width * frameRate); } public float FrameToPixel(float i, float frameRate, Rect rect) { return FrameToPixel(i, frameRate, rect, shownArea); } public float TimeField(Rect rect, int id, float time, float frameRate, TimeFormat timeFormat) { if (timeFormat == TimeFormat.None) { float newTime = EditorGUI.DoFloatField( EditorGUI.s_RecycledEditor, rect, new Rect(0, 0, 0, 0), id, time, EditorGUI.kFloatFieldFormatString, EditorStyles.numberField, false); return SnapTimeToWholeFPS(newTime, frameRate); } if (timeFormat == TimeFormat.Frame) { int frame = Mathf.RoundToInt(time * frameRate); int newFrame = EditorGUI.DoIntField( EditorGUI.s_RecycledEditor, rect, new Rect(0, 0, 0, 0), id, frame, EditorGUI.kIntFieldFormatString, EditorStyles.numberField, false, 0f); return (float)newFrame / frameRate; } else // if (timeFormat == TimeFormat.TimeFrame) { string str = FormatTime(time, frameRate, TimeFormat.TimeFrame); string allowedCharacters = "0123456789.,:"; bool changed; str = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, rect, str, EditorStyles.numberField, allowedCharacters, out changed, false, false, false); if (changed) { if (GUIUtility.keyboardControl == id) { GUI.changed = true; // Make sure that comma & period are interchangable. str = str.Replace(',', '.'); // format is time:frame int index = str.IndexOf(':'); if (index >= 0) { string timeStr = str.Substring(0, index); string frameStr = str.Substring(index + 1); int timeValue, frameValue; if (int.TryParse(timeStr, out timeValue) && int.TryParse(frameStr, out frameValue)) { float newTime = (float)timeValue + (float)frameValue / frameRate; return newTime; } } // format is floating time value. else { float newTime; if (float.TryParse(str, out newTime)) { return SnapTimeToWholeFPS(newTime, frameRate); } } } } } return time; } public float ValueField(Rect rect, int id, float value) { float newValue = EditorGUI.DoFloatField( EditorGUI.s_RecycledEditor, rect, new Rect(0, 0, 0, 0), id, value, EditorGUI.kFloatFieldFormatString, EditorStyles.numberField, false); return newValue; } public string FormatTime(float time, float frameRate, TimeFormat timeFormat) { if (timeFormat == TimeFormat.None) { int hDecimals; if (frameRate != 0) hDecimals = MathUtils.GetNumberOfDecimalsForMinimumDifference(1 / frameRate); else hDecimals = MathUtils.GetNumberOfDecimalsForMinimumDifference(shownArea.width / drawRect.width); return time.ToString("N" + hDecimals, CultureInfo.InvariantCulture.NumberFormat); } int frame = Mathf.RoundToInt(time * frameRate); if (timeFormat == TimeFormat.TimeFrame) { int frameDigits = frameRate != 0 ? ((int)frameRate - 1).ToString().Length : 1; string sign = string.Empty; if (frame < 0) { sign = "-"; frame = -frame; } return sign + (frame / (int)frameRate) + ":" + (frame % frameRate).ToString().PadLeft(frameDigits, '0'); } else { return frame.ToString(); } } public virtual string FormatTickTime(float time, float frameRate, TimeFormat timeFormat) { return FormatTime(time, frameRate, timeFormat); } public string FormatValue(float value) { int vDecimals = MathUtils.GetNumberOfDecimalsForMinimumDifference(shownArea.height / drawRect.height); return value.ToString("N" + vDecimals, CultureInfo.InvariantCulture.NumberFormat); } public float SnapTimeToWholeFPS(float time, float frameRate) { if (frameRate == 0) return time; return Mathf.Round(time * frameRate) / frameRate; } public void DrawTimeOnSlider(float time, Color c, float maxTime, float leftSidePadding = 0, float rightSidePadding = 0) { const float maxTimeFudgeFactor = 3; if (!hSlider) return; if (styles.horizontalScrollbar == null) styles.InitGUIStyles(false, allowSliderZoomHorizontal, allowSliderZoomVertical); var inMin = TimeToPixel(0, rect); // Assume 0 minTime var inMax = TimeToPixel(maxTime, rect); var outMin = TimeToPixel(shownAreaInsideMargins.xMin, rect) + styles.horizontalScrollbarLeftButton.fixedWidth + leftSidePadding; var outMax = TimeToPixel(shownAreaInsideMargins.xMax, rect) - (styles.horizontalScrollbarRightButton.fixedWidth + rightSidePadding); var x = (TimeToPixel(time, rect) - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; if (x > rect.xMax - (styles.horizontalScrollbarLeftButton.fixedWidth + leftSidePadding + maxTimeFudgeFactor)) return; var inset = styles.sliderWidth - styles.visualSliderWidth; var otherInset = (vSlider && hSlider) ? inset : 0; var hRangeSliderRect = new Rect(drawRect.x + 1, drawRect.yMax - inset, drawRect.width - otherInset, styles.sliderWidth); var p1 = new Vector2(x, hRangeSliderRect.yMin); var p2 = new Vector2(x, hRangeSliderRect.yMax); var lineRect = Rect.MinMaxRect(p1.x - 0.5f, p1.y, p2.x + 0.5f, p2.y); EditorGUI.DrawRect(lineRect, c); } } }
UnityCsReference/Editor/Mono/Animation/TimeArea.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/TimeArea.cs", "repo_id": "UnityCsReference", "token_count": 11607 }
253
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License // NOTE: the build system includes this source file in ALL Editor modules using System.Runtime.CompilerServices; using UnityEngine; [assembly: AssemblyIsEditorAssembly] // TODO: over time, remove the InternalsVisibleTo attributes from this section // You can start by moving them to EditorCoreModuleAssemblyInfo.cs to reduce internal visibility // To remove a line in there, the target assembly must not depend on _any_ internal API from built-in Editor modules // ADD_NEW_PLATFORM_HERE [assembly: InternalsVisibleTo("Unity.LiveNotes")] [assembly: InternalsVisibleTo("Unity.Audio.Tests")] [assembly: InternalsVisibleTo("Unity.Burst")] [assembly: InternalsVisibleTo("Unity.Burst.Editor")] [assembly: InternalsVisibleTo("Unity.Cloud.Collaborate.Editor")] [assembly: InternalsVisibleTo("Unity.CollabProxy.Editor")] [assembly: InternalsVisibleTo("Unity.CollabProxy.EditorTests")] [assembly: InternalsVisibleTo("Unity.CollabProxy.UI")] [assembly: InternalsVisibleTo("Unity.CollabProxy.UI.Tests")] [assembly: InternalsVisibleTo("Unity.CollabProxy.Client")] [assembly: InternalsVisibleTo("Unity.CollabProxy.Client.Tests")] [assembly: InternalsVisibleTo("UnityEditor.Advertisements")] [assembly: InternalsVisibleTo("Unity.PackageManager")] [assembly: InternalsVisibleTo("Unity.PackageManagerStandalone")] [assembly: InternalsVisibleTo("Unity.AndroidBuildPipeline")] [assembly: InternalsVisibleTo("Unity.Automation")] [assembly: InternalsVisibleTo("UnityEngine.Common")] [assembly: InternalsVisibleTo("Unity.PureCSharpTests")] [assembly: InternalsVisibleTo("Unity.IntegrationTests")] [assembly: InternalsVisibleTo("Unity.DeploymentTests.Services")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.ExternalVersionControl")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.UnityAnalytics")] [assembly: InternalsVisibleTo("Unity.PerformanceIntegrationTests")] [assembly: InternalsVisibleTo("Unity.Timeline.Editor")] [assembly: InternalsVisibleTo("Unity.PackageManagerUI.Develop.Editor")] [assembly: InternalsVisibleTo("Unity.DeviceSimulator.Editor")] [assembly: InternalsVisibleTo("Unity.Timeline.EditorTests")] [assembly: InternalsVisibleTo("UnityEditor.Graphs")] [assembly: InternalsVisibleTo("UnityEditor.UWP.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.iOS.Extensions.Common")] [assembly: InternalsVisibleTo("UnityEditor.iOS.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.VisionOS.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.AppleTV.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.Android.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.XboxOne.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.PS4.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.PS5.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.Switch.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.WebGL.Extensions")] [assembly: InternalsVisibleTo("Unity.WebGL.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.LinuxStandalone.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.CloudRendering.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.EmbeddedLinux.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.QNX.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.WindowsStandalone.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.OSXStandalone.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.Lumin.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.GameCoreScarlett.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.GameCoreXboxOne.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.GameCoreCommon.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.Networking")] [assembly: InternalsVisibleTo("UnityEngine.Networking")] [assembly: InternalsVisibleTo("Unity.Analytics.Editor")] [assembly: InternalsVisibleTo("UnityEditor.Analytics")] [assembly: InternalsVisibleTo("UnityEditor.Purchasing")] [assembly: InternalsVisibleTo("UnityEditor.Lumin")] [assembly: InternalsVisibleTo("UnityEditor.Switch.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.EditorTestsRunner")] [assembly: InternalsVisibleTo("UnityEditor.TestRunner")] [assembly: InternalsVisibleTo("UnityEditor.TestRunner.Tests")] [assembly: InternalsVisibleTo("Unity.Compiler.Client")] [assembly: InternalsVisibleTo("ExternalCSharpCompiler")] [assembly: InternalsVisibleTo("UnityEngine.TestRunner")] [assembly: InternalsVisibleTo("UnityEditor.VR")] [assembly: InternalsVisibleTo("Unity.RuntimeTests")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework")] [assembly: InternalsVisibleTo("Assembly-CSharp-Editor-firstpass-testable")] [assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: InternalsVisibleTo("UnityEditor.InteractiveTutorialsFramework")] [assembly: InternalsVisibleTo("UnityEditor.Networking")] [assembly: InternalsVisibleTo("UnityEditor.UI")] [assembly: InternalsVisibleTo("UnityEditor.AR")] [assembly: InternalsVisibleTo("UnityEditor.SpatialTracking")] [assembly: InternalsVisibleTo("Unity.WindowsMRAutomation")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.001")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.002")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.003")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.004")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.005")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.006")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.007")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.008")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.009")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.010")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.011")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.012")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.013")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.014")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.015")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.016")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.017")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.018")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.019")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.020")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.021")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.022")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.023")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridge.024")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridgeDev.001")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridgeDev.002")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridgeDev.003")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridgeDev.004")] [assembly: InternalsVisibleTo("Unity.InternalAPIEditorBridgeDev.005")] [assembly: InternalsVisibleTo("Unity.XR.Remoting.Editor")] [assembly: InternalsVisibleTo("UnityEngine.Common")] [assembly: InternalsVisibleTo("Unity.UI.Builder.Editor")] [assembly: InternalsVisibleTo("UnityEditor.UIElements.Tests.Tests")] // for UI Test Framework [assembly: InternalsVisibleTo("UnityEditor.UIBuilderModule")] [assembly: InternalsVisibleTo("Unity.UI.Builder.EditorTests")] [assembly: InternalsVisibleTo("Unity.GraphViewTestUtilities.Editor")] [assembly: InternalsVisibleTo("Unity.ProBuilder.Editor")] [assembly: InternalsVisibleTo("Unity.2D.Sprite.Editor")] [assembly: InternalsVisibleTo("Unity.2D.Sprite.EditorTests")] [assembly: InternalsVisibleTo("Unity.2D.Tilemap.Editor")] [assembly: InternalsVisibleTo("Unity.2D.Tilemap.EditorTests")] [assembly: InternalsVisibleTo("Unity.PackageCleanConsoleTest.Editor")] [assembly: InternalsVisibleTo("Unity.TextCore.Editor.Tests")] [assembly: InternalsVisibleTo("UnityEditor.TextCoreTextEngineModule")] [assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor")] [assembly: InternalsVisibleTo("Unity.Animation.Editor.AnimationWindow")] [assembly: InternalsVisibleTo("Unity.VisualEffectGraph.Editor")] [assembly: InternalsVisibleTo("Unity.Testing.VisualEffectGraph.EditorTests")] [assembly: InternalsVisibleTo("Unity.VisualEffectGraph.EditorTests")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.Multiple_SRP.EditorTests")] [assembly: InternalsVisibleTo("Unity.SceneTemplate.Editor")] [assembly: InternalsVisibleTo("com.unity.purchasing.udp.Editor")] [assembly: InternalsVisibleTo("com.unity.search.extensions.editor")] [assembly: InternalsVisibleTo("UnityEditor.Android.Extensions")] [assembly: InternalsVisibleTo("Unity.Entities.Build")] [assembly: InternalsVisibleTo("Unity.Scenes")] // This should move with the AnimationWindow to a module at some point [assembly: InternalsVisibleTo("UnityEditor.Modules.Animation.tests.AnimationWindow")] [assembly: InternalsVisibleTo("UnityEditor.Modules.Physics.Tests")] [assembly: InternalsVisibleTo("UnityEditor.Switch.Tests")] [assembly: InternalsVisibleTo("UnityEditor.BuildProfileModule.Tests")] [assembly: InternalsVisibleTo("UnityEditor.PS4.Tests")] [assembly: InternalsVisibleTo("UnityEditor.PS5.Tests")] [assembly: InternalsVisibleTo("Unity.Automation.Players.EmbeddedLinux")] [assembly: InternalsVisibleTo("Unity.Automation.Players.QNX")]
UnityCsReference/Editor/Mono/AssemblyInfo/AssemblyInfo.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssemblyInfo/AssemblyInfo.cs", "repo_id": "UnityCsReference", "token_count": 2945 }
254
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using System.Collections.Generic; using UnityEngine; using Object = UnityEngine.Object; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEditor.AssetImporters; namespace UnityEditor { [NativeHeader("Editor/Src/AssetPipeline/AssetImporter.h")] [NativeHeader("Editor/Src/AssetPipeline/AssetImporter.bindings.h")] [ExcludeFromObjectFactory] [Preserve] [UsedByNativeCode] public partial class AssetImporter : Object { [NativeType(CodegenOptions.Custom, "MonoSourceAssetIdentifier")] public struct SourceAssetIdentifier { public SourceAssetIdentifier(Object asset) { if (asset == null) { throw new ArgumentNullException("asset"); } this.type = asset.GetType(); this.name = asset.name; } public SourceAssetIdentifier(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The name is empty", "name"); } this.type = type; this.name = name; } public Type type; public string name; } [NativeName("AssetPathName")] public extern string assetPath { get; } public extern bool importSettingsMissing { get; } public extern ulong assetTimeStamp { get; } public extern string userData { get; set; } public extern string assetBundleName { get; set; } public extern string assetBundleVariant { get; set; } public static ImportLog GetImportLog(string path) { return GetImportLog(AssetDatabase.GUIDFromAssetPath(path)); } [FreeFunction("AssetImporter::GetImportLog")] internal static extern ImportLog GetImportLog(GUID guid); [FreeFunction("AssetImporter::GetImportLogEntriesCount")] internal static extern bool GetImportLogEntriesCount(GUID guid, out int nbErrors, out int nbWarnings); [NativeName("SetAssetBundleName")] extern public void SetAssetBundleNameAndVariant(string assetBundleName, string assetBundleVariant); [NativeMethod("SetThumbnailFromTexture2D")] extern internal void SetThumbnailFromTexture2D(Texture2D image, int instanceID); [FreeFunction("FindAssetImporterAtAssetPath")] extern public static AssetImporter GetAtPath(string path); public void SaveAndReimport() { AssetDatabase.ImportAsset(assetPath); } [FreeFunction("AssetImporterBindings::LocalFileIDToClassID")] extern internal static int LocalFileIDToClassID(long fileId); [FreeFunction("AssetImporterBindings::MakeLocalFileIDWithHash")] extern internal static long MakeLocalFileIDWithHash(int persistentTypeId, string name, long offset); extern internal long MakeInternalID(int persistentTypeId, string name); extern public void AddRemap(SourceAssetIdentifier identifier, Object externalObject); extern public bool RemoveRemap(SourceAssetIdentifier identifier); extern internal void RenameSubAssets(int peristentTypeId, string[] oldNames, string[] newNames); [FreeFunction("AssetImporterBindings::GetIdentifiers")] extern private static SourceAssetIdentifier[] GetIdentifiers(AssetImporter self); [FreeFunction("AssetImporterBindings::GetExternalObjects")] extern private static Object[] GetExternalObjects(AssetImporter self); public Dictionary<SourceAssetIdentifier, Object> GetExternalObjectMap() { // bogdanc: this is not optimal - we should have only one call to get both the identifiers and the external objects. // However, the new bindings do not support well output array parameters. // FIXME: change this to a single call when the bindings are fixed SourceAssetIdentifier[] identifiers = GetIdentifiers(this); Object[] externalObjects = GetExternalObjects(this); Dictionary<SourceAssetIdentifier, Object> map = new Dictionary<SourceAssetIdentifier, Object>(); for (int i = 0; i < identifiers.Length; ++i) { map.Add(identifiers[i], externalObjects[i]); } return map; } [FreeFunction("AssetImporterBindings::RegisterImporter", ThrowsException = true)] extern internal static void RegisterImporter(Type importer, int importerVersion, int queuePos, string fileExt, bool supportsImportDependencyHinting, bool autoSelect, bool allowCaching); [FreeFunction("AssetImporterBindings::SupportsRemappedAssetType", HasExplicitThis = true, IsThreadSafe = true)] public extern bool SupportsRemappedAssetType(Type type); internal extern double GetImportStartTime(); internal AssetPostprocessor.PostprocessorInfo[] GetDynamicPostprocessors() { return AssetPostprocessingInternal.GetSortedDynamicPostprocessorsForAsset(assetPath).ToArray(); } internal static AssetPostprocessor.PostprocessorInfo[] GetStaticPostprocessors(Type importerType) { return AssetPostprocessingInternal.GetSortedStaticPostprocessorTypes(importerType).ToArray(); } } }
UnityCsReference/Editor/Mono/AssetPipeline/AssetImporter.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetPipeline/AssetImporter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2510 }
255
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.IO; using System.Runtime.InteropServices; using UnityEngine; namespace UnityEditor.SpeedTree.Importer { #region Data Classes [StructLayout(LayoutKind.Sequential, Pack = 4)] struct Vec2 { private float x, y; public float X { get { return x; } set { x = value; } } public float Y { get { return y; } set { y = value; } } } [StructLayout(LayoutKind.Sequential, Pack = 4)] struct Vec3 { private float x, y, z; public float X { get { return x; } set { x = value; } } public float Y { get { return y; } set { y = value; } } public float Z { get { return z; } set { z = value; } } } [StructLayout(LayoutKind.Sequential, Pack = 4)] struct Vec4 { private float x, y, z, w; public float X { get { return x; } set { x = value; } } public float Y { get { return y; } set { y = value; } } public float Z { get { return z; } set { z = value; } } public float W { get { return w; } set { w = value; } } } [StructLayout(LayoutKind.Sequential, Pack = 4)] struct Bounds3 { public Vec3 Min { get; private set; } public Vec3 Max { get; private set; } } [StructLayout(LayoutKind.Sequential, Pack = 4)] struct Vertex { public Vec3 Anchor { get; private set; } public Vec3 Offset { get; private set; } public Vec3 LodOffset { get; private set; } public Vec3 Normal { get; private set; } public Vec3 Tangent { get; private set; } public Vec3 Binormal { get; private set; } public Vec2 TexCoord { get; private set; } public Vec2 LightmapTexCoord { get; private set; } public Vec3 Color { get; private set; } public float AmbientOcclusion { get; private set; } public float BlendWeight { get; private set; } public Vec3 BranchWind1 { get; private set; } // pos, dir, weight public Vec3 BranchWind2 { get; private set; } public float RippleWeight { get; private set; } public bool CameraFacing { get; private set; } public uint BoneID { get; private set; } } [StructLayout(LayoutKind.Sequential, Pack = 4)] struct DrawCall { public uint MaterialIndex { get; private set; } public bool ContainsFacingGeometry { get; private set; } public uint IndexStart { get; private set; } public uint IndexCount { get; private set; } } [StructLayout(LayoutKind.Sequential, Pack = 4)] struct Bone { public uint ID { get; private set; } public bool ParentID { get; private set; } public Vec3 Start { get; private set; } public Vec3 End { get; private set; } public float Radius { get; private set; } } #endregion #region Data Tables interface ReaderData { public void Initialize(Byte[] data, int offset); } class Lod : ReaderData { private enum OffsetData { Vertices = 0, Indices = 1, DrawCalls = 2 } public Vertex[] Vertices { get; private set; } public uint[] Indices { get; private set; } public DrawCall[] DrawCalls { get; private set; } public void Initialize(Byte[] data, int offset) { Vertices = SpeedTree9ReaderUtility.GetArray<Vertex>(data, offset, (int)OffsetData.Vertices); Indices = SpeedTree9ReaderUtility.GetArray<uint>(data, offset, (int)OffsetData.Indices); DrawCalls = SpeedTree9ReaderUtility.GetArray<DrawCall>(data, offset, (int)OffsetData.DrawCalls); } } class BillboardInfo : ReaderData { private enum OffsetData { LastLodIsBillboard = 0, IncludesTopDown = 1, SideViewCount = 2 } public bool LastLodIsBillboard { get; private set; } public bool IncludesTopDown { get; private set; } public uint SideViewCount { get; private set; } public void Initialize(Byte[] data, int offset) { LastLodIsBillboard = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.LastLodIsBillboard); IncludesTopDown = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.IncludesTopDown); SideViewCount = SpeedTree9ReaderUtility.GetUInt(data, offset, (int)OffsetData.SideViewCount); } } class CollisionObject : ReaderData { private enum OffsetData { Position = 0, Position2 = 1, Radius = 2, UserData = 3 } public Vec3 Position { get; private set; } public Vec3 Position2 { get; private set; } public float Radius { get; private set; } public string UserData { get; private set; } public void Initialize(Byte[] data, int offset) { Position = SpeedTree9ReaderUtility.GetStruct<Vec3>(data, offset, (int)OffsetData.Position); Position2 = SpeedTree9ReaderUtility.GetStruct<Vec3>(data, offset, (int)OffsetData.Position2); Radius = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.Radius); UserData = SpeedTree9ReaderUtility.GetString(data, offset, (int)OffsetData.UserData); } } class MaterialMap : ReaderData { private enum OffsetData { Used = 0, Path = 1, Color = 2 } public bool Used { get; private set; } public string Path { get; private set; } public Vec4 Color { get; private set; } public void Initialize(Byte[] data, int offset) { Used = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.Used); Path = SpeedTree9ReaderUtility.GetString(data, offset, (int)OffsetData.Path); Color = SpeedTree9ReaderUtility.GetStruct<Vec4>(data, offset, (int)OffsetData.Color); } } class STMaterial : ReaderData { private enum OffsetData { Name = 0, TwoSided = 1, FlipNormalsOnBackside = 2, Billboard = 3, Maps = 4 } public string Name { get; private set; } public bool TwoSided { get; private set; } public bool FlipNormalsOnBackside { get; private set; } public bool Billboard { get; private set; } public MaterialMap[] Maps { get; private set; } public void Initialize(Byte[] data, int offset) { Name = SpeedTree9ReaderUtility.GetString(data, offset, (int)OffsetData.Name); TwoSided = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.TwoSided); FlipNormalsOnBackside = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.FlipNormalsOnBackside); Billboard = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.Billboard); Maps = SpeedTree9ReaderUtility.GetDataObjectArray<MaterialMap>(data, offset, (int)OffsetData.Maps); } } #endregion #region Wind Data Tables class WindConfigCommon : ReaderData { private enum OffsetData { StrengthResponse = 0, DirectionResponse = 1, GustFrequency = 5, GustStrengthMin = 6, GustStrengthMax = 7, GustDurationMin = 8, GustDurationMax = 9, GustRiseScalar = 10, GustFallScalar = 11, CurrentStrength = 15 } public float StrengthResponse { get; private set; } public float DirectionResponse { get; private set; } public float GustFrequency { get; private set; } public float GustStrengthMin { get; private set; } public float GustStrengthMax { get; private set; } public float GustDurationMin { get; private set; } public float GustDurationMax { get; private set; } public float GustRiseScalar { get; private set; } public float GustFallScalar { get; private set; } public float CurrentStrength { get; private set; } public void Initialize(Byte[] data, int offset) { StrengthResponse = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.StrengthResponse); DirectionResponse = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.DirectionResponse); GustFrequency = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.GustFrequency); GustStrengthMin = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.GustStrengthMin); GustStrengthMax = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.GustStrengthMax); GustDurationMin = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.GustDurationMin); GustDurationMax = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.GustDurationMax); GustRiseScalar = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.GustRiseScalar); GustFallScalar = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.GustFallScalar); CurrentStrength = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.CurrentStrength); } }; class WindConfigSDK : ReaderData { internal class WindBranch : ReaderData { private enum OffsetData { Bend = 0, Oscillation = 1, Speed = 2, Turbulence = 3, Flexibility = 4, Independence = 5 } public float[] Bend { get; private set; } public float[] Oscillation { get; private set; } public float[] Speed { get; private set; } public float[] Turbulence { get; private set; } public float[] Flexibility { get; private set; } public float Independence { get; private set; } public void Initialize(Byte[] data, int offset) { Bend = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Bend); Oscillation = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Oscillation); Speed = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Speed); Turbulence = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Turbulence); Flexibility = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Flexibility); Independence = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.Independence); } }; internal class WindRipple : ReaderData { private enum OffsetData { Planar = 0, Directional = 1, Speed = 2, Flexibility = 3, Shimmer = 4, Independence = 5 } public float[] Planar { get; private set; } public float[] Directional { get; private set; } public float[] Speed { get; private set; } public float[] Flexibility { get; private set; } public float Shimmer { get; private set; } public float Independence { get; private set; } public void Initialize(Byte[] data, int offset) { Planar = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Planar); Directional = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Directional); Speed = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Speed); Flexibility = SpeedTree9ReaderUtility.GetArray<float>(data, offset, (int)OffsetData.Flexibility); Shimmer = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.Shimmer); Independence = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.Independence); } }; private enum OffsetData { Common = 0, Shared = 1, Branch1 = 2, Branch2 = 3, Ripple = 4, SharedStartHeight = 10, Branch1StretchLimit = 11, Branch2StretchLimit = 12, DoShared = 15, DoBranch1 = 16, DoBranch2 = 17, DoRipple = 18, DoShimmer = 19 } public WindConfigCommon Common { get; private set; } public WindBranch Shared { get; private set; } public WindBranch Branch1 { get; private set; } public WindBranch Branch2 { get; private set; } public WindRipple Ripple { get; private set; } public float SharedStartHeight { get; private set; } public float Branch1StretchLimit { get; private set; } public float Branch2StretchLimit { get; private set; } public bool DoShared { get; private set; } public bool DoBranch1 { get; private set; } public bool DoBranch2 { get; private set; } public bool DoRipple { get; private set; } public bool DoShimmer { get; private set; } public void Initialize(Byte[] data, int offset) { Common = SpeedTree9ReaderUtility.GetDataObject<WindConfigCommon>(data, offset, (int)OffsetData.Common); Shared = SpeedTree9ReaderUtility.GetDataObject<WindBranch>(data, offset, (int)OffsetData.Shared); Branch1 = SpeedTree9ReaderUtility.GetDataObject<WindBranch>(data, offset, (int)OffsetData.Branch1); Branch2 = SpeedTree9ReaderUtility.GetDataObject<WindBranch>(data, offset, (int)OffsetData.Branch2); Ripple = SpeedTree9ReaderUtility.GetDataObject<WindRipple>(data, offset, (int)OffsetData.Ripple); SharedStartHeight = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.SharedStartHeight); Branch1StretchLimit = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.Branch1StretchLimit); Branch2StretchLimit = SpeedTree9ReaderUtility.GetFloat(data, offset, (int)OffsetData.Branch2StretchLimit); DoShared = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.DoShared); DoBranch1 = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.DoBranch1); DoBranch2 = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.DoBranch2); DoRipple = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.DoRipple); DoShimmer = SpeedTree9ReaderUtility.GetBool(data, offset, (int)OffsetData.DoShimmer); } }; #endregion #region Reader Utilities static class SpeedTree9ReaderUtility { public static int GetOffset(in Byte[] data, int offsetIn, int index) { int offset = offsetIn + (index + 1) * 4; return offsetIn + (int)BitConverter.ToUInt32(data, offset); } public static float GetFloat(in Byte[] data, int offsetIn, int index) { return BitConverter.ToSingle(data, GetOffset(data, offsetIn, index)); } public static string GetString(in Byte[] data, int offsetIn, int index) { int offset = GetOffset(data, offsetIn, index); int length = (int)BitConverter.ToUInt32(data, offset); return System.Text.Encoding.UTF8.GetString(data, offset + 4, length - 1); } public static T GetStruct<T>(in Byte[] data, int offsetIn, int index) where T : struct { int offset = GetOffset(data, offsetIn, index); return MemoryMarshal.Cast<byte, T>(data.AsSpan().Slice(offset))[0]; } public static bool GetBool(in Byte[] data, int offsetIn, int index) { return GetInt(data, offsetIn, index) != 0; } public static int GetInt(in Byte[] data, int offsetIn, int index) { return BitConverter.ToInt32(data, GetOffset(data, offsetIn, index)); } public static uint GetUInt(in Byte[] data, int offsetIn, int index) { return BitConverter.ToUInt32(data, GetOffset(data, offsetIn, index)); } public static T[] GetArray<T>(Byte[] data, int offset, int type) where T : struct { int offsetData = SpeedTree9ReaderUtility.GetOffset(data, offset, (int)type); uint countData = BitConverter.ToUInt32(data, offsetData); T[] array = new T[countData]; for (int i = 0; i < countData; i++) { array[i] = MemoryMarshal.Cast<byte, T>(data.AsSpan().Slice(offsetData + 4))[i]; } return array; } public static T GetDataObject<T>(in Byte[] data, int offset, int index) where T : ReaderData, new() { int dataOffset = SpeedTree9ReaderUtility.GetOffset(data, offset, index); T readData = new T(); readData.Initialize(data, dataOffset); return readData; } public static T[] GetDataObjectArray<T>(in Byte[] data, int offset, int index) where T : ReaderData, new() { int dataOffset = SpeedTree9ReaderUtility.GetOffset(data, offset, index); uint dataCount = BitConverter.ToUInt32(data, dataOffset); T[] readData = new T[dataCount]; for (int i = 0; i < dataCount; i++) { int offsetNew = SpeedTree9ReaderUtility.GetOffset(data, dataOffset, i); T newData = new T(); newData.Initialize(data, offsetNew); readData[i] = newData; } return readData; } } #endregion internal class SpeedTree9Reader : IDisposable { internal enum FileStatus { Valid = 0, InvalidPath = 1, InvalidSignature = 2 } enum OffsetData { VersionMajor = 0, VersionMinor = 1, Bounds = 2, Lod = 5, BillboardInfo = 6, CollisionObjects = 7, Materials = 10, Wind = 15 } const string k_TokenKey = "SpeedTree9______"; public uint VersionMajor { get; private set; } public uint VersionMinor { get; private set; } public Bounds3 Bounds { get; private set; } public Lod[] Lod { get; private set; } public BillboardInfo BillboardInfo { get; private set; } public CollisionObject[] CollisionObjects { get; private set; } public STMaterial[] Materials { get; private set; } public WindConfigSDK Wind { get; private set; } private string m_AssetPath; private FileStream m_FileStream; private int m_Offset; private bool m_Disposed; public FileStatus Initialize(string assetPath) { m_AssetPath = assetPath; m_FileStream = new FileStream(m_AssetPath, FileMode.Open, FileAccess.Read); if (!File.Exists(assetPath)) { return FileStatus.InvalidPath; } if (!ValidateFileSignature()) { return FileStatus.InvalidSignature; } return FileStatus.Valid; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected void Dispose(bool disposing) { if (!m_Disposed) { // Manual release of managed resources. if (disposing) { if (m_FileStream != null) { m_FileStream.Close(); } } // Release unmanaged resources. m_Disposed = true; } } public void ReadContent() { byte[] data = File.ReadAllBytes(m_AssetPath); VersionMajor = SpeedTree9ReaderUtility.GetUInt(data, m_Offset, (int)OffsetData.VersionMajor); VersionMinor = SpeedTree9ReaderUtility.GetUInt(data, m_Offset, (int)OffsetData.VersionMinor); Bounds = SpeedTree9ReaderUtility.GetStruct<Bounds3>(data, m_Offset, (int)OffsetData.Bounds); Lod = SpeedTree9ReaderUtility.GetDataObjectArray<Lod>(data, m_Offset, (int)OffsetData.Lod); BillboardInfo = SpeedTree9ReaderUtility.GetDataObject<BillboardInfo>(data, m_Offset, (int)OffsetData.BillboardInfo); CollisionObjects = SpeedTree9ReaderUtility.GetDataObjectArray<CollisionObject>(data, m_Offset, (int)OffsetData.CollisionObjects); Materials = SpeedTree9ReaderUtility.GetDataObjectArray<STMaterial>(data, m_Offset, (int)OffsetData.Materials); Wind = SpeedTree9ReaderUtility.GetDataObject<WindConfigSDK>(data, m_Offset, (int)OffsetData.Wind); if (m_FileStream != null) { m_FileStream.Close(); } } private unsafe bool ValidateFileSignature() { byte[] buffer = new byte[k_TokenKey.Length]; try { int bytesRead = m_FileStream.Read(buffer, m_Offset, k_TokenKey.Length); if (bytesRead != buffer.Length) { return false; } } catch (UnauthorizedAccessException ex) { Debug.LogError(ex.Message); } bool valid = true; for (int i = 0; i < k_TokenKey.Length && valid; ++i) { valid &= (k_TokenKey[i] == buffer[i]); } if (valid) { m_Offset = k_TokenKey.Length; } return valid; } } }
UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTree9Reader.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTree9Reader.cs", "repo_id": "UnityCsReference", "token_count": 10273 }
256
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System.Collections.Generic; namespace UnityEditor { /** * Fetching and caches preview images of asset store assets from the * asset store server */ internal sealed class AssetStorePreviewManager { private AssetStorePreviewManager() {} // disallow instantiation static AssetStorePreviewManager s_SharedAssetStorePreviewManager = null; static RenderTexture s_RenderTexture = null; static internal AssetStorePreviewManager Instance { get { if (s_SharedAssetStorePreviewManager == null) { s_SharedAssetStorePreviewManager = new AssetStorePreviewManager(); s_SharedAssetStorePreviewManager.m_DummyItem.lastUsed = -1; } return s_SharedAssetStorePreviewManager; } } public class CachedAssetStoreImage { private const double kFadeTime = 0.5; public Texture2D image; public double lastUsed; // time since app start public double lastFetched; // time since app start public int requestedWidth; // public string label; // internal AsyncHTTPClient client; // null if not in progress of fetching preview public Color color { get { return Color.Lerp(new Color(1, 1, 1, 0), new Color(1, 1, 1, 1), Mathf.Min(1f, (float)((EditorApplication.timeSinceStartup - lastFetched) / kFadeTime))); } } } // @TODO: MAKE handling of incoming images span several repaints in order to // not have the jumpy behaviour. Just put the in a queue an handle them from there. // Dictionary<string, CachedAssetStoreImage> m_CachedAssetStoreImages; const int kMaxConcurrentDownloads = 15; const int kMaxConvertionsPerTick = 1; int m_MaxCachedAssetStoreImages = 10; int m_Aborted = 0; int m_Success = 0; internal int Requested = 0; internal int CacheHit = 0; int m_CacheRemove = 0; int m_ConvertedThisTick = 0; CachedAssetStoreImage m_DummyItem = new CachedAssetStoreImage(); static bool s_NeedsRepaint = false; static Dictionary<string, CachedAssetStoreImage> CachedAssetStoreImages { get { if (Instance.m_CachedAssetStoreImages == null) { Instance.m_CachedAssetStoreImages = new Dictionary<string, CachedAssetStoreImage>(); } return Instance.m_CachedAssetStoreImages; } } public static int MaxCachedImages { get { return Instance.m_MaxCachedAssetStoreImages; } set { Instance.m_MaxCachedAssetStoreImages = value; } } public static bool CacheFull { get { return CachedAssetStoreImages.Count >= MaxCachedImages; } } public static int Downloading { get { int c = 0; foreach (KeyValuePair<string, CachedAssetStoreImage> kv in CachedAssetStoreImages) if (kv.Value.client != null) c++; return c; } } public static string StatsString() { return string.Format("Reqs: {0}, Ok: {1}, Abort: {2}, CacheDel: {3}, Cache: {4}/{5}, CacheHit: {6}", Instance.Requested, Instance.m_Success, Instance.m_Aborted, Instance.m_CacheRemove, AssetStorePreviewManager.CachedAssetStoreImages.Count, Instance.m_MaxCachedAssetStoreImages, Instance.CacheHit); } /** * Return a texture from a url that points to an image resource * * This method does not block but queues a request to fetch the image and return null. * When the image has been fetched this method will return the image texture downloaded. */ public static CachedAssetStoreImage TextureFromUrl(string url, string label, int textureSize, GUIStyle labelStyle, GUIStyle iconStyle, bool onlyCached) { if (string.IsNullOrEmpty(url)) return Instance.m_DummyItem; CachedAssetStoreImage cached; bool newentry = true; if (CachedAssetStoreImages.TryGetValue(url, out cached)) { cached.lastUsed = EditorApplication.timeSinceStartup; // Refetch the image if the size has changed and is not in the progress of being fetched bool refetchInitiated = cached.requestedWidth == textureSize; bool correctSize = cached.image != null && cached.image.width == textureSize; bool cacheRequestAborted = cached.requestedWidth == -1; if ((correctSize || refetchInitiated || onlyCached) && !cacheRequestAborted) { Instance.CacheHit++; // Use cached image (that may be null) if we're in progress of fetching the image // or if we have rendered the images correctly //return cached; bool fetchingImage = cached.client != null; bool labelDrawn = cached.label == null; bool valid = fetchingImage || labelDrawn; bool convPerTickExceeded = Instance.m_ConvertedThisTick > kMaxConvertionsPerTick; s_NeedsRepaint = s_NeedsRepaint || convPerTickExceeded; return (valid || convPerTickExceeded) ? cached : RenderEntry(cached, labelStyle, iconStyle); } //Debug.Log(string.Format("Found {0} {1} {2} {3}", correctSize, refetchInitiated, onlyCached, cacheRequestAborted)); newentry = false; if (Downloading >= kMaxConcurrentDownloads) return cached.image == null ? Instance.m_DummyItem : cached; } else { if (onlyCached || Downloading >= kMaxConcurrentDownloads) return Instance.m_DummyItem; cached = new CachedAssetStoreImage(); cached.image = null; cached.lastUsed = EditorApplication.timeSinceStartup; //Debug.Log("url is " + textureSize.ToString() + " " + url); } // Only set fetch time when there is not image in order to use it for // fading in the image when it becomes available if (cached.image == null) cached.lastFetched = EditorApplication.timeSinceStartup; cached.requestedWidth = textureSize; cached.label = label; AsyncHTTPClient client = null; client = SetupTextureDownload(cached, url, "previewSize-" + textureSize); ExpireCacheEntries(); if (newentry) CachedAssetStoreImages.Add(url, cached); client.Begin(); Instance.Requested++; return cached; } private static AsyncHTTPClient SetupTextureDownload(CachedAssetStoreImage cached, string url, string tag) { AsyncHTTPClient client = new AsyncHTTPClient(url); cached.client = client; client.tag = tag; client.doneCallback = delegate(IAsyncHTTPClient c) { // Debug.Log("Got image " + EditorApplication.timeSinceStartup.ToString()); cached.client = null; if (!client.IsSuccess()) { if (client.state != AsyncHTTPClient.State.ABORTED) { string err = "error " + client.text + " " + client.state + " '" + url + "'"; if (ObjectListArea.s_Debug) Debug.LogError(err); else System.Console.Write(err); } else { Instance.m_Aborted++; } return; } // In the case of refetch because of resize first destroy the current image if (cached.image != null) Object.DestroyImmediate(cached.image); cached.image = c.texture; s_NeedsRepaint = true; Instance.m_Success++; }; return client; } // Make room for image if needed (because of cache limits) private static void ExpireCacheEntries() { while (CacheFull) { string oldestUrl = null; CachedAssetStoreImage oldestEntry = null; foreach (KeyValuePair<string, CachedAssetStoreImage> kv in CachedAssetStoreImages) { if (oldestEntry == null || oldestEntry.lastUsed > kv.Value.lastUsed) { oldestEntry = kv.Value; oldestUrl = kv.Key; } } CachedAssetStoreImages.Remove(oldestUrl); Instance.m_CacheRemove++; if (oldestEntry == null) { Debug.LogError("Null entry found while removing cache entry"); break; } if (oldestEntry.client != null) { oldestEntry.client.Abort(); oldestEntry.client = null; } if (oldestEntry.image != null) Object.DestroyImmediate(oldestEntry.image); } } /* * When the new GUI system is is place this should render the label to the cached icon * to speed up rendering. For now we just scale the incoming image and render the label * separately */ private static CachedAssetStoreImage RenderEntry(CachedAssetStoreImage cached, GUIStyle labelStyle, GUIStyle iconStyle) { if (cached.label == null || cached.image == null) return cached; Texture2D tmp = cached.image; cached.image = new Texture2D(cached.requestedWidth, cached.requestedWidth, TextureFormat.RGB24, false, true); ScaleImage(cached.requestedWidth, cached.requestedWidth, tmp, cached.image, iconStyle); // Compressing creates artifacts on the images // cached.image.Compress(true); Object.DestroyImmediate(tmp); cached.label = null; Instance.m_ConvertedThisTick++; return cached; } /** Slow version of scaling an image but i doesn't * matter since it is not performance critical */ internal static void ScaleImage(int w, int h, Texture2D inimage, Texture2D outimage, GUIStyle bgStyle) { SavedRenderTargetState saved = new SavedRenderTargetState(); if (s_RenderTexture != null && (s_RenderTexture.width != w || s_RenderTexture.height != h)) { Object.DestroyImmediate(s_RenderTexture); s_RenderTexture = null; } if (s_RenderTexture == null) { s_RenderTexture = RenderTexture.GetTemporary(w, h, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); s_RenderTexture.hideFlags = HideFlags.HideAndDontSave; } RenderTexture r = s_RenderTexture; RenderTexture.active = r; Rect rect = new Rect(0, 0, w, h); EditorGUIUtility.SetRenderTextureNoViewport(r); GL.LoadOrtho(); GL.LoadPixelMatrix(0, w, h, 0); ShaderUtil.rawViewportRect = new Rect(0, 0, w, h); ShaderUtil.rawScissorRect = new Rect(0 , 0, w, h); GL.Clear(true, true, new Color(0, 0, 0, 0)); Rect blitRect = rect; if (inimage.width > inimage.height) { float newHeight = (float)blitRect.height * ((float)inimage.height / (float)inimage.width); blitRect.height = (int)newHeight; blitRect.y += (int)(newHeight * 0.5f); } else if (inimage.width < inimage.height) { float newWidth = (float)blitRect.width * ((float)inimage.width / (float)inimage.height); blitRect.width = (int)newWidth; blitRect.x += (int)(newWidth * 0.5f); } if (bgStyle != null && bgStyle.normal != null && bgStyle.normal.background != null) Graphics.DrawTexture(rect, bgStyle.normal.background); Graphics.DrawTexture(blitRect, inimage); outimage.ReadPixels(rect, 0, 0, false); outimage.Apply(); outimage.hideFlags = HideFlags.HideAndDontSave; saved.Restore(); } /* * Check if textures queued for download has finished downloading. * This call will reset the flag for finished downloads. */ public static bool CheckRepaint() { bool needsRepaint = s_NeedsRepaint; s_NeedsRepaint = false; return needsRepaint; } // Abort fetching all previews with the specified size public static void AbortSize(int size) { AsyncHTTPClient.AbortByTag("previewSize-" + size); // Mark any pending requests for that width in the cases as invalid // now that requests has been aborted. foreach (KeyValuePair<string, CachedAssetStoreImage> kv in AssetStorePreviewManager.CachedAssetStoreImages) { if (kv.Value.requestedWidth != size) continue; kv.Value.requestedWidth = -1; kv.Value.client = null; } } // Abort fetching all reviews that haven't been used since timestamp public static void AbortOlderThan(double timestamp) { foreach (KeyValuePair<string, CachedAssetStoreImage> kv in AssetStorePreviewManager.CachedAssetStoreImages) { CachedAssetStoreImage entry = kv.Value; if (entry.lastUsed >= timestamp || entry.client == null) continue; entry.requestedWidth = -1; entry.client.Abort(); entry.client = null; } // @TODO: Currently we know that AbortOlderThan is called exactly once each repaint. // Therefore this counter can be reset here. Should probably be moved to a // more intuitive location. Instance.m_ConvertedThisTick = 0; } } } // UnityEditor namespace
UnityCsReference/Editor/Mono/AssetStore/AssetStorePreviewManager.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetStore/AssetStorePreviewManager.cs", "repo_id": "UnityCsReference", "token_count": 7338 }
257
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEditor.Audio; using UnityEditor.Audio.UIElements; using UnityEditor.ShortcutManagement; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Audio; using UnityEngine.Scripting; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace UnityEditor; sealed class AudioContainerWindow : EditorWindow { /// <summary> /// The cached instance of the window, if it is open. /// </summary> internal static AudioContainerWindow Instance { get; private set; } internal readonly AudioContainerWindowState State = new(); /// <summary> /// Holds the added list elements in the list interaction callbacks. /// Only used locally in these methods, but it's a global member to avoid GC. /// </summary> readonly List<AudioContainerElement> m_AddedElements = new(); readonly string k_EmptyGuidString = Guid.Empty.ToString("N"); VisualElement m_ContainerRootVisualElement; VisualElement m_Day0RootVisualElement; // Preview section Label m_AssetNameLabel; Button m_PlayStopButton; VisualElement m_PlayStopButtonImage; Button m_SkipButton; VisualElement m_SkipButtonImage; // Volume section Slider m_VolumeSlider; AudioRandomRangeSliderTracker m_VolumeRandomRangeTracker; FloatField m_VolumeField; Button m_VolumeRandomizationButton; VisualElement m_VolumeRandomizationButtonImage; MinMaxSlider m_VolumeRandomizationRangeSlider; Vector2Field m_VolumeRandomizationRangeField; AudioLevelMeter m_Meter; // Pitch section Slider m_PitchSlider; AudioRandomRangeSliderTracker m_PitchRandomRangeTracker; FloatField m_PitchField; Button m_PitchRandomizationButton; VisualElement m_PitchRandomizationButtonImage; MinMaxSlider m_PitchRandomizationRangeSlider; Vector2Field m_PitchRandomizationRangeField; // Clip list section ListView m_ClipsListView; AudioContainerListDragAndDropManipulator m_DragManipulator; // Trigger and playback mode section RadioButtonGroup m_TriggerRadioButtonGroup; RadioButtonGroup m_PlaybackModeRadioButtonGroup; IntegerField m_AvoidRepeatingLastField; // Automatic trigger section RadioButtonGroup m_AutomaticTriggerModeRadioButtonGroup; Slider m_TimeSlider; AudioRandomRangeSliderTracker m_TimeRandomRangeTracker; FloatField m_TimeField; Button m_TimeRandomizationButton; VisualElement m_TimeRandomizationButtonImage; MinMaxSlider m_TimeRandomizationRangeSlider; Vector2Field m_TimeRandomizationRangeField; RadioButtonGroup m_LoopRadioButtonGroup; IntegerField m_CountField; Button m_CountRandomizationButton; VisualElement m_CountRandomizationButtonImage; MinMaxSlider m_CountRandomizationRangeSlider; Vector2Field m_CountRandomizationRangeField; Label m_AutomaticTriggerModeLabel; Label m_LoopLabel; // Shared icon references Texture2D m_DiceIconOff; Texture2D m_DiceIconOn; bool m_IsVisible; bool m_IsSubscribedToGUICallbacksAndEvents; bool m_IsInitializing; bool m_Day0ElementsInitialized; bool m_ContainerElementsInitialized; bool m_ClipFieldProgressBarsAreCleared = true; /// <summary> /// Holds the previous state of the list elements for undo/delete housekeeping /// </summary> List<AudioContainerElement> m_CachedElements = new(); [RequiredByNativeCode] internal static void CreateAudioRandomContainerWindow() { var window = GetWindow<AudioContainerWindow>(); window.Show(); } static void OnCreateButtonClicked() { ProjectWindowUtil.CreateAudioRandomContainer(); } void OnEnable() { Instance = this; m_DiceIconOff = EditorGUIUtility.IconContent("AudioRandomContainer On Icon").image as Texture2D; m_DiceIconOn = EditorGUIUtility.IconContent("AudioRandomContainer Icon").image as Texture2D; SetTitle(); } void OnDisable() { Instance = null; State.OnDestroy(); UnsubscribeFromGUICallbacksAndEvents(); m_IsInitializing = false; m_Day0ElementsInitialized = false; m_ContainerElementsInitialized = false; m_CachedElements.Clear(); m_AddedElements.Clear(); } void Update() { if (!m_IsVisible) return; if (State.IsPlayingOrPaused()) { UpdateClipFieldProgressBars(); } else if (!m_ClipFieldProgressBarsAreCleared) { ClearClipFieldProgressBars(); } if (m_Meter != null) { if (State.IsPlayingOrPaused()) { if (State != null) { m_Meter.Value = State.GetMeterValue(); } else { m_Meter.Value = -80.0f; } } else { if (m_Meter.Value != -80.0f) { m_Meter.Value = -80.0f; } } } } void SetTitle() { var titleString = "Audio Random Container"; if (State.IsDirty()) titleString += "*"; titleContent = new GUIContent(titleString) { image = m_DiceIconOff }; } void CreateGUI() { try { if (m_IsInitializing) return; m_IsInitializing = true; var root = rootVisualElement; if (root.childCount == 0) { var rootAsset = UIToolkitUtilities.LoadUxml("UXML/Audio/AudioRandomContainer.uxml"); Assert.IsNotNull(rootAsset); rootAsset.CloneTree(root); var styleSheet = UIToolkitUtilities.LoadStyleSheet("StyleSheets/Audio/AudioRandomContainer.uss"); Assert.IsNotNull(styleSheet); root.styleSheets.Add(styleSheet); root.Add(State.GetResourceTrackerElement()); m_ContainerRootVisualElement = UIToolkitUtilities.GetChildByName<ScrollView>(root, "ARC_ScrollView"); Assert.IsNotNull(m_ContainerRootVisualElement); m_Day0RootVisualElement = UIToolkitUtilities.GetChildByName<VisualElement>(root, "Day0"); Assert.IsNotNull(m_Day0RootVisualElement); } if (m_ContainerElementsInitialized) root.Unbind(); if (State.AudioContainer == null) { if (!m_Day0ElementsInitialized) { InitializeDay0Elements(); m_Day0ElementsInitialized = true; } m_Day0RootVisualElement.style.display = DisplayStyle.Flex; m_ContainerRootVisualElement.style.display = DisplayStyle.None; } else { if (!m_ContainerElementsInitialized) { InitializeContainerElements(); m_ContainerElementsInitialized = true; EditorApplication.update += OneTimeEditorApplicationUpdate; } if (!m_IsSubscribedToGUICallbacksAndEvents) SubscribeToGUICallbacksAndEvents(); BindAndTrackObjectAndProperties(); m_Day0RootVisualElement.style.display = DisplayStyle.None; m_ContainerRootVisualElement.style.display = DisplayStyle.Flex; m_ClipsListView.Rebuild(); // Force a list rebuild when the list has changed or it will not always render correctly due to a UI toolkit bug. } } finally { m_IsInitializing = false; } } bool IsDisplayingTarget() { return m_Day0RootVisualElement != null && m_Day0RootVisualElement.style.display == DisplayStyle.None && m_ContainerRootVisualElement != null && m_ContainerRootVisualElement.style.display == DisplayStyle.Flex; } void InitializeDay0Elements() { var createButtonLabel = UIToolkitUtilities.GetChildByName<Label>(m_Day0RootVisualElement, "CreateButtonLabel"); var createButton = UIToolkitUtilities.GetChildByName<Button>(m_Day0RootVisualElement, "CreateButton"); createButton.clicked += OnCreateButtonClicked; createButtonLabel.text = "Select an existing Audio Random Container asset in the project browser or create a new one using the button below."; } void InitializeContainerElements() { InitializePreviewElements(); InitializeVolumeElements(); InitializePitchElements(); InitializeClipListElements(); InitializeTriggerAndPlayModeElements(); InitializeAutomaticTriggerElements(); } void SubscribeToGUICallbacksAndEvents() { if (!m_ContainerElementsInitialized || m_IsSubscribedToGUICallbacksAndEvents) { return; } SubscribeToPreviewCallbacksAndEvents(); SubscribeToVolumeCallbacksAndEvents(); SubscribeToPitchCallbacksAndEvents(); SubscribeToClipListCallbacksAndEvents(); SubscribeToAutomaticTriggerCallbacksAndEvents(); SubscribeToTooltipCallbacksAndEvents(); m_IsSubscribedToGUICallbacksAndEvents = true; } void UnsubscribeFromGUICallbacksAndEvents() { if (!m_ContainerElementsInitialized || !m_IsSubscribedToGUICallbacksAndEvents) { return; } UnsubscribeFromPreviewCallbacksAndEvents(); UnsubscribeFromVolumeCallbacksAndEvents(); UnsubscribeFromPitchCallbacksAndEvents(); UnsubscribeFromClipListCallbacksAndEvents(); UnsubscribeFromAutomaticTriggerCallbacksAndEvents(); UnsubscribeFromTooltipCallbacksAndEvents(); m_IsSubscribedToGUICallbacksAndEvents = false; } void BindAndTrackObjectAndProperties() { m_ContainerRootVisualElement.TrackSerializedObjectValue(State.SerializedObject, OnSerializedObjectChanged); BindAndTrackPreviewProperties(); BindAndTrackVolumeProperties(); BindAndTrackPitchProperties(); BindAndTrackClipListProperties(); BindAndTrackTriggerAndPlayModeProperties(); BindAndTrackAutomaticTriggerProperties(); } void OnTargetChanged(object sender, EventArgs e) { SetTitle(); CreateGUI(); if (State.AudioContainer == null) m_CachedElements.Clear(); else m_CachedElements = State.AudioContainer.elements.ToList(); m_AddedElements.Clear(); } void OnSerializedObjectChanged(SerializedObject obj) { SetTitle(); } void OneTimeEditorApplicationUpdate() { // Setting this is a temp workaround for a UIToolKit bug // https://unity.slack.com/archives/C3414V4UV/p1681828689005249?thread_ts=1676901177.340799&cid=C3414V4UV m_ClipsListView.reorderable = true; m_ClipsListView.reorderMode = ListViewReorderMode.Animated; EditorApplication.update -= OneTimeEditorApplicationUpdate; } static void InsertUnitFieldForFloatField(VisualElement field, string unit) { var floatInput = UIToolkitUtilities.GetChildByName<VisualElement>(field, "unity-text-input"); var unitTextElement = new TextElement { name = "numeric-field-unit-label", text = unit }; floatInput.Add(unitTextElement); } #region Preview void InitializePreviewElements() { m_AssetNameLabel = UIToolkitUtilities.GetChildByName<Label>(m_ContainerRootVisualElement, "asset-name-label"); m_PlayStopButton = UIToolkitUtilities.GetChildByName<Button>(m_ContainerRootVisualElement, "play-button"); m_PlayStopButtonImage = UIToolkitUtilities.GetChildByName<VisualElement>(m_ContainerRootVisualElement, "play-button-image"); m_SkipButton = UIToolkitUtilities.GetChildByName<Button>(m_ContainerRootVisualElement, "skip-button"); m_SkipButtonImage = UIToolkitUtilities.GetChildByName<VisualElement>(m_ContainerRootVisualElement, "skip-button-image"); var skipIcon = UIToolkitUtilities.LoadIcon("Skip"); m_SkipButtonImage.style.backgroundImage = new StyleBackground(skipIcon); } void SubscribeToPreviewCallbacksAndEvents() { m_PlayStopButton.clicked += OnPlayStopButtonClicked; m_SkipButton.clicked += OnSkipButtonClicked; } void UnsubscribeFromPreviewCallbacksAndEvents() { if (m_PlayStopButton != null) m_PlayStopButton.clicked -= OnPlayStopButtonClicked; if (m_SkipButton != null) m_SkipButton.clicked -= OnSkipButtonClicked; } void BindAndTrackPreviewProperties() { UpdateTransportButtonStates(); m_AssetNameLabel.text = State.AudioContainer.name; } void OnPlayStopButtonClicked() { if (State.IsPlayingOrPaused()) { State.Stop(); ClearClipFieldProgressBars(); } else State.Play(); UpdateTransportButtonStates(); } void OnSkipButtonClicked() { if (State.IsPlayingOrPaused()) State.Skip(); } void UpdateTransportButtonStates() { var editorIsPaused = EditorApplication.isPaused; m_PlayStopButton?.SetEnabled(State.IsReadyToPlay() && !editorIsPaused); m_SkipButton?.SetEnabled(State.IsPlayingOrPaused() && State.AudioContainer.triggerMode == AudioRandomContainerTriggerMode.Automatic && !editorIsPaused); var image = State.IsPlayingOrPaused() ? UIToolkitUtilities.LoadIcon("Stop") : UIToolkitUtilities.LoadIcon("Play"); m_PlayStopButtonImage.style.backgroundImage = new StyleBackground(image); } void OnTransportStateChanged(object sender, EventArgs e) { UpdateTransportButtonStates(); } void EditorPauseStateChanged(object sender, EventArgs e) { UpdateTransportButtonStates(); } #endregion #region Volume void InitializeVolumeElements() { m_Meter = UIToolkitUtilities.GetChildByName<AudioLevelMeter>(m_ContainerRootVisualElement, "meter"); m_VolumeSlider = UIToolkitUtilities.GetChildByName<Slider>(m_ContainerRootVisualElement, "volume-slider"); m_VolumeRandomRangeTracker = AudioRandomRangeSliderTracker.Create(m_VolumeSlider, State.AudioContainer.volumeRandomizationRange); m_VolumeField = UIToolkitUtilities.GetChildByName<FloatField>(m_ContainerRootVisualElement, "volume-field"); m_VolumeRandomizationButton = UIToolkitUtilities.GetChildByName<Button>(m_ContainerRootVisualElement, "volume-randomization-button"); m_VolumeRandomizationButtonImage = UIToolkitUtilities.GetChildByName<VisualElement>(m_ContainerRootVisualElement, "volume-randomization-button-image"); m_VolumeRandomizationRangeSlider = UIToolkitUtilities.GetChildByName<MinMaxSlider>(m_ContainerRootVisualElement, "volume-randomization-range-slider"); m_VolumeRandomizationRangeField = UIToolkitUtilities.GetChildByName<Vector2Field>(m_ContainerRootVisualElement, "volume-randomization-range-field"); var volumeRandomizationMinField = UIToolkitUtilities.GetChildByName<FloatField>(m_VolumeRandomizationRangeField, "unity-x-input"); var volumeRandomizationMaxField = UIToolkitUtilities.GetChildByName<FloatField>(m_VolumeRandomizationRangeField, "unity-y-input"); m_VolumeField.formatString = "0.#"; InsertUnitFieldForFloatField(m_VolumeField, "dB"); m_VolumeField.isDelayed = true; volumeRandomizationMinField.isDelayed = true; volumeRandomizationMinField.label = ""; volumeRandomizationMinField.formatString = "0.#"; InsertUnitFieldForFloatField(volumeRandomizationMinField, "dB"); volumeRandomizationMaxField.isDelayed = true; volumeRandomizationMaxField.label = ""; volumeRandomizationMaxField.formatString = "0.#"; InsertUnitFieldForFloatField(volumeRandomizationMaxField, "dB"); } void SubscribeToVolumeCallbacksAndEvents() { m_VolumeRandomizationButton.clicked += OnVolumeRandomizationButtonClicked; m_VolumeSlider.RegisterValueChangedCallback(OnVolumeChanged); m_VolumeRandomizationRangeSlider.RegisterValueChangedCallback(OnVolumeRandomizationRangeChanged); m_VolumeRandomizationRangeField.RegisterValueChangedCallback(OnVolumeRandomizationRangeChanged); } void UnsubscribeFromVolumeCallbacksAndEvents() { if (m_VolumeRandomizationButton != null) m_VolumeRandomizationButton.clicked -= OnVolumeRandomizationButtonClicked; m_VolumeSlider?.UnregisterValueChangedCallback(OnVolumeChanged); m_VolumeRandomizationRangeSlider?.UnregisterValueChangedCallback(OnVolumeRandomizationRangeChanged); m_VolumeRandomizationRangeField?.UnregisterValueChangedCallback(OnVolumeRandomizationRangeChanged); } void BindAndTrackVolumeProperties() { var volumeProperty = State.SerializedObject.FindProperty("m_Volume"); var volumeRandomizationEnabledProperty = State.SerializedObject.FindProperty("m_VolumeRandomizationEnabled"); var volumeRandomizationRangeProperty = State.SerializedObject.FindProperty("m_VolumeRandomizationRange"); m_VolumeSlider.BindProperty(volumeProperty); m_VolumeField.BindProperty(volumeProperty); m_VolumeRandomizationRangeSlider.BindProperty(volumeRandomizationRangeProperty); m_VolumeRandomizationRangeField.BindProperty(volumeRandomizationRangeProperty); m_VolumeRandomizationButton.TrackPropertyValue(volumeRandomizationEnabledProperty, OnVolumeRandomizationEnabledChanged); OnVolumeRandomizationEnabledChanged(volumeRandomizationEnabledProperty); } void OnVolumeChanged(ChangeEvent<float> evt) { m_VolumeRandomRangeTracker.SetRange(State.AudioContainer.volumeRandomizationRange); } void OnVolumeRandomizationRangeChanged(ChangeEvent<Vector2> evt) { // Have to clamp immediately here to avoid UI jitter because the min-max slider cannot clamp before updating the property var newValue = evt.newValue; if (newValue.x > 0) newValue.x = 0; if (newValue.y < 0) newValue.y = 0; m_VolumeRandomRangeTracker.SetRange(newValue); } void OnVolumeRandomizationEnabledChanged(SerializedProperty property) { if (property.boolValue) { m_VolumeRandomizationButtonImage.style.backgroundImage = new StyleBackground(m_DiceIconOn); m_VolumeRandomizationRangeSlider.SetEnabled(true); m_VolumeRandomizationRangeField.SetEnabled(true); } else { m_VolumeRandomizationButtonImage.style.backgroundImage = new StyleBackground(m_DiceIconOff); m_VolumeRandomizationRangeSlider.SetEnabled(false); m_VolumeRandomizationRangeField.SetEnabled(false); } } void OnVolumeRandomizationButtonClicked() { var newButtonStateString = !State.AudioContainer.volumeRandomizationEnabled ? "Enabled" : "Disabled"; Undo.RecordObject(State.AudioContainer, $"Modified Volume Randomization {newButtonStateString} in {State.AudioContainer.name}"); State.AudioContainer.volumeRandomizationEnabled = !State.AudioContainer.volumeRandomizationEnabled; } #endregion #region Pitch void InitializePitchElements() { m_PitchSlider = UIToolkitUtilities.GetChildByName<Slider>(m_ContainerRootVisualElement, "pitch-slider"); m_PitchRandomRangeTracker = AudioRandomRangeSliderTracker.Create(m_PitchSlider, State.AudioContainer.pitchRandomizationRange); m_PitchField = UIToolkitUtilities.GetChildByName<FloatField>(m_ContainerRootVisualElement, "pitch-field"); m_PitchRandomizationButton = UIToolkitUtilities.GetChildByName<Button>(m_ContainerRootVisualElement, "pitch-randomization-button"); m_PitchRandomizationButtonImage = UIToolkitUtilities.GetChildByName<VisualElement>(m_ContainerRootVisualElement, "pitch-randomization-button-image"); m_PitchRandomizationRangeSlider = UIToolkitUtilities.GetChildByName<MinMaxSlider>(m_ContainerRootVisualElement, "pitch-randomization-range-slider"); m_PitchRandomizationRangeField = UIToolkitUtilities.GetChildByName<Vector2Field>(m_ContainerRootVisualElement, "pitch-randomization-range-field"); var pitchRandomizationMinField = UIToolkitUtilities.GetChildByName<FloatField>(m_PitchRandomizationRangeField, "unity-x-input"); var pitchRandomizationMaxField = UIToolkitUtilities.GetChildByName<FloatField>(m_PitchRandomizationRangeField, "unity-y-input"); m_PitchField.formatString = "0"; InsertUnitFieldForFloatField(m_PitchField, "ct"); m_PitchField.isDelayed = true; pitchRandomizationMinField.isDelayed = true; pitchRandomizationMinField.label = ""; pitchRandomizationMinField.formatString = "0"; InsertUnitFieldForFloatField(pitchRandomizationMinField, "ct"); pitchRandomizationMaxField.isDelayed = true; pitchRandomizationMaxField.label = ""; pitchRandomizationMaxField.formatString = "0"; InsertUnitFieldForFloatField(pitchRandomizationMaxField, "ct"); } void SubscribeToPitchCallbacksAndEvents() { m_PitchRandomizationButton.clicked += OnPitchRandomizationButtonClicked; m_PitchSlider.RegisterValueChangedCallback(OnPitchChanged); m_PitchRandomizationRangeSlider.RegisterValueChangedCallback(OnPitchRandomizationRangeChanged); m_PitchRandomizationRangeField.RegisterValueChangedCallback(OnPitchRandomizationRangeChanged); } void UnsubscribeFromPitchCallbacksAndEvents() { if (m_PitchRandomizationButton != null) m_PitchRandomizationButton.clicked -= OnPitchRandomizationButtonClicked; m_PitchSlider?.UnregisterValueChangedCallback(OnPitchChanged); m_PitchRandomizationRangeSlider?.UnregisterValueChangedCallback(OnPitchRandomizationRangeChanged); m_PitchRandomizationRangeField?.UnregisterValueChangedCallback(OnPitchRandomizationRangeChanged); } void BindAndTrackPitchProperties() { var pitchProperty = State.SerializedObject.FindProperty("m_Pitch"); var pitchRandomizationEnabledProperty = State.SerializedObject.FindProperty("m_PitchRandomizationEnabled"); var pitchRandomizationRangeProperty = State.SerializedObject.FindProperty("m_PitchRandomizationRange"); m_PitchSlider.BindProperty(pitchProperty); m_PitchField.BindProperty(pitchProperty); m_PitchRandomizationRangeSlider.BindProperty(pitchRandomizationRangeProperty); m_PitchRandomizationRangeField.BindProperty(pitchRandomizationRangeProperty); m_PitchRandomizationButton.TrackPropertyValue(pitchRandomizationEnabledProperty, OnPitchRandomizationEnabledChanged); OnPitchRandomizationEnabledChanged(pitchRandomizationEnabledProperty); } void OnPitchChanged(ChangeEvent<float> evt) { m_PitchRandomRangeTracker.SetRange(State.AudioContainer.pitchRandomizationRange); } void OnPitchRandomizationRangeChanged(ChangeEvent<Vector2> evt) { // Have to clamp immediately here to avoid UI jitter because the min-max slider cannot clamp before updating the property var newValue = evt.newValue; if (newValue.x > 0) newValue.x = 0; if (newValue.y < 0) newValue.y = 0; m_PitchRandomRangeTracker.SetRange(newValue); } void OnPitchRandomizationEnabledChanged(SerializedProperty property) { if (property.boolValue) { m_PitchRandomizationButtonImage.style.backgroundImage = new StyleBackground(m_DiceIconOn); m_PitchRandomizationRangeSlider.SetEnabled(true); m_PitchRandomizationRangeField.SetEnabled(true); } else { m_PitchRandomizationButtonImage.style.backgroundImage = new StyleBackground(m_DiceIconOff); m_PitchRandomizationRangeSlider.SetEnabled(false); m_PitchRandomizationRangeField.SetEnabled(false); } } void OnPitchRandomizationButtonClicked() { var newButtonStateString = !State.AudioContainer.pitchRandomizationEnabled ? "Enabled" : "Disabled"; Undo.RecordObject(State.AudioContainer, $"Modified Pitch Randomization {newButtonStateString} in {State.AudioContainer.name}"); State.AudioContainer.pitchRandomizationEnabled = !State.AudioContainer.pitchRandomizationEnabled; } #endregion #region ClipList void InitializeClipListElements() { m_ClipsListView = UIToolkitUtilities.GetChildByName<ListView>(m_ContainerRootVisualElement, "audio-clips-list-view"); m_ClipsListView.CreateDragAndDropController(); m_DragManipulator = new AudioContainerListDragAndDropManipulator(m_ContainerRootVisualElement); m_ClipsListView.fixedItemHeight = 24; } void SubscribeToClipListCallbacksAndEvents() { m_ClipsListView.itemsAdded += OnListItemsAdded; m_ClipsListView.itemsRemoved += OnListItemsRemoved; m_ClipsListView.itemIndexChanged += OnItemListIndexChanged; m_ClipsListView.makeItem = OnMakeListItem; m_ClipsListView.bindItem = OnBindListItem; // We need a no-op unbind callback to prevent the default implementation from being run. // See the comments in UUM-46918. m_ClipsListView.unbindItem = (elm, idx) => { }; m_DragManipulator.addAudioClipsDelegate += OnAudioClipDrag; } void UnsubscribeFromClipListCallbacksAndEvents() { if (m_ClipsListView != null) { m_ClipsListView.itemsAdded -= OnListItemsAdded; m_ClipsListView.itemsRemoved -= OnListItemsRemoved; m_ClipsListView.itemIndexChanged -= OnItemListIndexChanged; m_ClipsListView.makeItem = null; m_ClipsListView.bindItem = null; m_ClipsListView.unbindItem = null; } if (m_DragManipulator != null) m_DragManipulator.addAudioClipsDelegate -= OnAudioClipDrag; } void BindAndTrackClipListProperties() { var clipsProperty = State.SerializedObject.FindProperty("m_Elements"); m_ClipsListView.BindProperty(clipsProperty); m_ClipsListView.TrackPropertyValue(clipsProperty, OnAudioClipListChanged); } static void UpdateListElementName(Object element, Object clip = null) { AssetDatabase.TryGetGUIDAndLocalFileIdentifier(element, out var guid, out var localId); var name = clip == null ? nameof(AudioContainerElement) : clip.name; element.name = $"{name}_{{{localId}}}"; } static VisualElement OnMakeListItem() { var element = UIToolkitUtilities.LoadUxml("UXML/Audio/AudioContainerElement.uxml").Instantiate(); var volumeField = UIToolkitUtilities.GetChildByName<FloatField>(element, "volume-field"); InsertUnitFieldForFloatField(volumeField, "dB"); return element; } void OnBindListItem(VisualElement element, int index) { // There is currently a bug in UIToolkit where the reported index can be out of bounds after shrinking the list if (index > State.AudioContainer.elements.Length - 1) return; var enabledToggle = UIToolkitUtilities.GetChildByName<Toggle>(element, "enabled-toggle"); var audioClipField = UIToolkitUtilities.GetChildByName<AudioContainerElementClipField>(element, "audio-clip-field"); var volumeField = UIToolkitUtilities.GetChildByName<FloatField>(element, "volume-field"); volumeField.formatString = "0.#"; audioClipField.objectType = typeof(AudioClip); var listElement = State.AudioContainer.elements[index]; if (listElement == null) { Debug.LogError($"AudioContainerElement at index {index} is null. Please report using `Help > Report a Bug...`."); element.SetEnabled(false); return; } element.SetEnabled(true); audioClipField.RegisterCallback<DragPerformEvent>(OnListDragPerform); audioClipField.AssetElementInstanceID = listElement.GetInstanceID(); var serializedObject = new SerializedObject(listElement); var enabledProperty = serializedObject.FindProperty("m_Enabled"); var audioClipProperty = serializedObject.FindProperty("m_AudioClip"); var volumeProperty = serializedObject.FindProperty("m_Volume"); // Shouldn't be necessary to unbind here, but currently required to work around an exception // being thrown when calling TrackPropertyValue. See https://jira.unity3d.com/browse/UUM-46918 // Should be removed once this issue has been fixed. enabledToggle.Unbind(); audioClipField.Unbind(); volumeField.Unbind(); enabledToggle.BindProperty(enabledProperty); audioClipField.BindProperty(audioClipProperty); volumeField.BindProperty(volumeProperty); enabledToggle.TrackPropertyValue(enabledProperty, OnElementEnabledToggleChanged); audioClipField.TrackPropertyValue(audioClipProperty, OnElementAudioClipChanged); volumeField.TrackPropertyValue(volumeProperty, OnElementPropertyChanged); } static void OnListDragPerform(DragPerformEvent evt) { evt.StopPropagation(); } void OnElementAudioClipChanged(SerializedProperty property) { var element = property.serializedObject.targetObject as AudioContainerElement; Assert.IsNotNull(element); var clip = property.objectReferenceValue as AudioClip; UpdateListElementName(element, clip); OnElementPropertyChanged(property); UpdateTransportButtonStates(); State.AudioContainer.NotifyObservers(AudioRandomContainer.ChangeEventType.List); } void OnElementEnabledToggleChanged(SerializedProperty property) { OnElementPropertyChanged(property); UpdateTransportButtonStates(); // Changing a property on the ListElement subasset does not call CheckConsistency on the main Asset // So quickly flip the values to force an update. :( var last = State.AudioContainer.avoidRepeatingLast; State.AudioContainer.avoidRepeatingLast = -1; State.AudioContainer.avoidRepeatingLast = last; if (State.IsPlayingOrPaused()) State.AudioContainer.NotifyObservers(AudioRandomContainer.ChangeEventType.List); } void OnElementPropertyChanged(SerializedProperty property) { EditorUtility.SetDirty(State.AudioContainer); SetTitle(); } void OnListItemsAdded(IEnumerable<int> indices) { var indicesArray = indices as int[] ?? indices.ToArray(); var elements = State.AudioContainer.elements.ToList(); foreach (var index in indicesArray) { var element = new AudioContainerElement { hideFlags = HideFlags.HideInHierarchy }; AssetDatabase.AddObjectToAsset(element, State.AudioContainer); UpdateListElementName(element); elements[index] = element; m_AddedElements.Add(element); } State.AudioContainer.elements = elements.ToArray(); // Object creation undo recording needs to be done in a separate pass from the object property changes above foreach (var element in m_AddedElements) Undo.RegisterCreatedObjectUndo(element, "Create AudioContainerElement"); m_AddedElements.Clear(); var undoName = $"Add {nameof(AudioRandomContainer)} element"; if (indicesArray.Length > 1) { undoName = $"{undoName}s"; } Undo.SetCurrentGroupName(undoName); m_AddedElements.Clear(); } void OnListItemsRemoved(IEnumerable<int> indices) { var indicesArray = indices as int[] ?? indices.ToArray(); // Confusingly, this callback is sometimes invoked post-delete and sometimes pre-delete, // i.e. the AudioRandomContainer.elements property may or may not be updated at this time, // so we use the cached list to be sure we get the correct reference to the subasset to delete. foreach (var index in indicesArray) { if (m_CachedElements[index] != null) { AssetDatabase.RemoveObjectFromAsset(m_CachedElements[index]); Undo.DestroyObjectImmediate(m_CachedElements[index]); } } State.AudioContainer.NotifyObservers(AudioRandomContainer.ChangeEventType.List); var undoName = $"Remove {nameof(AudioRandomContainer)} element"; if (indicesArray.Length > 1) { undoName = $"{undoName}s"; } Undo.SetCurrentGroupName(undoName); } void OnItemListIndexChanged(int oldIndex, int newIndex) { Undo.SetCurrentGroupName($"Reorder {nameof(AudioRandomContainer)} list"); State.AudioContainer.NotifyObservers(AudioRandomContainer.ChangeEventType.List); } void OnAudioClipDrag(List<AudioClip> audioClips) { var undoName = $"Add {nameof(AudioRandomContainer)} element"; if (audioClips.Count > 1) undoName = $"{undoName}s"; Undo.RegisterCompleteObjectUndo(State.AudioContainer, undoName); var elements = State.AudioContainer.elements.ToList(); foreach (var audioClip in audioClips) { var element = new AudioContainerElement { audioClip = audioClip, hideFlags = HideFlags.HideInHierarchy }; AssetDatabase.AddObjectToAsset(element, State.AudioContainer); UpdateListElementName(element, audioClip); elements.Add(element); m_AddedElements.Add(element); } State.AudioContainer.elements = elements.ToArray(); // Object creation undo recording needs to be done in a separate pass from the object property changes above foreach (var element in m_AddedElements) Undo.RegisterCreatedObjectUndo(element, "Create AudioContainerElement"); m_AddedElements.Clear(); Undo.SetCurrentGroupName(undoName); } void OnAudioClipListChanged(SerializedProperty property) { // Do manual fixup of orphaned subassets after a possible undo of item removal // because the undo system does not play nice with RegisterCreatedObjectUndo. if (m_CachedElements.Count < State.AudioContainer.elements.Length) { var elements = State.AudioContainer.elements; foreach (var elm in elements) { AssetDatabase.TryGetGUIDAndLocalFileIdentifier(elm, out var guid, out var localId); // An empty asset GUID means the subasset has lost the reference // to the main asset after an undo of item removal, so re-add it manually. if (guid.Equals(k_EmptyGuidString)) AssetDatabase.AddObjectToAsset(elm, State.AudioContainer); } } // Update the cached list of elements m_CachedElements = State.AudioContainer.elements.ToList(); // Force a list rebuild when the list has changed or it will not always render correctly m_ClipsListView.Rebuild(); UpdateTransportButtonStates(); SetTitle(); } void UpdateClipFieldProgressBars() { var playables = State.GetActivePlayables(); if (playables == null) return; // Iterate over the ActivePlayables from the runtime and try and match them to the instance ID on the clip field. // if its a match, set the progress and remove the clip field to avoid overwriting the progress. var clipFields = m_ClipsListView.Query<AudioContainerElementClipField>().ToList(); // We need to sort the active playables as the runtime does not guarantee order Array.Sort(playables, (x, y) => x.settings.scheduledTime.CompareTo(y.settings.scheduledTime)); for (var i = playables.Length - 1; i >= 0; i--) { var playable = new AudioClipPlayable(playables[i].clipPlayableHandle); for (var j = clipFields.Count - 1; j >= 0; j--) { var field = clipFields[j]; if (field.AssetElementInstanceID == playables[i].settings.element.GetInstanceID()) { field.Progress = playable.GetClipPositionSec() / playable.GetClip().length; clipFields.RemoveAt(j); } } } // Any clip fields that did not have a match with active playables should have their progress set to 0. foreach (var field in clipFields) if (field.Progress != 0.0f) field.Progress = 0.0f; m_ClipFieldProgressBarsAreCleared = false; } void ClearClipFieldProgressBars() { if (m_ClipsListView == null) return; var clipFields = m_ClipsListView.Query<AudioContainerElementClipField>().ToList(); foreach (var field in clipFields) field.Progress = 0.0f; m_ClipFieldProgressBarsAreCleared = true; } #endregion #region TriggerAndPlaybackMode void InitializeTriggerAndPlayModeElements() { m_TriggerRadioButtonGroup = UIToolkitUtilities.GetChildByName<RadioButtonGroup>(m_ContainerRootVisualElement, "trigger-radio-button-group"); m_PlaybackModeRadioButtonGroup = UIToolkitUtilities.GetChildByName<RadioButtonGroup>(m_ContainerRootVisualElement, "playback-radio-button-group"); m_AvoidRepeatingLastField = UIToolkitUtilities.GetChildByName<IntegerField>(m_ContainerRootVisualElement, "avoid-repeating-last-field"); } void BindAndTrackTriggerAndPlayModeProperties() { var triggerProperty = State.SerializedObject.FindProperty("m_TriggerMode"); var playbackModeProperty = State.SerializedObject.FindProperty("m_PlaybackMode"); var avoidRepeatingLastProperty = State.SerializedObject.FindProperty("m_AvoidRepeatingLast"); m_TriggerRadioButtonGroup.BindProperty(triggerProperty); m_TriggerRadioButtonGroup.TrackPropertyValue(triggerProperty, OnTriggerChanged); m_PlaybackModeRadioButtonGroup.BindProperty(playbackModeProperty); m_PlaybackModeRadioButtonGroup.TrackPropertyValue(playbackModeProperty, OnPlaybackModeChanged); m_AvoidRepeatingLastField.BindProperty(avoidRepeatingLastProperty); OnTriggerChanged((AudioRandomContainerTriggerMode)m_TriggerRadioButtonGroup.value); OnPlaybackModeChanged(playbackModeProperty); } void OnTriggerChanged(SerializedProperty property) { OnTriggerChanged((AudioRandomContainerTriggerMode)property.intValue); } void OnTriggerChanged(AudioRandomContainerTriggerMode mode) { var enabled = mode == AudioRandomContainerTriggerMode.Automatic; m_AutomaticTriggerModeRadioButtonGroup.SetEnabled(enabled); m_TimeSlider.SetEnabled(enabled); m_TimeField.SetEnabled(enabled); m_LoopRadioButtonGroup.SetEnabled(enabled); m_AutomaticTriggerModeLabel.SetEnabled(enabled); m_LoopLabel.SetEnabled(enabled); m_TimeRandomizationButton.SetEnabled(enabled); m_CountRandomizationButton.SetEnabled(enabled); var loopProperty = State.SerializedObject.FindProperty("m_LoopMode"); OnLoopChanged(loopProperty); var timeRandomizationEnabledProperty = State.SerializedObject.FindProperty("m_AutomaticTriggerTimeRandomizationEnabled"); OnTimeRandomizationEnabledChanged(timeRandomizationEnabledProperty); } void OnPlaybackModeChanged(SerializedProperty property) { m_AvoidRepeatingLastField.SetEnabled(property.intValue == (int)AudioRandomContainerPlaybackMode.Random); } #endregion #region AutomaticTrigger void InitializeAutomaticTriggerElements() { m_AutomaticTriggerModeRadioButtonGroup = UIToolkitUtilities.GetChildByName<RadioButtonGroup>(m_ContainerRootVisualElement, "trigger-mode-radio-button-group"); m_TimeSlider = UIToolkitUtilities.GetChildByName<Slider>(m_ContainerRootVisualElement, "time-slider"); m_TimeRandomRangeTracker = AudioRandomRangeSliderTracker.Create(m_TimeSlider, State.AudioContainer.automaticTriggerTimeRandomizationRange); m_TimeField = UIToolkitUtilities.GetChildByName<FloatField>(m_ContainerRootVisualElement, "time-field"); m_TimeRandomizationButton = UIToolkitUtilities.GetChildByName<Button>(m_ContainerRootVisualElement, "time-randomization-button"); m_TimeRandomizationButtonImage = UIToolkitUtilities.GetChildByName<VisualElement>(m_ContainerRootVisualElement, "time-randomization-button-image"); m_TimeRandomizationRangeSlider = UIToolkitUtilities.GetChildByName<MinMaxSlider>(m_ContainerRootVisualElement, "time-randomization-range-slider"); m_TimeRandomizationRangeField = UIToolkitUtilities.GetChildByName<Vector2Field>(m_ContainerRootVisualElement, "time-randomization-range-field"); var timeRandomizationMinField = UIToolkitUtilities.GetChildByName<FloatField>(m_TimeRandomizationRangeField, "unity-x-input"); var timeRandomizationMaxField = UIToolkitUtilities.GetChildByName<FloatField>(m_TimeRandomizationRangeField, "unity-y-input"); m_LoopRadioButtonGroup = UIToolkitUtilities.GetChildByName<RadioButtonGroup>(m_ContainerRootVisualElement, "loop-radio-button-group"); m_CountField = UIToolkitUtilities.GetChildByName<IntegerField>(m_ContainerRootVisualElement, "count-field"); m_CountRandomizationButton = UIToolkitUtilities.GetChildByName<Button>(m_ContainerRootVisualElement, "count-randomization-button"); m_CountRandomizationButtonImage = UIToolkitUtilities.GetChildByName<VisualElement>(m_ContainerRootVisualElement, "count-randomization-button-image"); m_CountRandomizationRangeSlider = UIToolkitUtilities.GetChildByName<MinMaxSlider>(m_ContainerRootVisualElement, "count-randomization-range-slider"); m_CountRandomizationRangeField = UIToolkitUtilities.GetChildByName<Vector2Field>(m_ContainerRootVisualElement, "count-randomization-range-field"); var countRandomizationMinField = UIToolkitUtilities.GetChildByName<FloatField>(m_CountRandomizationRangeField, "unity-x-input"); var countRandomizationMaxField = UIToolkitUtilities.GetChildByName<FloatField>(m_CountRandomizationRangeField, "unity-y-input"); m_AutomaticTriggerModeLabel = UIToolkitUtilities.GetChildByName<Label>(m_ContainerRootVisualElement, "automatic-trigger-mode-label"); m_LoopLabel = UIToolkitUtilities.GetChildByName<Label>(m_ContainerRootVisualElement, "loop-label"); m_TimeField.formatString = "0.00"; InsertUnitFieldForFloatField(m_TimeField, "s"); m_TimeField.isDelayed = true; timeRandomizationMinField.isDelayed = true; timeRandomizationMinField.label = ""; timeRandomizationMinField.formatString = "0.#"; InsertUnitFieldForFloatField(timeRandomizationMinField, "s"); timeRandomizationMaxField.isDelayed = true; timeRandomizationMaxField.label = ""; timeRandomizationMaxField.formatString = "0.#"; InsertUnitFieldForFloatField(timeRandomizationMaxField, "s"); m_CountField.formatString = "0.#"; m_CountField.isDelayed = true; countRandomizationMinField.isDelayed = true; countRandomizationMinField.label = ""; countRandomizationMaxField.isDelayed = true; countRandomizationMaxField.label = ""; } void SubscribeToAutomaticTriggerCallbacksAndEvents() { m_TimeRandomizationButton.clicked += OnTimeRandomizationButtonClicked; m_CountRandomizationButton.clicked += OnCountRandomizationButtonClicked; m_TimeSlider.RegisterValueChangedCallback(OnTimeChanged); m_TimeRandomizationRangeField.RegisterValueChangedCallback(OnTimeRandomizationRangeChanged); m_TimeRandomizationRangeSlider.RegisterValueChangedCallback(OnTimeRandomizationRangeChanged); } void UnsubscribeFromAutomaticTriggerCallbacksAndEvents() { if (m_TimeRandomizationButton != null) m_TimeRandomizationButton.clicked -= OnTimeRandomizationButtonClicked; if (m_CountRandomizationButton != null) m_CountRandomizationButton.clicked -= OnCountRandomizationButtonClicked; m_TimeSlider?.UnregisterValueChangedCallback(OnTimeChanged); m_TimeRandomizationRangeField?.UnregisterValueChangedCallback(OnTimeRandomizationRangeChanged); m_TimeRandomizationRangeSlider?.UnregisterValueChangedCallback(OnTimeRandomizationRangeChanged); } void SubscribeToTooltipCallbacksAndEvents() { rootVisualElement.RegisterCallback<TooltipEvent>(ShowTooltip, TrickleDown.TrickleDown); } void UnsubscribeFromTooltipCallbacksAndEvents() { rootVisualElement.UnregisterCallback<TooltipEvent>(ShowTooltip); } void ShowTooltip(TooltipEvent evt) { var name = (evt.target as VisualElement).name; if (name == "play-button" || name == "play-button-image") { var mode = State.IsPlayingOrPaused() ? "Stop" : "Play"; var shortcut = ShortcutManager.instance.GetShortcutBinding("Audio/Play-stop Audio Random Container"); if (shortcut.Equals(ShortcutBinding.empty)) { evt.tooltip = mode; } else { evt.tooltip = mode + " (" + shortcut + ")"; } evt.rect = (evt.target as VisualElement).worldBound; evt.StopPropagation(); } } void BindAndTrackAutomaticTriggerProperties() { var automaticTriggerModeProperty = State.SerializedObject.FindProperty("m_AutomaticTriggerMode"); var triggerTimeProperty = State.SerializedObject.FindProperty("m_AutomaticTriggerTime"); var triggerTimeRandomizationEnabledProperty = State.SerializedObject.FindProperty("m_AutomaticTriggerTimeRandomizationEnabled"); var triggerTimeRandomizationRangeProperty = State.SerializedObject.FindProperty("m_AutomaticTriggerTimeRandomizationRange"); var loopModeProperty = State.SerializedObject.FindProperty("m_LoopMode"); var loopCountProperty = State.SerializedObject.FindProperty("m_LoopCount"); var loopCountRandomizationEnabledProperty = State.SerializedObject.FindProperty("m_LoopCountRandomizationEnabled"); var loopCountRandomizationRangeProperty = State.SerializedObject.FindProperty("m_LoopCountRandomizationRange"); m_AutomaticTriggerModeRadioButtonGroup.BindProperty(automaticTriggerModeProperty); m_TimeSlider.BindProperty(triggerTimeProperty); m_TimeField.BindProperty(triggerTimeProperty); m_TimeRandomizationRangeSlider.BindProperty(triggerTimeRandomizationRangeProperty); m_TimeRandomizationRangeField.BindProperty(triggerTimeRandomizationRangeProperty); m_LoopRadioButtonGroup.BindProperty(loopModeProperty); m_CountField.BindProperty(loopCountProperty); m_CountRandomizationRangeSlider.BindProperty(loopCountRandomizationRangeProperty); m_CountRandomizationRangeField.BindProperty(loopCountRandomizationRangeProperty); m_TimeRandomizationButton.TrackPropertyValue(triggerTimeRandomizationEnabledProperty, OnTimeRandomizationEnabledChanged); m_LoopRadioButtonGroup.TrackPropertyValue(loopModeProperty, OnLoopChanged); m_CountRandomizationButton.TrackPropertyValue(loopCountRandomizationEnabledProperty, OnCountRandomizationEnabledChanged); OnTimeRandomizationEnabledChanged(triggerTimeRandomizationEnabledProperty); OnLoopChanged(loopModeProperty); OnCountRandomizationEnabledChanged(loopCountRandomizationEnabledProperty); } void OnTimeChanged(ChangeEvent<float> evt) { m_TimeRandomRangeTracker.SetRange(State.AudioContainer.automaticTriggerTimeRandomizationRange); } void OnTimeRandomizationRangeChanged(ChangeEvent<Vector2> evt) { // Have to clamp immediately here to avoid UI jitter because the min-max slider cannot clamp before updating the property var newValue = evt.newValue; if (newValue.x > 0) newValue.x = 0; if (newValue.y < 0) newValue.y = 0; m_TimeRandomRangeTracker.SetRange(newValue); } void OnTimeRandomizationEnabledChanged(SerializedProperty property) { if (property.boolValue && State.AudioContainer.triggerMode == AudioRandomContainerTriggerMode.Automatic) { m_TimeRandomizationButtonImage.style.backgroundImage = new StyleBackground(m_DiceIconOn); m_TimeRandomizationRangeSlider.SetEnabled(true); m_TimeRandomizationRangeField.SetEnabled(true); } else { m_TimeRandomizationButtonImage.style.backgroundImage = new StyleBackground(m_DiceIconOff); m_TimeRandomizationRangeSlider.SetEnabled(false); m_TimeRandomizationRangeField.SetEnabled(false); } } void OnTimeRandomizationButtonClicked() { var newButtonStateString = !State.AudioContainer.automaticTriggerTimeRandomizationEnabled ? "Enabled" : "Disabled"; Undo.RecordObject(State.AudioContainer, $"Modified Time Randomization {newButtonStateString} in {State.AudioContainer.name}"); State.AudioContainer.automaticTriggerTimeRandomizationEnabled = !State.AudioContainer.automaticTriggerTimeRandomizationEnabled; } void OnLoopChanged(SerializedProperty property) { var enabled = property.intValue != (int)AudioRandomContainerLoopMode.Infinite && State.AudioContainer.triggerMode == AudioRandomContainerTriggerMode.Automatic; m_CountField.SetEnabled(enabled); m_CountRandomizationRangeSlider.SetEnabled(enabled); m_CountRandomizationRangeField.SetEnabled(enabled); m_CountRandomizationButton.SetEnabled(enabled); var countRandomizationEnabledProperty = State.SerializedObject.FindProperty("m_LoopCountRandomizationEnabled"); OnCountRandomizationEnabledChanged(countRandomizationEnabledProperty); } void OnCountRandomizationEnabledChanged(SerializedProperty property) { if (property.boolValue && State.AudioContainer.loopMode != AudioRandomContainerLoopMode.Infinite && State.AudioContainer.triggerMode == AudioRandomContainerTriggerMode.Automatic) { m_CountRandomizationButtonImage.style.backgroundImage = new StyleBackground(m_DiceIconOn); m_CountRandomizationRangeSlider.SetEnabled(true); m_CountRandomizationRangeField.SetEnabled(true); } else { m_CountRandomizationButtonImage.style.backgroundImage = new StyleBackground(m_DiceIconOff); m_CountRandomizationRangeSlider.SetEnabled(false); m_CountRandomizationRangeField.SetEnabled(false); } } void OnCountRandomizationButtonClicked() { var newButtonStateString = !State.AudioContainer.loopCountRandomizationEnabled ? "Enabled" : "Disabled"; Undo.RecordObject(State.AudioContainer, $"Modified Count Randomization {newButtonStateString} in {State.AudioContainer.name}"); State.AudioContainer.loopCountRandomizationEnabled = !State.AudioContainer.loopCountRandomizationEnabled; } #endregion #region GlobalEditorCallbackHandlers void OnBecameVisible() { m_IsVisible = true; State.TargetChanged += OnTargetChanged; State.TransportStateChanged += OnTransportStateChanged; State.EditorPauseStateChanged += EditorPauseStateChanged; State.Resume(); if (!m_IsSubscribedToGUICallbacksAndEvents && m_ContainerElementsInitialized && IsDisplayingTarget()) { SubscribeToGUICallbacksAndEvents(); } } void OnBecameInvisible() { m_IsVisible = false; State.TargetChanged -= OnTargetChanged; State.TransportStateChanged -= OnTransportStateChanged; State.EditorPauseStateChanged -= EditorPauseStateChanged; State.Suspend(); if (m_IsSubscribedToGUICallbacksAndEvents && m_ContainerElementsInitialized && IsDisplayingTarget()) { UnsubscribeFromGUICallbacksAndEvents(); } EditorApplication.update -= OneTimeEditorApplicationUpdate; ClearClipFieldProgressBars(); } void OnWillSaveAssets(IEnumerable<string> paths) { // If there is no target we are in day 0 state. if (State.AudioContainer == null) return; foreach (var path in paths) if (path == State.TargetPath) { SetTitle(); return; } } void OnAssetsImported(IEnumerable<string> paths) { // If there is no target we are in day 0 state. if (State.AudioContainer == null) return; foreach (var path in paths) if (path == State.TargetPath) { State.SerializedObject.Update(); OnTargetChanged(this, EventArgs.Empty); return; } } void OnAssetsDeleted(IEnumerable<string> paths) { // The target reference will already be invalid at this point if it's been deleted. if (State.AudioContainer != null) return; // ...but we still have the target path available for the check. foreach (var path in paths) if (path == State.TargetPath) { State.Reset(); OnTargetChanged(this, EventArgs.Empty); return; } } class AudioContainerModificationProcessor : AssetModificationProcessor { /// <summary> /// Handles save of AudioRandomContainer assets /// and relays it to AudioContainerWindow, /// removing the asterisk in the window tab label. /// </summary> static string[] OnWillSaveAssets(string[] paths) { if (Instance != null) Instance.OnWillSaveAssets(paths); return paths; } } class AudioContainerPostProcessor : AssetPostprocessor { /// <summary> /// Handles import and deletion of AudioRandomContainer assets /// and relays it to AudioContainerWindow, /// refreshing or clearing the window content. /// </summary> static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { if (Instance == null) return; if (importedAssets.Length > 0) Instance.OnAssetsImported(importedAssets); if (deletedAssets.Length > 0) Instance.OnAssetsDeleted(deletedAssets); } } #endregion #region Shortcuts [Shortcut("Audio/Play-stop Audio Random Container", typeof(AudioContainerWindow), KeyCode.P, ShortcutModifiers.Alt)] static void Preview(ShortcutArguments args) { var audioContainerWindow = focusedWindow as AudioContainerWindow; if (audioContainerWindow != null && audioContainerWindow.IsDisplayingTarget()) { audioContainerWindow.OnPlayStopButtonClicked(); } } #endregion }
UnityCsReference/Editor/Mono/Audio/AudioContainerWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/AudioContainerWindow.cs", "repo_id": "UnityCsReference", "token_count": 21344 }
258
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor.Audio; namespace UnityEditor { internal static class AudioMixerEffectGUI { const string kAudioSliderFloatFormat = "F2"; const string kExposedParameterUnicodeChar = " \u2794"; public static void EffectHeader(string text) { GUILayout.Label(text, styles.headerStyle); } public static bool Slider(GUIContent label, ref float value, float displayScale, float displayExponent, string unit, float leftValue, float rightValue, AudioMixerController controller, AudioParameterPath path, params GUILayoutOption[] options) { EditorGUI.BeginChangeCheck(); float oldNumberWidth = EditorGUIUtility.fieldWidth; string origFormat = EditorGUI.kFloatFieldFormatString; bool exposed = controller.ContainsExposedParameter(path.parameter); float displayValue = value * displayScale; EditorGUIUtility.fieldWidth = 70f; // do not go over 70 because then sliders will not be shown when inspector has minimal width EditorGUI.kFloatFieldFormatString = kAudioSliderFloatFormat; EditorGUI.s_UnitString = unit; try { GUIContent content = label; if (exposed) content = GUIContent.Temp(label.text + kExposedParameterUnicodeChar, label.tooltip); displayValue = EditorGUILayout.PowerSlider(content, displayValue, leftValue * displayScale, rightValue * displayScale, displayExponent, options); } finally { EditorGUI.s_UnitString = null; EditorGUI.kFloatFieldFormatString = origFormat; EditorGUIUtility.fieldWidth = oldNumberWidth; } if (Event.current.type == EventType.ContextClick) { Rect wholeSlider = GUILayoutUtility.topLevel.GetLast(); if (wholeSlider.Contains(Event.current.mousePosition)) { Event.current.Use(); GenericMenu pm = new GenericMenu(); if (!exposed) pm.AddItem(EditorGUIUtility.TrTextContent("Expose '" + path.ResolveStringPath(false) + "' to script"), false, ExposePopupCallback, new ExposedParamContext(controller, path)); else pm.AddItem(EditorGUIUtility.TrTextContent("Unexpose"), false, UnexposePopupCallback, new ExposedParamContext(controller, path)); ParameterTransitionType existingType; bool overrideExists = controller.TargetSnapshot.GetTransitionTypeOverride(path.parameter, out existingType); System.Diagnostics.Debug.Assert(!overrideExists || existingType == ParameterTransitionType.Lerp); pm.AddSeparator(string.Empty); pm.AddItem(EditorGUIUtility.TrTextContent("Linear Snapshot Transition"), existingType == ParameterTransitionType.Lerp, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Lerp)); pm.AddItem(EditorGUIUtility.TrTextContent("Smoothstep Snapshot Transition"), existingType == ParameterTransitionType.Smoothstep, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Smoothstep)); pm.AddItem(EditorGUIUtility.TrTextContent("Squared Snapshot Transition"), existingType == ParameterTransitionType.Squared, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Squared)); pm.AddItem(EditorGUIUtility.TrTextContent("SquareRoot Snapshot Transition"), existingType == ParameterTransitionType.SquareRoot, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.SquareRoot)); pm.AddItem(EditorGUIUtility.TrTextContent("BrickwallStart Snapshot Transition"), existingType == ParameterTransitionType.BrickwallStart, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.BrickwallStart)); pm.AddItem(EditorGUIUtility.TrTextContent("BrickwallEnd Snapshot Transition"), existingType == ParameterTransitionType.BrickwallEnd, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.BrickwallEnd)); pm.AddItem(EditorGUIUtility.TrTextContent("Attenuation Snapshot Transition"), existingType == ParameterTransitionType.Attenuation, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Attenuation)); pm.AddSeparator(string.Empty); pm.ShowAsContext(); } } if (EditorGUI.EndChangeCheck()) { value = displayValue / displayScale; return true; } return false; } private class ExposedParamContext { public ExposedParamContext(AudioMixerController controller, AudioParameterPath path) { this.controller = controller; this.path = path; } public AudioMixerController controller; public AudioParameterPath path; } public static void ExposePopupCallback(object obj) { ExposedParamContext context = (ExposedParamContext)obj; Undo.RecordObject(context.controller, "Expose Mixer Parameter"); context.controller.AddExposedParameter(context.path); AudioMixerUtility.RepaintAudioMixerAndInspectors(); } public static void UnexposePopupCallback(object obj) { ExposedParamContext context = (ExposedParamContext)obj; Undo.RecordObject(context.controller, "Unexpose Mixer Parameter"); context.controller.RemoveExposedParameter(context.path.parameter); AudioMixerUtility.RepaintAudioMixerAndInspectors(); } private class ParameterTransitionOverrideContext { public ParameterTransitionOverrideContext(AudioMixerController controller, GUID parameter, ParameterTransitionType type) { this.controller = controller; this.parameter = parameter; this.type = type; } public AudioMixerController controller; public GUID parameter; public ParameterTransitionType type; } private class ParameterTransitionOverrideRemoveContext { public ParameterTransitionOverrideRemoveContext(AudioMixerController controller, GUID parameter) { this.controller = controller; this.parameter = parameter; } public AudioMixerController controller; public GUID parameter; } public static void ParameterTransitionOverrideCallback(object obj) { ParameterTransitionOverrideContext context = (ParameterTransitionOverrideContext)obj; Undo.RecordObject(context.controller, "Change Parameter Transition Type"); if (context.type == ParameterTransitionType.Lerp) context.controller.TargetSnapshot.ClearTransitionTypeOverride(context.parameter); else context.controller.TargetSnapshot.SetTransitionTypeOverride(context.parameter, context.type); } public static bool PopupButton(GUIContent label, GUIContent buttonContent, GUIStyle style, out Rect buttonRect, params GUILayoutOption[] options) { if (label != null) { Rect r = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, EditorGUI.kSingleLineHeight, style, options); int id = EditorGUIUtility.GetControlID("EditorPopup".GetHashCode(), FocusType.Keyboard, r); buttonRect = EditorGUI.PrefixLabel(r, id, label); } else { Rect r = GUILayoutUtility.GetRect(buttonContent, style, options); buttonRect = r; } return EditorGUI.DropdownButton(buttonRect, buttonContent, FocusType.Passive, style); } private static AudioMixerDrawUtils.Styles styles { get { return AudioMixerDrawUtils.styles; } } } }
UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerEffectGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerEffectGUI.cs", "repo_id": "UnityCsReference", "token_count": 3625 }
259
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Audio.UIElements; class AudioRandomRangeSliderTracker : VisualElement { [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new AudioRandomRangeSliderTracker(); } static readonly CustomStyleProperty<Color> s_TrackerColorProperty = new("--tracker-color"); Slider m_ParentSlider; Vector2 m_Range = Vector2.zero; Color m_TrackerColor; static void CustomStylesResolved(CustomStyleResolvedEvent evt) { var element = (AudioRandomRangeSliderTracker)evt.currentTarget; element.UpdateCustomStyles(); } void UpdateCustomStyles() { if (customStyle.TryGetValue(s_TrackerColorProperty, out var trackerColor)) { m_TrackerColor = trackerColor; } } internal static AudioRandomRangeSliderTracker Create(Slider parentSlider, Vector2 range) { var dragContainer = UIToolkitUtilities.GetChildByName<VisualElement>(parentSlider, "unity-drag-container"); var rangeTrackerAsset = UIToolkitUtilities.LoadUxml("UXML/Audio/AudioRandomRangeSliderTracker.uxml"); var baseTracker = UIToolkitUtilities.GetChildByName<VisualElement>(parentSlider, "unity-tracker"); var insertionIndex = dragContainer.IndexOf(baseTracker) + 1; var templateContainer = rangeTrackerAsset.Instantiate(); dragContainer.Insert(insertionIndex, templateContainer); var rangeTracker = UIToolkitUtilities.GetChildAtIndex<AudioRandomRangeSliderTracker>(templateContainer, 0); rangeTracker.SetRange(range); rangeTracker.m_ParentSlider = parentSlider; rangeTracker.generateVisualContent += GenerateVisualContent; rangeTracker.RegisterCallback<CustomStyleResolvedEvent>(CustomStylesResolved); rangeTracker.m_ParentSlider.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged); return rangeTracker; } internal void SetRange(Vector2 range) { m_Range = range; MarkDirtyRepaint(); } static void OnGeometryChanged(GeometryChangedEvent evt) { var sliderTracker = UIToolkitUtilities.GetChildByClassName<AudioRandomRangeSliderTracker>(evt.elementTarget, "unity-audio-random-range-slider-tracker"); sliderTracker.SetRange(sliderTracker.m_Range); } // Maps 'x' from the range '[x_min; x_max]' to the range '[y_min; y_max]'. static float Map(float x, float x_min, float x_max, float y_min, float y_max) { var a = (x_max - x) / (x_max - x_min); var b = (x - x_min) / (x_max - x_min); return a * y_min + b * y_max; } static void GenerateVisualContent(MeshGenerationContext context) { var painter2D = context.painter2D; var sliderTracker = context.visualElement as AudioRandomRangeSliderTracker; var range = sliderTracker.m_Range; var parentSlider = sliderTracker.m_ParentSlider; var contentRect = context.visualElement.contentRect; // Offset the range so it is centered around the parent slider's current value. range.x += parentSlider.value; range.y += parentSlider.value; // Map the range from the slider value range (e.g. dB) to the horizontal span of the content-rect (px). var left = Map(range.y, parentSlider.lowValue, parentSlider.highValue, contentRect.xMin, contentRect.xMax); var right = Map(range.x, parentSlider.lowValue, parentSlider.highValue, contentRect.xMin, contentRect.xMax); // Clamp the mapped range so that it lies within the boundaries of the content-rect. left = Mathf.Clamp(left, contentRect.xMin, contentRect.xMax); right = Mathf.Clamp(right, contentRect.xMin, contentRect.xMax); // Draw the tracker. painter2D.fillColor = sliderTracker.m_TrackerColor; painter2D.BeginPath(); painter2D.MoveTo(new Vector2(left, contentRect.yMin)); painter2D.LineTo(new Vector2(right, contentRect.yMin)); painter2D.LineTo(new Vector2(right, contentRect.yMax)); painter2D.LineTo(new Vector2(left, contentRect.yMax)); painter2D.ClosePath(); painter2D.Fill(); } }
UnityCsReference/Editor/Mono/Audio/UIElements/AudioRandomRangeSliderTracker.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/UIElements/AudioRandomRangeSliderTracker.cs", "repo_id": "UnityCsReference", "token_count": 1645 }
260
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NiceIO; using UnityEditor.Build.Reporting; using UnityEngine; using UnityEditor; using UnityEditor.Build; using UnityEditor.Modules; using UnityEditor.UnityLinker; using Debug = UnityEngine.Debug; namespace UnityEditorInternal { internal class AssemblyStripper { static List<NPath> ProcessBuildPipelineGenerateAdditionalLinkXmlFiles(BuildPostProcessArgs args) { var results = new List<NPath>(); var processors = BuildPipelineInterfaces.processors.unityLinkerProcessors; if (processors == null) return results; NPath stagingAreaManaged = $"{args.stagingAreaData}/Managed"; var pipelineData = new UnityLinkerBuildPipelineData(args.target, stagingAreaManaged.MakeAbsolute().ToString()); foreach (var processor in processors) { results.Add(processor.GenerateAdditionalLinkXmlFile(args.report, pipelineData)); var processorType = processor.GetType(); // The OnBeforeRun and OnAfterRun methods are no longer supported. We warn if the project uses them. // But since these were interface methods, any project using GenerateAdditionalLinkXmlFile also had to // implement these. So we only want to warn if the methods are not empty. // // To detect if we should consider a method as "empty" we check if the method body has more than 2 bytes. // An empty method is 1 byte (ret), or 2 bytes in debug mode (nop, ret). The assumption is that there is // no viable void method with side effects having only 2 bytes. var onBeforeRun = processorType.GetMethod("OnBeforeRun"); if (onBeforeRun != null && onBeforeRun.GetMethodBody().GetILAsByteArray().Length > 2) Debug.LogWarning($"{processorType} has a non-empty OnBeforeRun method, but IUnityLinkerProcessor.OnBeforeRun is no longer supported."); var onAfterRun = processorType.GetMethod("OnAfterRun"); if (onAfterRun != null && onAfterRun.GetMethodBody().GetILAsByteArray().Length > 2) Debug.LogWarning($"{processorType} has a non-empty OnAfterRun method, but IUnityLinkerProcessor.OnAfterRun is no longer supported."); } return results; } internal static IEnumerable<NPath> GetUserBlacklistFiles() { return Directory.GetFiles("Assets", "link.xml", SearchOption.AllDirectories) .Select(s => Path.Combine(Directory.GetCurrentDirectory(), s)) .ToNPaths(); } public static string[] GetLinkXmlFiles(BuildPostProcessArgs args, NPath linkerInputDirectory) { var linkXmlFiles = new List<NPath>(); if (args.usedClassRegistry != null) { var buildFiles = args.report.GetFiles(); linkXmlFiles.Add(WriteMethodsToPreserveBlackList(args.usedClassRegistry, linkerInputDirectory)); linkXmlFiles.Add(WriteTypesInScenesBlacklist(args.usedClassRegistry, linkerInputDirectory, buildFiles)); linkXmlFiles.Add(WriteSerializedTypesBlacklist(args.usedClassRegistry, linkerInputDirectory, buildFiles)); } linkXmlFiles.AddRange(ProcessBuildPipelineGenerateAdditionalLinkXmlFiles(args)); linkXmlFiles.AddRange(GetUserBlacklistFiles()); var isMonoBackend = PlayerSettings.GetScriptingBackend(NamedBuildTarget.FromActiveSettings(args.target)) == ScriptingImplementation.Mono2x; if (isMonoBackend) { // The old Mono assembly stripper uses per-platform link.xml files if available. Apply these here. var buildToolsDirectory = BuildPipeline.GetBuildToolsDirectory(args.target); if (!string.IsNullOrEmpty(buildToolsDirectory)) { var platformDescriptor = Path.Combine(buildToolsDirectory, "link.xml"); if (File.Exists(platformDescriptor)) linkXmlFiles.Add(platformDescriptor); } } return linkXmlFiles .Where(p => p?.FileExists() ?? false) .Select(p => p.MakeAbsolute().ToString()) .ToArray(); } static bool BuildFileMatchesAssembly(BuildFile file, string assemblyName) { return file.path.ToNPath().FileNameWithoutExtension == assemblyName && (file.role == "ManagedLibrary" || file.role == "DependentManagedLibrary" || file.role == "ManagedEngineAPI"); } private static NPath WriteTypesInScenesBlacklist(RuntimeClassRegistry rcr, NPath linkerInputDirectory, BuildFile[] buildFiles) { var items = rcr.GetAllManagedTypesInScenes(); var sb = new StringBuilder(); sb.AppendLine("<linker>"); foreach (var assemblyTypePair in items.OrderBy(t => t.Key)) { // Some how stuff for assemblies that will not be in the build make it into UsedTypePerUserAssembly such as // ex: [UnityEditor.TestRunner.dll] UnityEditor.TestTools.TestRunner.TestListCacheData // // Filter anything out where the assembly doesn't exist so that UnityLinker can be strict about preservations in link xml files var filename = assemblyTypePair.Key.ToNPath().FileNameWithoutExtension; if (buildFiles.All(file => !BuildFileMatchesAssembly(file, filename))) continue; sb.AppendLine($"\t<assembly fullname=\"{filename}\">"); foreach (var type in assemblyTypePair.Value.OrderBy(s => s)) { sb.AppendLine($"\t\t<type fullname=\"{type}\" preserve=\"nothing\"/>"); } sb.AppendLine("\t</assembly>"); } sb.AppendLine("</linker>"); var path = linkerInputDirectory.Combine("TypesInScenes.xml"); path.WriteAllText(sb.ToString()); return path; } private static NPath WriteSerializedTypesBlacklist(RuntimeClassRegistry rcr, NPath linkerInputDirectory, BuildFile[] buildFiles) { var items = rcr.GetAllSerializedClassesAsString(); var oneOrMoreItemsWritten = false; var sb = new StringBuilder(); sb.AppendLine("<linker>"); foreach (var assemblyTypePair in items.OrderBy(t => t.Key)) { // Filter anything out where the assembly doesn't exist so that UnityLinker can be strict about preservations in link xml files if (buildFiles.All(file => !BuildFileMatchesAssembly(file, assemblyTypePair.Key))) continue; sb.AppendLine($"\t<assembly fullname=\"{assemblyTypePair.Key}\">"); foreach (var type in assemblyTypePair.Value.OrderBy(s => s)) { oneOrMoreItemsWritten = true; sb.AppendLine($"\t\t<type fullname=\"{type}\" preserve=\"nothing\" serialized=\"true\"/>"); } sb.AppendLine("\t</assembly>"); } sb.AppendLine("</linker>"); // Avoid writing empty files if (!oneOrMoreItemsWritten) return null; var path = linkerInputDirectory.Combine("SerializedTypes.xml"); path.WriteAllText(sb.ToString()); return path; } private static UnityType s_GameManagerTypeInfo = null; internal static UnityType GameManagerTypeInfo { get { if (s_GameManagerTypeInfo == null) { UnityType result = UnityType.FindTypeByName("GameManager"); if (result == null) throw new ArgumentException(string.Format("Could not map typename '{0}' to type info ({1})", "GameManager", "initializing code stripping utils")); s_GameManagerTypeInfo = result; } return s_GameManagerTypeInfo; } } internal static void UpdateBuildReport(LinkerToEditorData dataFromLinker, StrippingInfo strippingInfo) { foreach (var moduleInfo in dataFromLinker.report.modules) { strippingInfo.AddModule(moduleInfo.name); foreach (var moduleDependency in moduleInfo.dependencies) { strippingInfo.RegisterDependency(StrippingInfo.ModuleName(moduleInfo.name), moduleDependency.name); if (!string.IsNullOrEmpty(moduleDependency.icon)) strippingInfo.SetIcon(moduleDependency.name, moduleDependency.icon); // Hacky way to match the existing behavior if (moduleDependency.name == "UnityConnectSettings") strippingInfo.RegisterDependency(moduleDependency.name, "Required by UnityAnalytics"); foreach (var scene in moduleDependency.scenes) { strippingInfo.RegisterDependency(moduleDependency.name, scene); var klass = UnityType.FindTypeByName(moduleDependency.name); if (klass != null && !klass.IsDerivedFrom(GameManagerTypeInfo)) { if (scene.EndsWith(".unity")) strippingInfo.SetIcon(scene, "class/SceneAsset"); else strippingInfo.SetIcon(scene, "class/AssetBundle"); } } } } } internal static LinkerToEditorData ReadLinkerToEditorData(string outputDirectory) { var dataPath = Path.Combine(outputDirectory, "UnityLinkerToEditorData.json"); var contents = File.ReadAllText(dataPath); var data = JsonUtility.FromJson<LinkerToEditorData>(contents); return data; } public static string WriteEditorData(BuildPostProcessArgs args, NPath linkerInputDirectory) { CollectIncludedAndExcludedModules(out var forceIncludeModules, out var forceExcludeModules); var editorToLinkerData = new EditorToLinkerData { typesInScenes = GetTypesInScenesInformation(args.report, args.usedClassRegistry) .OrderBy(data => data.fullManagedTypeName ?? data.nativeClass) .ToArray(), allNativeTypes = CollectNativeTypeData().ToArray(), forceIncludeModules = forceIncludeModules.ToArray(), forceExcludeModules = forceExcludeModules.ToArray() }; var path = linkerInputDirectory.Combine("EditorToUnityLinkerData.json"); File.WriteAllText(path.ToString(), JsonUtility.ToJson(editorToLinkerData, true)); return path.MakeAbsolute().ToString(); } static List<EditorToLinkerData.TypeInSceneData> GetTypesInScenesInformation(BuildReport report, RuntimeClassRegistry rcr) { var items = new List<EditorToLinkerData.TypeInSceneData>(); foreach (var nativeClass in rcr.GetAllNativeClassesIncludingManagersAsString()) { var unityType = UnityType.FindTypeByName(nativeClass); var managedName = RuntimeClassMetadataUtils.ScriptingWrapperTypeNameForNativeID(unityType.persistentTypeID); var usedInScenes = rcr.GetScenesForClass(unityType.persistentTypeID)?.OrderBy(p => p); bool noManagedType = unityType.persistentTypeID != 0 && managedName == "UnityEngine.Object"; var information = new EditorToLinkerData.TypeInSceneData( noManagedType ? null : "UnityEngine.dll", noManagedType ? null : managedName, nativeClass, unityType.module, usedInScenes != null ? usedInScenes.ToArray() : null); items.Add(information); } var buildFiles = report.GetFiles(); foreach (var userAssembly in rcr.UsedTypePerUserAssembly) { // Some how stuff for assemblies that will not be in the build make it into UsedTypePerUserAssembly such as // ex: [UnityEditor.TestRunner.dll] UnityEditor.TestTools.TestRunner.TestListCacheData // // Filter anything out where the assembly doesn't exist so that UnityLinker can be strict about being able to find // all of the types that are reported as being in the scene. var filename = userAssembly.Key.ToNPath().FileNameWithoutExtension; if (buildFiles.All(file => !BuildFileMatchesAssembly(file, filename))) continue; foreach (var type in userAssembly.Value) items.Add(new EditorToLinkerData.TypeInSceneData(userAssembly.Key, type, null, null, null)); } return items; } static List<EditorToLinkerData.NativeTypeData> CollectNativeTypeData() { var items = new List<EditorToLinkerData.NativeTypeData>(); foreach (var unityType in UnityType.GetTypes()) { items.Add(new EditorToLinkerData.NativeTypeData { name = unityType.name, qualifiedName = unityType.qualifiedName, nativeNamespace = unityType.hasNativeNamespace ? unityType.nativeNamespace : null, module = unityType.module, baseName = unityType.baseClass != null ? unityType.baseClass.name : null, baseModule = unityType.baseClass != null ? unityType.baseClass.module : null, }); } return items; } static void CollectIncludedAndExcludedModules(out List<string> forceInclude, out List<string> forceExclude) { forceInclude = new List<string>(); forceExclude = new List<string>(); // Apply manual stripping overrides foreach (var module in ModuleMetadata.GetModuleNames()) { var includeSetting = ModuleMetadata.GetModuleIncludeSettingForModule(module); if (includeSetting == ModuleIncludeSetting.ForceInclude) forceInclude.Add(module); else if (includeSetting == ModuleIncludeSetting.ForceExclude) forceExclude.Add(module); } } private static NPath WriteMethodsToPreserveBlackList(RuntimeClassRegistry rcr, NPath linkerInputDirectory) { var contents = GetMethodPreserveBlacklistContents(rcr); if (contents == null) return null; var methodPreserveBlackList = linkerInputDirectory.Combine("MethodsToPreserve.xml"); methodPreserveBlackList.WriteAllText(contents); return methodPreserveBlackList; } private static string GetMethodPreserveBlacklistContents(RuntimeClassRegistry rcr) { if (rcr.GetMethodsToPreserve().Count == 0) return null; var sb = new StringBuilder(); sb.AppendLine("<linker>"); var groupedByAssembly = rcr.GetMethodsToPreserve().GroupBy(m => m.assembly); foreach (var assembly in groupedByAssembly.OrderBy(a => a.Key)) { var assemblyName = assembly.Key; sb.AppendLine(string.Format("\t<assembly fullname=\"{0}\" ignoreIfMissing=\"1\">", assemblyName)); var groupedByType = assembly.GroupBy(m => m.fullTypeName); foreach (var type in groupedByType.OrderBy(t => t.Key)) { sb.AppendLine(string.Format("\t\t<type fullname=\"{0}\">", type.Key)); foreach (var method in type.OrderBy(m => m.methodName)) sb.AppendLine(string.Format("\t\t\t<method name=\"{0}\"/>", method.methodName)); sb.AppendLine("\t\t</type>"); } sb.AppendLine("\t</assembly>"); } sb.AppendLine("</linker>"); return sb.ToString(); } } }
UnityCsReference/Editor/Mono/BuildPipeline/AssemblyStripper.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/BuildPipeline/AssemblyStripper.cs", "repo_id": "UnityCsReference", "token_count": 7715 }
261