text stringlengths 7 35.3M | id stringlengths 11 185 | metadata dict | __index_level_0__ int64 0 2.14k |
|---|---|---|---|
fileFormatVersion: 2
guid: 2c141d6067781964fb40dd63bdc2cc5a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Settings/IgnoreAsmdef/Model/Client/Ignore.asmdef.DISABLED.meta/0 | {
"file_path": "ET/Unity/Assets/Settings/IgnoreAsmdef/Model/Client/Ignore.asmdef.DISABLED.meta",
"repo_id": "ET",
"token_count": 63
} | 199 |
{
"MonoBehaviour": {
"Version": 4,
"EnableBurstCompilation": true,
"EnableOptimisations": true,
"EnableSafetyChecks": false,
"EnableDebugInAllBuilds": false,
"EnableArmv9SecurityFeatures": false,
"CpuMinTargetX32": 0,
"CpuMaxTargetX32": 0,
"CpuMinTargetX64": 0,
"CpuMaxTargetX64": 0,
"OptimizeFor": 0
}
}
| ET/Unity/ProjectSettings/BurstAotSettings_iOS.json/0 | {
"file_path": "ET/Unity/ProjectSettings/BurstAotSettings_iOS.json",
"repo_id": "ET",
"token_count": 156
} | 200 |
#!/bin/sh
#
# To enable this hook, copy/symlink this file to ".git/hooks/pre-commit".
# mklink .git\hooks\pre-commit ..\..\BuildTools\pre-commit
set -eu
DOTNET_FORMAT_VERSION=6.2.315104
DOTNET_PATH="$LOCALAPPDATA/ICSharpCode/ILSpy/dotnet-format-$DOTNET_FORMAT_VERSION"
if [ ! -d "$DOTNET_PATH" ]; then
dotnet tool install --tool-path "$DOTNET_PATH" dotnet-format --version "$DOTNET_FORMAT_VERSION" --add-source "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet6/nuget/v3/index.json"
fi
"$DOTNET_PATH/dotnet-format.exe" --version
if git diff --quiet --ignore-submodules; then
"$DOTNET_PATH/dotnet-format.exe" whitespace --no-restore --verbosity detailed ILSpy.sln
git add -u -- \*\*.cs
else
exec "$DOTNET_PATH/dotnet-format.exe" whitespace --verify-no-changes --no-restore --verbosity detailed ILSpy.sln
fi
| ILSpy/BuildTools/pre-commit/0 | {
"file_path": "ILSpy/BuildTools/pre-commit",
"repo_id": "ILSpy",
"token_count": 328
} | 201 |
/*
Copyright (c) 2015 Ki
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace ICSharpCode.BamlDecompiler.Xaml
{
internal class XamlExtension
{
public XamlType ExtensionType { get; }
public object[] Initializer { get; set; }
public IDictionary<string, object> NamedArguments { get; }
public XamlExtension(XamlType type)
{
ExtensionType = type;
NamedArguments = new Dictionary<string, object>();
}
static void WriteObject(StringBuilder sb, XamlContext ctx, XElement ctxElement, object value)
{
if (value is XamlExtension)
sb.Append(((XamlExtension)value).ToString(ctx, ctxElement));
else
sb.Append(value.ToString());
}
public string ToString(XamlContext ctx, XElement ctxElement)
{
var sb = new StringBuilder();
sb.Append('{');
var typeName = ctx.ToString(ctxElement, ExtensionType);
if (typeName.EndsWith("Extension"))
sb.Append(typeName.Substring(0, typeName.Length - 9));
else
sb.Append(typeName);
bool comma = false;
if (Initializer != null && Initializer.Length > 0)
{
sb.Append(' ');
for (int i = 0; i < Initializer.Length; i++)
{
if (comma)
sb.Append(", ");
WriteObject(sb, ctx, ctxElement, Initializer[i]);
comma = true;
}
}
if (NamedArguments.Count > 0)
{
foreach (var kvp in NamedArguments)
{
if (comma)
sb.Append(", ");
else
{
sb.Append(' ');
comma = true;
}
sb.AppendFormat("{0}=", kvp.Key);
WriteObject(sb, ctx, ctxElement, kvp.Value);
}
}
sb.Append('}');
return sb.ToString();
}
}
} | ILSpy/ICSharpCode.BamlDecompiler/Xaml/XamlExtension.cs/0 | {
"file_path": "ILSpy/ICSharpCode.BamlDecompiler/Xaml/XamlExtension.cs",
"repo_id": "ILSpy",
"token_count": 1000
} | 202 |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<RootNamespace>ICSharpCode.Decompiler.PowerShell</RootNamespace>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PowerShellStandard.Library" />
<PackageReference Include="Mono.Cecil" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\ICSharpCode.ILSpyX\PdbProvider\MonoCecilDebugInfoProvider.cs" Link="MonoCecilDebugInfoProvider.cs" />
<Compile Include="..\ICSharpCode.ILSpyX\PdbProvider\PortableDebugInfoProvider.cs" Link="PortableDebugInfoProvider.cs" />
<Compile Include="..\ICSharpCode.ILSpyX\PdbProvider\DebugInfoUtils.cs" Link="DebugInfoUtils.cs" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Condition=" '$(OS)' == 'Windows_NT' " Command="powershell -Command "Copy-Item $(ProjectDir)manifest.psd1 $(TargetDir)$(TargetName).psd1"" />
<Exec Condition=" '$(OS)' != 'Windows_NT' " Command="pwsh -Command "Copy-Item $(ProjectDir)manifest.psd1 $(TargetDir)$(TargetName).psd1"" />
</Target>
</Project>
| ILSpy/ICSharpCode.Decompiler.PowerShell/ICSharpCode.Decompiler.PowerShell.csproj/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.PowerShell/ICSharpCode.Decompiler.PowerShell.csproj",
"repo_id": "ILSpy",
"token_count": 508
} | 203 |
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<IsPackable>false</IsPackable>
<StartupObject>AutoGeneratedProgram</StartupObject>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<NoWarn>1701;1702;1705,67,169,1058,728,1720,649,168,251,660,661,675;1998;162;8632;626;8618;8714;8602</NoWarn>
<GenerateAssemblyVersionAttribute>False</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>False</GenerateAssemblyFileVersionAttribute>
<GenerateAssemblyInformationalVersionAttribute>False</GenerateAssemblyInformationalVersionAttribute>
<EnableDefaultItems>false</EnableDefaultItems>
<AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects>
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<DebugType>pdbonly</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>TRACE;DEBUG;ROSLYN;NET60;CS60;CS70;CS71;CS72;CS73;CS80;CS90;CS100</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DefineConstants>TRACE;ROSLYN;NET60;CS60;CS70;CS71;CS72;CS73;CS80;CS90;CS100</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DiffLib" />
<PackageReference Include="CliWrap" />
<PackageReference Include="NuGet.Protocol" />
<PackageReference Include="System.Collections.Immutable" />
<PackageReference Include="System.Reflection.Metadata" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic" />
<PackageReference Include="Microsoft.DiaSymReader.Converter.Xml" />
<PackageReference Include="Microsoft.DiaSymReader" />
<PackageReference Include="Microsoft.DiaSymReader.Native" />
<PackageReference Include="NUnit3TestAdapter" />
<PackageReference Include="coverlet.collector" />
<PackageReference Include="NUnit" />
<PackageReference Include="FluentAssertions" />
<PackageReference Include="JunitXml.TestLogger" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="System.Memory" />
<PackageReference Include="Mono.Cecil" />
<PackageReference Include="Microsoft.NETCore.ILAsm" />
<PackageReference Include="Microsoft.NETCore.ILDAsm" />
<PackageReference Include="System.Resources.Extensions" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.ILSpyX\ICSharpCode.ILSpyX.csproj" />
<ProjectReference Include="..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="TestCases\Correctness\Jmp.il" />
<None Include="TestCases\Correctness\StackTests.il" />
<None Include="TestCases\Correctness\StackTypes.il" />
<None Include="TestCases\Correctness\Uninit.vb" />
<None Include="TestCases\Disassembler\Pretty\InterfaceImplAttributes.il" />
<None Include="TestCases\Disassembler\Pretty\SortMembers.expected.il" />
<None Include="TestCases\Disassembler\Pretty\SortMembers.il" />
<None Include="TestCases\ILPretty\GuessAccessors.cs" />
<None Include="TestCases\ILPretty\GuessAccessors.il" />
<None Include="TestCases\ILPretty\Issue2260SwitchString.il" />
<None Include="TestCases\ILPretty\UnknownTypes.cs" />
<None Include="TestCases\ILPretty\UnknownTypes.il" />
<None Include="TestCases\ILPretty\EvalOrder.cs" />
<None Include="TestCases\ILPretty\EvalOrder.il" />
<None Include="TestCases\ILPretty\CallIndirect.il" />
<None Include="TestCases\ILPretty\Issue1454.il" />
<None Include="TestCases\ILPretty\Issue1681.il" />
<None Include="TestCases\ILPretty\Issue1922.il" />
<None Include="TestCases\ILPretty\Issue1918.il" />
<None Include="TestCases\ILPretty\Issue2104.il" />
<None Include="TestCases\ILPretty\WeirdEnums.il" />
<None Include="TestCases\ILPretty\ConstantBlobs.il" />
<None Include="TestCases\ILPretty\CS1xSwitch_Debug.il" />
<None Include="TestCases\ILPretty\CS1xSwitch_Release.il" />
<None Include="TestCases\ILPretty\Issue1157.il" />
<None Include="TestCases\ILPretty\Issue684.cs" />
<None Include="TestCases\ILPretty\Issue684.il" />
<None Include="TestCases\ILPretty\FSharpLoops.fs" />
<None Include="TestCases\ILPretty\FSharpLoops_Debug.il" />
<None Include="TestCases\ILPretty\FSharpLoops_Release.il" />
<None Include="TestCases\ILPretty\FSharpUsing.fs" />
<None Include="TestCases\ILPretty\FSharpUsing_Debug.il" />
<None Include="TestCases\ILPretty\DirectCallToExplicitInterfaceImpl.il" />
<None Include="TestCases\ILPretty\FSharpUsing_Release.il" />
<None Include="TestCases\Correctness\BitNot.il" />
<None Include="TestCases\Correctness\Readme.txt" />
</ItemGroup>
<ItemGroup>
<Compile Include="DisassemblerPrettyTestRunner.cs" />
<Compile Include="Helpers\RoslynToolset.cs" />
<Compile Include="Output\InsertParenthesesVisitorTests.cs" />
<Compile Include="ProjectDecompiler\TargetFrameworkTests.cs" />
<Compile Include="TestAssemblyResolver.cs" />
<Compile Include="Util\ResourceReaderWriterTests.cs" />
<None Include="TestCases\VBPretty\VBAutomaticEvents.vb" />
<Compile Include="TestCases\VBPretty\VBAutomaticEvents.cs" />
<Compile Include="TestCases\VBPretty\VBNonGenericForEach.cs" />
<None Include="TestCases\VBPretty\VBNonGenericForEach.vb" />
<Compile Include="TestCases\VBPretty\YieldReturn.cs" />
<None Include="TestCases\VBPretty\YieldReturn.vb" />
<Compile Include="TypeSystem\ReflectionHelperTests.cs" />
<None Include="TestCases\Pretty\MetadataAttributes.cs" />
<None Include="TestCases\Correctness\ComInterop.cs" />
<Compile Include="TestCases\Correctness\DeconstructionTests.cs" />
<Compile Include="TestCases\Correctness\DynamicTests.cs" />
<Compile Include="TestCases\Correctness\StringConcat.cs" />
<None Include="TestCases\Pretty\StaticAbstractInterfaceMembers.cs" />
<Compile Include="TestCases\Pretty\Structs.cs" />
<None Include="TestCases\Pretty\FileScopedNamespaces.cs" />
<Compile Include="TestCases\Pretty\PatternMatching.cs" />
<None Include="TestCases\Ugly\NoPropertiesAndEvents.Expected.cs" />
<Compile Include="TestCases\Ugly\NoPropertiesAndEvents.cs" />
<None Include="TestCases\Pretty\CovariantReturns.cs" />
<Compile Include="TestCases\VBPretty\VBPropertiesTest.cs" />
<None Include="TestCases\ILPretty\Issue2260SwitchString.cs" />
<None Include="TestCases\Pretty\Records.cs" />
<Compile Include="TestCases\VBPretty\Issue2192.cs" />
<Compile Include="Util\FileUtilityTests.cs" />
<None Include="TestCases\Pretty\FunctionPointers.cs" />
<None Include="TestCases\Pretty\CS9_ExtensionGetEnumerator.cs" />
<None Include="TestCases\Pretty\UsingVariables.cs" />
<None Include="TestCases\Pretty\AsyncForeach.cs" />
<Compile Include="TestCases\Pretty\DeconstructionTests.cs" />
<Compile Include="TestCases\ILPretty\Issue2104.cs" />
<Compile Include="TestCases\Pretty\SwitchExpressions.cs" />
<None Include="TestCases\Pretty\NativeInts.cs" />
<None Include="TestCases\ILPretty\CallIndirect.cs" />
<Compile Include="TestCases\ILPretty\Issue1681.cs" />
<Compile Include="TestCases\Ugly\AggressiveScalarReplacementOfAggregates.cs" />
<None Include="TestCases\Ugly\AggressiveScalarReplacementOfAggregates.Expected.cs" />
<None Include="TestCases\Pretty\IndexRangeTest.cs" />
<None Include="TestCases\ILPretty\Issue1918.cs" />
<Compile Include="TestCases\ILPretty\Issue1922.cs" />
<Compile Include="TestCases\Ugly\NoLocalFunctions.cs" />
<Compile Include="TestCases\VBPretty\Issue1906.cs" />
<Compile Include="TestCases\VBPretty\Select.cs" />
<None Include="TestCases\ILPretty\WeirdEnums.cs" />
<Compile Include="TestCases\ILPretty\ConstantBlobs.cs" />
<Compile Include="TestCases\Pretty\AsyncStreams.cs" />
<Compile Include="TestCases\Pretty\AsyncUsing.cs" />
<Compile Include="TestCases\Pretty\OutVariables.cs" />
<Compile Include="TestCases\Pretty\CustomTaskType.cs" />
<None Include="TestCases\Ugly\NoForEachStatement.Expected.cs" />
<Compile Include="TestCases\Ugly\NoForEachStatement.cs" />
<None Include="TestCases\Ugly\NoExtensionMethods.Expected.cs" />
<Compile Include="TestCases\Ugly\NoExtensionMethods.cs" />
<None Include="TestCases\VBPretty\Issue1906.vb" />
<None Include="TestCases\VBPretty\Issue2192.vb" />
<None Include="TestCases\VBPretty\Select.vb" />
<None Include="TestCases\VBPretty\VBCompoundAssign.cs" />
<Compile Include="TestCases\Pretty\ThrowExpressions.cs" />
<None Include="TestCases\ILPretty\Issue1145.cs" />
<Compile Include="TestCases\ILPretty\Issue1157.cs" />
<None Include="TestCases\ILPretty\Unsafe.cs" />
<None Include="TestCases\ILPretty\CS1xSwitch_Debug.cs" />
<None Include="TestCases\ILPretty\CS1xSwitch_Release.cs" />
<None Include="TestCases\ILPretty\DirectCallToExplicitInterfaceImpl.cs" />
<Compile Include="TestCases\ILPretty\Issue1389.cs" />
<Compile Include="TestCases\ILPretty\Issue1454.cs" />
<Compile Include="TestCases\Pretty\Discards.cs" />
<Compile Include="TestCases\Pretty\MultidimensionalArray.cs" />
<Compile Include="Output\CSharpAmbienceTests.cs" />
<Compile Include="Semantics\ConversionTests.cs" />
<Compile Include="Semantics\ExplicitConversionTest.cs" />
<Compile Include="Semantics\OverloadResolutionTests.cs" />
<Compile Include="DataFlowTest.cs" />
<Compile Include="TestCases\Pretty\LocalFunctions.cs" />
<Compile Include="TestCases\ILPretty\Issue1256.cs" />
<Compile Include="TestCases\ILPretty\Issue1323.cs" />
<Compile Include="TestCases\Pretty\CustomAttributes2.cs" />
<Compile Include="TestCases\Pretty\EnumTests.cs" />
<Compile Include="TestCases\Pretty\UserDefinedConversions.cs" />
<None Include="TestCases\ILPretty\Unsafe.il" />
<None Include="TestCases\Pretty\NullableRefTypes.cs" />
<Compile Include="TestCases\Pretty\TypeMemberTests.cs" />
<Compile Include="TestCases\Pretty\ValueTypes.cs" />
<None Include="TestCases\ILPretty\Issue1389.il" />
<None Include="TestCases\ILPretty\SequenceOfNestedIfs.cs" />
<Compile Include="TestCases\Pretty\ConstructorInitializers.cs" />
<None Include="TestCases\ILPretty\SequenceOfNestedIfs.il" />
<None Include="TestCases\Pretty\AsyncMain.cs" />
<None Include="TestCases\ILPretty\Issue1325.cs" />
<Compile Include="TestCases\Pretty\ConstantsTests.cs" />
<Compile Include="TestCases\Pretty\CS73_StackAllocInitializers.cs" />
<Compile Include="TestCases\Pretty\OptionalArguments.cs" />
<Compile Include="TestCases\Pretty\CustomShortCircuitOperators.cs" />
<Compile Include="TestCases\Pretty\ReduceNesting.cs" />
<Compile Include="TestCases\Pretty\InterfaceTests.cs" />
<Compile Include="TestCases\Pretty\YieldReturn.cs" />
<None Include="TestCases\ILPretty\Issue1256.il" />
<None Include="TestCases\ILPretty\Issue1323.il" />
<None Include="TestCases\ILPretty\Issue1325.il" />
<None Include="TestCases\Ugly\NoDecimalConstants.Expected.cs" />
<Compile Include="TestCases\Ugly\NoDecimalConstants.cs" />
<None Include="TestCases\Disassembler\Pretty\SecurityDeclarations.il" />
<Compile Include="TestCases\Pretty\CustomAttributeConflicts.cs" />
<Compile Include="TestCases\Pretty\DynamicTests.cs" />
<Compile Include="TestCases\Pretty\Issue1080.cs" />
<None Include="TestCases\Pretty\MemberTests.cs" />
<Compile Include="TestCases\Pretty\NamedArguments.cs" />
<Compile Include="TestCases\Pretty\QualifierTests.cs" />
<None Include="TestCases\Pretty\RefFields.cs" />
<Compile Include="TestCases\Pretty\RefLocalsAndReturns.cs" />
<Compile Include="TestCases\Pretty\TupleTests.cs" />
<Compile Include="TestCases\Pretty\WellKnownConstants.cs" />
<Compile Include="TypeSystem\TypeSystemLoaderTests.cs" />
<Compile Include="TypeSystem\TypeSystemTestCase.cs" />
<Compile Include="VBPrettyTestRunner.cs" />
<Compile Include="TestCases\VBPretty\Async.cs" />
<Compile Include="UglyTestRunner.cs" />
<Compile Include="TestCases\Correctness\ExpressionTrees.cs" />
<Compile Include="TestCases\Correctness\LINQRaytracer.cs" />
<Compile Include="TestCases\Correctness\MiniJSON.cs" />
<Compile Include="TestCases\Correctness\FloatingPointArithmetic.cs" />
<Compile Include="TestCases\ILPretty\Issue1038.cs" />
<None Include="TestCases\ILPretty\Issue1038.il" />
<Compile Include="TestCases\Ugly\NoArrayInitializers.cs" />
<None Include="TestCases\ILPretty\Issue1145.il" />
<None Include="TestCases\Ugly\NoArrayInitializers.Expected.cs" />
<None Include="TestCases\ILPretty\Issue1047.cs" />
<Compile Include="TestCases\Correctness\NullPropagation.cs" />
<Compile Include="TestCases\ILPretty\Issue982.cs" />
<Compile Include="TestCases\Pretty\CS72_PrivateProtected.cs" />
<Compile Include="TestCases\Pretty\StringInterpolation.cs" />
<Compile Include="TestCases\Pretty\ExpressionTrees.cs" />
<Compile Include="TestCases\Pretty\NullPropagation.cs" />
<Compile Include="TestCases\Pretty\VariableNaming.cs" />
<Compile Include="TestCases\Pretty\VariableNamingWithoutSymbols.cs" />
<Compile Include="PdbGenerationTestRunner.cs" />
<None Include="TestCases\ILPretty\Issue1047.il" />
<None Include="TestCases\ILPretty\Issue959.cs" />
<None Include="TestCases\ILPretty\FSharpLoops_Debug.cs" />
<None Include="TestCases\ILPretty\FSharpLoops_Release.cs" />
<Compile Include="TestCases\Pretty\DelegateConstruction.cs" />
<None Include="TestCases\ILPretty\FSharpUsing_Debug.cs" />
<None Include="TestCases\ILPretty\FSharpUsing_Release.cs" />
<Compile Include="Helpers\CodeAssert.cs" />
<Compile Include="Helpers\SdkUtility.cs" />
<Compile Include="Helpers\RemoveCompilerAttribute.cs" />
<Compile Include="Helpers\Tester.cs" />
<Compile Include="Helpers\Tester.VB.cs" />
<Compile Include="ILPrettyTestRunner.cs" />
<Compile Include="TestCases\Correctness\Loops.cs" />
<Compile Include="TestCases\Correctness\NullableTests.cs" />
<Compile Include="TestCases\Correctness\TrickyTypes.cs" />
<Compile Include="TestCases\Correctness\Using.cs" />
<Compile Include="TestCases\ILPretty\Issue379.cs" />
<Compile Include="TestCases\Pretty\FixProxyCalls.cs" />
<Compile Include="TestCases\Pretty\UnsafeCode.cs" />
<Compile Include="TestCases\Pretty\InitializerTests.cs" />
<None Include="TestCases\ILPretty\Issue959.il" />
<None Include="TestCases\ILPretty\Issue646.cs" />
<Compile Include="TestCases\Pretty\Async.cs" />
<Compile Include="TestCases\Pretty\CheckedUnchecked.cs" />
<Compile Include="TestCases\Pretty\Generics.cs" />
<Compile Include="TestCases\Pretty\LiftedOperators.cs" />
<Compile Include="PrettyTestRunner.cs" />
<Compile Include="RoundtripAssembly.cs" />
<Compile Include="TestCases\Correctness\Capturing.cs" />
<Compile Include="TestCases\Correctness\OverloadResolution.cs" />
<Compile Include="TestCases\Pretty\AnonymousTypes.cs" />
<Compile Include="TestCases\Correctness\Async.cs" />
<Compile Include="TestCases\Correctness\CompoundAssignment.cs" />
<Compile Include="TestCases\Correctness\ConditionalAttr.cs" />
<Compile Include="TestCases\Correctness\ControlFlow.cs" />
<Compile Include="TestCases\Correctness\Conversions.cs" />
<Compile Include="TestCases\Correctness\DecimalFields.cs" />
<Compile Include="TestCases\Correctness\Comparisons.cs" />
<Compile Include="TestCases\Correctness\Generics.cs" />
<Compile Include="TestCases\Correctness\HelloWorld.cs" />
<Compile Include="TestCases\Correctness\InitializerTests.cs" />
<Compile Include="TestCases\Correctness\MemberLookup.cs" />
<Compile Include="TestCases\Correctness\PropertiesAndEvents.cs" />
<Compile Include="TestCases\Correctness\Switch.cs" />
<Compile Include="TestCases\Correctness\UndocumentedExpressions.cs" />
<Compile Include="TestCases\Correctness\UnsafeCode.cs" />
<Compile Include="TestCases\Correctness\ValueTypeCall.cs" />
<Compile Include="CorrectnessTestRunner.cs" />
<Compile Include="TestCases\Pretty\AutoProperties.cs" />
<Compile Include="TestCases\Pretty\Lock.cs" />
<Compile Include="TestCases\Pretty\Loops.cs" />
<Compile Include="TestCases\Correctness\YieldReturn.cs" />
<Compile Include="TestCases\Pretty\CompoundAssignmentTest.cs" />
<Compile Include="TestCases\Pretty\ExceptionHandling.cs" />
<Compile Include="TestCases\Pretty\HelloWorld.cs" />
<Compile Include="TestCases\Pretty\InlineAssignmentTest.cs" />
<Compile Include="TestCases\Pretty\PInvoke.cs" />
<Compile Include="TestCases\Pretty\PropertiesAndEvents.cs" />
<Compile Include="TestCases\Pretty\QueryExpressions.cs" />
<Compile Include="TestCases\Pretty\ShortCircuit.cs" />
<Compile Include="TestCases\Pretty\Switch.cs" />
<Compile Include="TestCases\Pretty\TypeAnalysisTests.cs" />
<Compile Include="TestCases\Pretty\Using.cs" />
<Compile Include="TestTraceListener.cs" />
<Compile Include="Util\BitSetTests.cs" />
<Compile Include="Util\IntervalTests.cs" />
<Compile Include="Util\LongSetTests.cs" />
<Compile Include="TestCases\Pretty\AssemblyCustomAttributes.cs" />
<Compile Include="TestCases\Pretty\CustomAttributeSamples.cs" />
<Compile Include="TestCases\Pretty\CustomAttributes.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="TestCases\PdbGen\Members.xml" />
<Content Include="TestCases\PdbGen\ProgressReporting.xml" />
<Content Include="TestCases\PdbGen\ForLoopTests.xml" />
<Content Include="TestCases\PdbGen\CustomPdbId.xml" />
<Content Include="TestCases\PdbGen\HelloWorld.xml" />
<Content Include="TestCases\PdbGen\LambdaCapturing.xml" />
</ItemGroup>
<ItemGroup>
<None Include="TestCases\ILPretty\Issue646.il" />
<None Include="TestCases\ILPretty\Issue379.il" />
<None Include="TestCases\ILPretty\Issue982.il" />
<None Include="TestCases\Pretty\Readme.txt" />
<None Include="TestCases\VBPretty\VBCompoundAssign.vb" />
<None Include="TestCases\VBPretty\Async.vb" />
<None Include="TestCases\VBPretty\VBPropertiesTest.vb" />
<EmbeddedResource Include="Util\Test.resources" />
</ItemGroup>
</Project>
| ILSpy/ICSharpCode.Decompiler.Tests/ICSharpCode.Decompiler.Tests.csproj/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/ICSharpCode.Decompiler.Tests.csproj",
"repo_id": "ILSpy",
"token_count": 7025
} | 204 |
// 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.Globalization;
#pragma warning disable 652
namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
public class Comparisons
{
public static int Main()
{
#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator
TestFloatOp("==", (a, b) => a == b);
TestFloatOp("!=", (a, b) => a != b);
TestFloatOp("<", (a, b) => a < b);
TestFloatOp(">", (a, b) => a > b);
TestFloatOp("<=", (a, b) => a <= b);
TestFloatOp(">=", (a, b) => a >= b);
TestFloatOp("!<", (a, b) => !(a < b));
TestFloatOp("!>", (a, b) => !(a > b));
TestFloatOp("!<=", (a, b) => !(a <= b));
TestFloatOp("!>=", (a, b) => !(a >= b));
TestUInt(0);
TestUInt(uint.MaxValue);
TestUShort(0);
TestUShort(ushort.MaxValue);
Console.WriteLine("Issue2398:");
Issue2398(0x100000000);
Console.WriteLine("OverloadedOperators:");
Console.WriteLine(IsNotNull(new OverloadedOperators()));
Console.WriteLine(IsNull(new OverloadedOperators()));
Console.WriteLine(NullIs(new OverloadedOperators()));
Console.WriteLine(NullIsNot(new OverloadedOperators()));
return 0;
}
static void TestFloatOp(string name, Func<float, float, bool> f)
{
float[] vals = { -1, 0, 3, float.PositiveInfinity, float.NaN };
for (int i = 0; i < vals.Length; i++)
{
for (int j = 0; j < vals.Length; j++)
{
Console.WriteLine("Float: {0} {1} {2:r} = {3}",
vals[i].ToString("r", CultureInfo.InvariantCulture),
name,
vals[j].ToString("r", CultureInfo.InvariantCulture),
f(vals[i], vals[j]));
}
}
}
static T Id<T>(T arg)
{
return arg;
}
static void TestUShort(ushort i)
{
Console.WriteLine("ushort: {0} == ushort.MaxValue = {1}", i, i == ushort.MaxValue);
Console.WriteLine("ushort: {0} == -1 = {1}", i, i == -1);
Console.WriteLine("ushort: {0} == Id<short>(-1) = {1}", i, i == Id<short>(-1));
Console.WriteLine("ushort: {0} == 0x1ffff = {1}", i, i == 0x1ffff);
}
static void TestUInt(uint i)
{
Console.WriteLine("uint: {0} == uint.MaxValue = {1}", i, i == uint.MaxValue);
Console.WriteLine("uint: {0} == Id(uint.MaxValue) = {1}", i, i == Id(uint.MaxValue));
Console.WriteLine("uint: {0} == -1 = {1}", i, i == -1);
Console.WriteLine("uint: {0} == Id(-1) = {1}", i, i == Id(-1));
}
static void Issue2398(long value)
{
if ((int)value != 0)
Console.WriteLine("TRUE");
}
static bool IsNull(OverloadedOperators oo)
{
return (object)oo == null;
}
static bool IsNotNull(OverloadedOperators oo)
{
return (object)oo != null;
}
static bool NullIs(OverloadedOperators oo)
{
return null == (object)oo;
}
static bool NullIsNot(OverloadedOperators oo)
{
return null != (object)oo;
}
}
#pragma warning disable CS0660 // Type defines operator == or operator != but does not override Object.Equals(object o)
#pragma warning disable CS0661 // Type defines operator == or operator != but does not override Object.GetHashCode()
class OverloadedOperators
{
public static bool operator ==(OverloadedOperators oo, object b)
{
throw new NotSupportedException("Not supported to call the user-defined operator");
}
public static bool operator !=(OverloadedOperators oo, object b)
{
throw new NotSupportedException("Not supported to call the user-defined operator");
}
public static bool operator ==(object oo, OverloadedOperators b)
{
throw new NotSupportedException("Not supported to call the user-defined operator");
}
public static bool operator !=(object oo, OverloadedOperators b)
{
throw new NotSupportedException("Not supported to call the user-defined operator");
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/Comparisons.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/Comparisons.cs",
"repo_id": "ILSpy",
"token_count": 1789
} | 205 |
// 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;
namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
public class MemberLookup
{
static readonly Action delegateConstruction = (new Child1() as Base1).TestAction;
public static int Main()
{
Console.WriteLine((new Child1() as Base1).Field);
Child1.Test();
delegateConstruction();
new Child2b().CallTestMethod();
return 0;
}
class Base1
{
public int Field = 1;
protected virtual void TestMethod()
{
Property = 5;
Console.WriteLine("Base1.TestMethod()");
Console.WriteLine(Property);
}
public void TestAction()
{
Console.WriteLine("Base1.TestAction()");
}
public int Property { get; set; }
public virtual int VirtProp {
get {
return 3;
}
}
}
class Child1 : Base1
{
Child1 child;
new public int Field = 2;
public static void Test()
{
var o = new Child1();
o.child = new Child1();
o.TestMethod();
Console.WriteLine(((Base1)o).Property);
Console.WriteLine(o.Property);
Console.WriteLine(((Base1)o).VirtProp);
Console.WriteLine(o.VirtProp);
}
protected override void TestMethod()
{
Property = 10;
base.TestMethod();
if (child != null)
child.TestMethod();
Console.WriteLine("Child1.TestMethod()");
Console.WriteLine("Property = " + Property + " " + base.Property);
Console.WriteLine("Field = " + Field);
Console.WriteLine("base.Field = " + base.Field);
}
new public void TestAction()
{
Console.WriteLine("Child1.TestAction()");
}
new public int Property { get; set; }
public override int VirtProp {
get {
return base.VirtProp * 2;
}
}
}
class Child2 : Base1
{
public void CallTestMethod()
{
Console.WriteLine("Child2 calling this.TestMethod():");
this.TestMethod();
Console.WriteLine("Child2 calling base.TestMethod():");
base.TestMethod();
}
}
class Child2b : Child2
{
protected override void TestMethod()
{
Console.WriteLine("Child2b.TestMethod");
}
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/MemberLookup.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/MemberLookup.cs",
"repo_id": "ILSpy",
"token_count": 1134
} | 206 |
using System;
using System.Collections.Generic;
namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
public struct MutValueType : IDisposable
{
public int val;
public void Increment()
{
Console.WriteLine("Inc() called on {0}", val);
val = val + 1;
}
public void Dispose()
{
Console.WriteLine("MutValueType disposed on {0}", val);
val = val + 1;
}
public override string ToString()
{
return "MutValueType.ToString() " + (++val);
}
}
public struct GenericValueType<T>
{
T data;
int num;
public GenericValueType(T data)
{
this.data = data;
this.num = 1;
}
public void Call(ref GenericValueType<T> v)
{
num++;
Console.WriteLine("Call #{0}: {1} with v=#{2}", num, data, v.num);
}
}
public struct ValueTypeWithReadOnlyMember
{
public readonly int Member;
public ValueTypeWithReadOnlyMember(int member)
{
this.Member = member;
}
}
public class ValueTypeCall
{
public static void Main()
{
MutValueType m = new MutValueType();
RefParameter(ref m);
ValueParameter(m);
Field();
Box();
BoxToStringCalls();
Using();
var gvt = new GenericValueType<string>("Test");
gvt.Call(ref gvt);
new ValueTypeCall().InstanceFieldTests();
ForEach();
#if CS73
DisposeMultipleTimes(ref m, in m);
ToStringGeneric(ref m, in m);
#endif
}
static void RefParameter(ref MutValueType m)
{
m.Increment();
m.Increment();
}
static void ValueParameter(MutValueType m)
{
m.Increment();
m.Increment();
}
static readonly MutValueType ReadonlyField = new MutValueType { val = 100 };
static MutValueType MutableField = new MutValueType { val = 200 };
static void Field()
{
ReadonlyField.Increment();
ReadonlyField.Increment();
MutableField.Increment();
MutableField.Increment();
// Ensure that 'v' isn't incorrectly removed
// as a compiler-generated temporary
MutValueType v = MutableField;
v.Increment();
Console.WriteLine("Final value in MutableField: " + MutableField.val);
// Read-only field copies cannot be inlined for static methods:
MutValueType localCopy = ReadonlyField;
RefParameter(ref localCopy);
}
static void Box()
{
Console.WriteLine("Box");
object o = new MutValueType { val = 300 };
((MutValueType)o).Increment();
((MutValueType)o).Increment();
MutValueType unboxed1 = (MutValueType)o;
unboxed1.Increment();
unboxed1.Increment();
((MutValueType)o).Increment();
MutValueType unboxed2 = (MutValueType)o;
unboxed2.val = 100;
((MutValueType)o).Dispose();
}
static void BoxToStringCalls()
{
Console.WriteLine("BoxToStringCalls:");
MutValueType m = new MutValueType { val = 400 };
Console.WriteLine(m.ToString());
Console.WriteLine(((object)m).ToString());
Console.WriteLine(m.ToString());
}
MutValueType instanceField;
ValueTypeWithReadOnlyMember mutableInstanceFieldWithReadOnlyMember;
void InstanceFieldTests()
{
this.instanceField.val = 42;
Console.WriteLine(this.instanceField.val);
mutableInstanceFieldWithReadOnlyMember = new ValueTypeWithReadOnlyMember(45);
Console.WriteLine(this.mutableInstanceFieldWithReadOnlyMember.Member);
}
static void Using()
{
Using1();
Using2();
Using3();
}
static void Using1()
{
Console.WriteLine("Using:");
using (var x = new MutValueType())
{
x.Increment();
}
}
static void Using2()
{
Console.WriteLine("Not using:");
var y = new MutValueType();
try
{
y.Increment();
}
finally
{
MutValueType x = y;
x.Dispose();
}
}
static void Using3()
{
Console.WriteLine("Using with variable declared outside:");
MutValueType z;
using (z = new MutValueType())
{
z.Increment();
}
}
static void ForEach()
{
var list = new List<MutValueType> {
new MutValueType { val = 10 },
new MutValueType { val = 20 },
new MutValueType { val = 30 },
};
ForEach1(list);
var array = new MutValueType[] {
new MutValueType { val = 100 },
new MutValueType { val = 200 },
new MutValueType { val = 300 },
};
ForEachArray1(array);
}
static void ForEach1(List<MutValueType> list)
{
Console.WriteLine("ForEach1:");
foreach (var val in list)
{
val.Increment();
val.Increment();
}
Console.WriteLine("after: " + list[0].val);
}
static void ForEachArray1(MutValueType[] list)
{
Console.WriteLine("ForEachArray1:");
foreach (var val in list)
{
val.Increment();
val.Increment();
}
Console.WriteLine("after: " + list[0].val);
}
#if CS73
static void DisposeMultipleTimes<T>(ref T mutRef, in T immutableRef) where T : struct, IDisposable
{
Console.WriteLine("DisposeMultipleTimes:");
mutRef.Dispose();
mutRef.Dispose();
T copyFromMut = mutRef;
copyFromMut.Dispose();
immutableRef.Dispose();
immutableRef.Dispose();
T copyFromImmutable = immutableRef;
copyFromImmutable.Dispose();
mutRef.Dispose();
immutableRef.Dispose();
}
static void ToStringGeneric<T>(ref T mutRef, in T immutableRef) where T : struct
{
Console.WriteLine("ToStringGeneric:");
Console.WriteLine(mutRef.ToString());
Console.WriteLine(mutRef.ToString());
T copyFromMut = mutRef;
Console.WriteLine(copyFromMut.ToString());
Console.WriteLine(immutableRef.ToString());
Console.WriteLine(immutableRef.ToString());
T copyFromImmutable = immutableRef;
Console.WriteLine(copyFromImmutable.ToString());
Console.WriteLine(mutRef.ToString());
Console.WriteLine(immutableRef.ToString());
}
#endif
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/ValueTypeCall.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/ValueTypeCall.cs",
"repo_id": "ILSpy",
"token_count": 2249
} | 207 |
using System;
public sealed class TestClass : IDisposable
{
void IDisposable.Dispose()
{
}
public void Test(TestClass other)
{
((IDisposable)this).Dispose();
((IDisposable)other).Dispose();
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/DirectCallToExplicitInterfaceImpl.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/DirectCallToExplicitInterfaceImpl.cs",
"repo_id": "ILSpy",
"token_count": 84
} | 208 |
// ClassLibrary1.UnknownClassTest
using System;
using System.Collections.Generic;
using UnknownNamespace;
namespace ClassLibrary1
{
public class UnknownClassTest : EventArgs
{
public void MethodUnknownClass()
{
//IL_0001: Unknown result type (might be due to invalid IL or missing references)
//IL_0007: Expected O, but got Unknown
UnknownClass val = new UnknownClass();
int? unknownProperty = val.UnknownProperty;
int? num2 = (val.UnknownProperty = unknownProperty.GetValueOrDefault());
int? num3 = num2;
List<object> list = new List<object> {
val[unknownProperty.Value] ?? "",
val.NotProperty,
val.get_NotPropertyWithGeneric<string>(42),
val[42],
val.get_NotPropertyWithParameterAndGeneric<object>(int.MinValue),
val.get_PropertyCalledGet,
val.set_HasReturnType(),
val.set_HasReturnType("")
};
val.get_NoReturnType();
val.set_NoValue();
val.OnEvent += Instance_OnEvent;
val.OnEvent -= Instance_OnEvent;
string text = val[(long?)null];
val[(long?)long.MaxValue] = text;
IntPtr intPtr = val[UIntPtr.Zero, "Hello"];
val[(UIntPtr)32uL, "World"] = intPtr;
}
public void MethodUnknownGenericClass()
{
//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
//IL_00bc: Expected O, but got Unknown
//IL_00be: Unknown result type (might be due to invalid IL or missing references)
//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
//IL_00cd: Expected O, but got Unknown
//IL_00cd: Expected O, but got Unknown
//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
//IL_00e1: Expected O, but got Unknown
//IL_00e1: Expected O, but got Unknown
UnknownGenericClass<UnknownEventArgs> val = new UnknownGenericClass<UnknownEventArgs>();
UnknownEventArgs val2 = (val.UnknownProperty = val.UnknownProperty);
List<object> list = new List<object> {
val[((object)val2).GetHashCode()] ?? "",
val.NotProperty,
val.get_NotPropertyWithGeneric<string>(42),
val[42],
val.get_NotPropertyWithParameterAndGeneric<object>(int.MinValue),
val.get_PropertyCalledGet
};
val.OnEvent += Instance_OnEvent;
val.OnEvent -= Instance_OnEvent;
UnknownEventArgs val3 = val[(UnknownEventArgs)null];
val[new UnknownEventArgs()] = val3;
UnknownEventArgs val4 = val[new UnknownEventArgs(), new UnknownEventArgs()];
val[new UnknownEventArgs(), new UnknownEventArgs()] = val4;
}
public void MethodUnknownStatic()
{
int? num = (UnknownStaticClass.UnknownProperty = UnknownStaticClass.UnknownProperty);
List<object> list = new List<object> {
UnknownStaticClass[num.Value] ?? "",
UnknownStaticClass.NotProperty,
UnknownStaticClass.get_NotPropertyWithGeneric<string>(42),
UnknownStaticClass[42],
UnknownStaticClass.get_NotPropertyWithParameterAndGeneric<object>(int.MinValue),
UnknownStaticClass.get_PropertyCalledGet
};
UnknownStaticClass.OnEvent += Instance_OnEvent;
UnknownStaticClass.OnEvent -= Instance_OnEvent;
}
public void MethodUnknownStaticGeneric()
{
string text = (UnknownStaticGenericClass<string>.UnknownProperty = UnknownStaticGenericClass<string>.UnknownProperty);
List<object> list = new List<object> {
UnknownStaticGenericClass<string>[text.Length] ?? "",
UnknownStaticGenericClass<string>.NotProperty,
UnknownStaticGenericClass<string>.get_NotPropertyWithGeneric<string>(42),
UnknownStaticGenericClass<string>[42],
UnknownStaticGenericClass<string>.get_NotPropertyWithParameterAndGeneric<object>(int.MinValue),
UnknownStaticGenericClass<string>.get_PropertyCalledGet
};
UnknownStaticGenericClass<string>.OnEvent += Instance_OnEvent;
UnknownStaticGenericClass<string>.OnEvent -= Instance_OnEvent;
}
public void MethodUnknownIndexerInitializer()
{
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
new UnknownClass {
["a"] = 1,
["b"] = 2
};
}
private void Instance_OnEvent(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void Instance_OnEvent(object sender, UnknownEventArgs e)
{
throw new NotImplementedException();
}
private void Instance_OnEvent(object sender, string e)
{
throw new NotImplementedException();
}
private static void Instance_OnEvent(object sender, object e)
{
throw new NotImplementedException();
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/GuessAccessors.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/GuessAccessors.cs",
"repo_id": "ILSpy",
"token_count": 1576
} | 209 |
Imports System
Imports System.IO
Module Program
Sub Main(args As String())
End Sub
Sub TestCode(ByVal t As Test, ByVal i As Integer)
Dim s As String = ""
s += File.ReadAllText("Test.txt")
s += "asdf"
t.Parameterized(i) = s
t.Unparameterized = s + "asdf"
End Sub
End Module
Class Test
Public Property Parameterized(ByVal i As Integer) As String
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Public Property Unparameterized As String
End Class | ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1325.vb/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1325.vb",
"repo_id": "ILSpy",
"token_count": 271
} | 210 |
// Microsoft (R) .NET Framework IL Disassembler. Version 4.6.1055.0
// Copyright (c) Microsoft Corporation. All rights reserved.
// 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 ClassLibrary1
{
.ver 1:0:0:0
}
.assembly ConsoleApp8
{
.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 )
.custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string) = ( 01 00 1C 2E 4E 45 54 46 72 61 6D 65 77 6F 72 6B // ....NETFramework
2C 56 65 72 73 69 6F 6E 3D 76 34 2E 37 2E 32 01 // ,Version=v4.7.2.
00 54 0E 14 46 72 61 6D 65 77 6F 72 6B 44 69 73 // .T..FrameworkDis
70 6C 61 79 4E 61 6D 65 14 2E 4E 45 54 20 46 72 // playName..NET Fr
61 6D 65 77 6F 72 6B 20 34 2E 37 2E 32 ) // amework 4.7.2
.custom instance void [mscorlib]System.Reflection.AssemblyCompanyAttribute::.ctor(string) = ( 01 00 0B 43 6F 6E 73 6F 6C 65 41 70 70 38 00 00 ) // ...ConsoleApp8..
.custom instance void [mscorlib]System.Reflection.AssemblyConfigurationAttribute::.ctor(string) = ( 01 00 07 52 65 6C 65 61 73 65 00 00 ) // ...Release..
.custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = ( 01 00 07 31 2E 30 2E 30 2E 30 00 00 ) // ...1.0.0.0..
.custom instance void [mscorlib]System.Reflection.AssemblyInformationalVersionAttribute::.ctor(string) = ( 01 00 05 31 2E 30 2E 30 00 00 ) // ...1.0.0..
.custom instance void [mscorlib]System.Reflection.AssemblyProductAttribute::.ctor(string) = ( 01 00 0B 43 6F 6E 73 6F 6C 65 41 70 70 38 00 00 ) // ...ConsoleApp8..
.custom instance void [mscorlib]System.Reflection.AssemblyTitleAttribute::.ctor(string) = ( 01 00 0B 43 6F 6E 73 6F 6C 65 41 70 70 38 00 00 ) // ...ConsoleApp8..
.hash algorithm 0x00008004
.ver 1:0:0:0
}
.module ConsoleApp8.exe
// MVID: {C71BB5CC-A98C-4CF4-B8A4-000055F94187}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
// Image base: 0x02890000
// =============== CLASS MEMBERS DECLARATION ===================
.class private auto ansi beforefieldinit ConsoleApp8.Program
extends [ClassLibrary1]ClassLibrary1.Class1
{
.method public hidebysig specialname rtspecialname
instance void .ctor(string _) cil managed
{
// Code size 18 (0x12)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call instance void [ClassLibrary1]ClassLibrary1.Class1::.ctor(string)
IL_0007: ldstr "Class1(string)<-Program(string)"
IL_000c: call void [mscorlib]System.Console::WriteLine(string)
IL_0011: ret
} // end of method Program::.ctor
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 22 (0x16)
.maxstack 8
IL_0000: ldstr ""
IL_0005: newobj instance void ConsoleApp8.Program::.ctor(string)
IL_000a: pop
IL_000b: ldstr "Hello World!"
IL_0010: call void [mscorlib]System.Console::WriteLine(string)
IL_0015: ret
} // end of method Program::Main
} // end of class ConsoleApp8.Program
// =============================================================
// *********** DISASSEMBLY COMPLETE ***********************
// WARNING: Created Win32 resource file Issue2443.res
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue2443.il/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue2443.il",
"repo_id": "ILSpy",
"token_count": 2094
} | 211 |
#define CORE_ASSEMBLY "System.Runtime"
.assembly extern CORE_ASSEMBLY
{
.publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....:
.ver 4:0:0:0
}
.assembly extern UnknownAssembly
{
.publickeytoken = (01 02 03 04 05 06 07 08 )
.ver 1:0:0:0
}
.class private auto ansi beforefieldinit UnknownTypes
extends [System.Private.CoreLib]System.Object
{
.field private initonly class [UnknownAssembly]IInterface memberField
// Methods
.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 [CORE_ASSEMBLY]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method UnknownTypes::.ctor
.method public hidebysig virtual
instance bool CanExecute (
class [UnknownAssembly]CallbackQuery message
) cil managed
{
// Method begins at RVA 0x4dbc
// Code size 44 (0x2c)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld class [UnknownAssembly]IInterface UnknownTypes::memberField
IL_0006: newobj instance void [UnknownAssembly]SomeClass::.ctor()
IL_000b: dup
IL_000d: ldarg.1
IL_000e: call int64 [UnknownAssembly]StaticClass::GetChatId(class [UnknownAssembly]CallbackQuery)
IL_0013: stfld int64 [UnknownAssembly]SomeClass::ChatId
IL_0018: dup
IL_001a: ldarg.1
IL_001b: call int32 [UnknownAssembly]StaticClass::GetMessageId(class [UnknownAssembly]CallbackQuery)
IL_0020: conv.i8
IL_0021: stfld int64 [UnknownAssembly]SomeClass::MessageId
IL_0026: callvirt instance !1 class [UnknownAssembly]IInterface`2<class [UnknownAssembly]SomeClass, bool>::Execute(!0)
IL_002b: ret
} // end of method CanExecute
} // end of class UnknownTypes
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/UnknownTypes.il/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/UnknownTypes.il",
"repo_id": "ILSpy",
"token_count": 775
} | 212 |
using System;
namespace CustomAttributes2
{
public static class CustomAttributes
{
[Flags]
public enum EnumWithFlag
{
All = 0xF,
None = 0,
Item1 = 1,
Item2 = 2,
Item3 = 4,
Item4 = 8
}
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
public MyAttribute(EnumWithFlag en)
{
}
}
[My(EnumWithFlag.Item1 | EnumWithFlag.Item2)]
private static int field;
[My(EnumWithFlag.All)]
#if ROSLYN
public static string Property => "aa";
#else
public static string Property {
get {
return "aa";
}
}
#endif
public static string GetterOnlyPropertyWithAttributeOnGetter {
[My(EnumWithFlag.Item1)]
get {
return "aa";
}
}
[My(EnumWithFlag.All)]
public static string GetterOnlyPropertyWithAttributeOnGetter2 {
[My(EnumWithFlag.Item1)]
get {
return "aa";
}
}
[Obsolete("some message")]
public static void ObsoletedMethod()
{
Console.WriteLine("{0} $$$ {1}", AttributeTargets.Interface, AttributeTargets.Property | AttributeTargets.Field);
AttributeTargets attributeTargets = AttributeTargets.Property | AttributeTargets.Field;
Console.WriteLine("{0} $$$ {1}", AttributeTargets.Interface, attributeTargets);
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/CustomAttributes2.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/CustomAttributes2.cs",
"repo_id": "ILSpy",
"token_count": 513
} | 213 |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty.InitializerTests
{
public static class Extensions
{
public static void Add(this TestCases.CustomList<int> inst, string a, string b)
{
}
public static void Add<T>(this IList<KeyValuePair<string, string>> collection, string key, T value, Func<T, string> convert = null)
{
}
public static void Add(this TestCases collection, string key)
{
}
}
public class TestCases
{
#region Types
public class CustomList<T> : IEnumerable<T>, IEnumerable
{
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
public void Add<T2>(string name)
{
new Dictionary<string, Type>().Add(name, typeof(T2));
}
public void Add(params int[] ints)
{
}
}
public class C
{
public int Z;
public S Y;
public List<S> L;
public S this[int index] {
get {
return default(S);
}
set {
}
}
public S this[object key] {
get {
return default(S);
}
set {
}
}
}
public struct S
{
public int A;
public int B;
public S(int a)
{
A = a;
B = 0;
}
}
private enum MyEnum
{
a,
b
}
private enum MyEnum2
{
c,
d
}
private class Data
{
public List<MyEnum2> FieldList = new List<MyEnum2>();
public MyEnum a { get; set; }
public MyEnum b { get; set; }
public List<MyEnum2> PropertyList { get; set; }
#if CS60
public List<MyEnum2> ReadOnlyPropertyList { get; }
#endif
public Data MoreData { get; set; }
public StructData NestedStruct { get; set; }
public Data this[int i] {
get {
return null;
}
set {
}
}
public Data this[int i, string j] {
get {
return null;
}
set {
}
}
public event EventHandler TestEvent;
}
private struct StructData
{
public int Field;
public int Property { get; set; }
public Data MoreData { get; set; }
public StructData(int initialValue)
{
this = default(StructData);
Field = initialValue;
Property = initialValue;
}
}
public class Item
{
public string Text { get; set; }
public decimal Value { get; set; }
public decimal Value2 { get; set; }
public string Value3 { get; set; }
public string Value4 { get; set; }
public string Value5 { get; set; }
public string Value6 { get; set; }
#if CS90
public Fields Value7 { get; set; }
#endif
}
public class OtherItem
{
public decimal Value { get; set; }
public decimal Value2 { get; set; }
public decimal? Nullable { get; set; }
public decimal? Nullable2 { get; set; }
public decimal? Nullable3 { get; set; }
public decimal? Nullable4 { get; set; }
}
public class OtherItem2
{
public readonly OtherItem Data;
public OtherItem Data2 { get; private set; }
#if CS60
public OtherItem Data3 { get; }
#endif
}
public class V3f
{
private float x;
private float y;
private float z;
public V3f(float _x, float _y, float _z)
{
x = _x;
y = _y;
z = _z;
}
}
#if CS90
public record Fields
{
public int A;
public double B = 1.0;
public object C;
public dynamic D;
public string S = "abc";
public Item I;
}
#endif
public interface IData
{
int Property { get; set; }
}
#endregion
private S s1;
private S s2;
#region Field initializer tests
private static V3f[] Issue1336_rg0 = new V3f[3] {
new V3f(1f, 1f, 1f),
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f)
};
private static V3f[,] Issue1336_rg1 = new V3f[3, 3] {
{
new V3f(1f, 1f, 1f),
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f)
},
{
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f)
},
{
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f),
new V3f(5f, 5f, 5f)
}
};
private static V3f[][] Issue1336_rg1b = new V3f[3][] {
new V3f[3] {
new V3f(1f, 1f, 1f),
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f)
},
new V3f[3] {
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f)
},
new V3f[3] {
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f),
new V3f(5f, 5f, 5f)
}
};
private static V3f[,][] Issue1336_rg1c = new V3f[3, 3][] {
{
new V3f[3] {
new V3f(1f, 1f, 1f),
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f)
},
new V3f[3] {
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f)
},
new V3f[3] {
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f),
new V3f(5f, 5f, 5f)
}
},
{
new V3f[3] {
new V3f(1f, 1f, 1f),
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f)
},
new V3f[3] {
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f)
},
new V3f[3] {
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f),
new V3f(5f, 5f, 5f)
}
},
{
new V3f[3] {
new V3f(1f, 1f, 1f),
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f)
},
new V3f[3] {
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f)
},
new V3f[3] {
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f),
new V3f(5f, 5f, 5f)
}
}
};
private static V3f[][,] Issue1336_rg1d = new V3f[2][,] {
new V3f[3, 3] {
{
new V3f(1f, 1f, 1f),
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f)
},
{
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f)
},
{
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f),
new V3f(5f, 5f, 5f)
}
},
new V3f[3, 3] {
{
new V3f(1f, 1f, 1f),
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f)
},
{
new V3f(2f, 2f, 2f),
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f)
},
{
new V3f(3f, 3f, 3f),
new V3f(4f, 4f, 4f),
new V3f(5f, 5f, 5f)
}
}
};
private static int[,] Issue1336_rg2 = new int[3, 3] {
{ 1, 1, 1 },
{ 1, 1, 1 },
{ 1, 1, 1 }
};
#if CS73 && !NET40
public static ReadOnlySpan<byte> StaticData1 => new byte[1] { 0 };
public static ReadOnlySpan<byte> StaticData3 => new byte[3] { 1, 2, 3 };
public static Span<byte> StaticData3Span => new byte[3] { 1, 2, 3 };
#endif
#if CS110 && !NET40
public static ReadOnlySpan<byte> UTF8Literal => "Hello, world!"u8;
#endif
#endregion
#region Helper methods used to ensure initializers used within expressions work correctly
private static void X(object a, object b)
{
}
private static object Y()
{
return null;
}
public static void TestCall(int a, Thread thread)
{
}
public static C TestCall(int a, C c)
{
return c;
}
private static int GetInt()
{
return 1;
}
private static string GetString()
{
return "Test";
}
private static void NoOp(Guid?[] array)
{
}
private void Data_TestEvent(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
#region Array initializers
public static void Array1()
{
X(Y(), new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
}
public static void Array2(int a, int b, int c)
{
X(Y(), new int[5] { a, 0, b, 0, c });
}
public static void NestedArray(int a, int b, int c)
{
X(Y(), new int[3][] {
new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
new int[3] { a, b, c },
new int[6] { 1, 2, 3, 4, 5, 6 }
});
}
public static void NestedNullableArray(int a, int b, int c)
{
X(Y(), new int?[3][] {
new int?[11] {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
null
},
new int?[4] { a, b, c, null },
new int?[7] { 1, 2, 3, 4, 5, 6, null }
});
}
public unsafe static void NestedPointerArray(int a, int b, int c)
{
X(Y(), new void*[3][] {
new void*[1] { null },
new void*[2] {
(void*)200,
null
},
new void*[2] {
(void*)100,
null
}
});
}
public static void ArrayBoolean()
{
X(Y(), new bool[8] { true, false, true, false, false, false, true, true });
}
public static void ArrayByte()
{
X(Y(), new byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 254, 255 });
}
public static void ArraySByte()
{
X(Y(), new sbyte[8] { -128, -127, 0, 1, 2, 3, 4, 127 });
}
public static void ArrayShort()
{
X(Y(), new short[5] { -32768, -1, 0, 1, 32767 });
}
public static void ArrayUShort()
{
X(Y(), new ushort[6] { 0, 1, 32767, 32768, 65534, 65535 });
}
public static void ArrayInt()
{
X(Y(), new int[10] { 1, -2, 2000000000, 4, 5, -6, 7, 8, 9, 10 });
}
public static void ArrayUInt()
{
X(Y(), new uint[10] { 1u, 2000000000u, 3000000000u, 4u, 5u, 6u, 7u, 8u, 9u, 10u });
}
public static void ArrayLong()
{
X(Y(), new long[5] { -4999999999999999999L, -1L, 0L, 1L, 4999999999999999999L });
}
public static void ArrayULong()
{
X(Y(), new ulong[10] { 1uL, 2000000000uL, 3000000000uL, 4uL, 5uL, 6uL, 7uL, 8uL, 4999999999999999999uL, 9999999999999999999uL });
}
public static void ArrayFloat()
{
X(Y(), new float[6] {
-1.5f,
0f,
1.5f,
float.NegativeInfinity,
float.PositiveInfinity,
float.NaN
});
}
public static void ArrayDouble()
{
X(Y(), new double[6] {
-1.5,
0.0,
1.5,
double.NegativeInfinity,
double.PositiveInfinity,
double.NaN
});
}
public static void ArrayDecimal()
{
X(Y(), new decimal[6] { -100m, 0m, 100m, -79228162514264337593543950335m, 79228162514264337593543950335m, 0.0000001m });
}
public static void ArrayString()
{
X(Y(), new string[4] { "", null, "Hello", "World" });
}
public static void ArrayEnum()
{
X(Y(), new MyEnum[4] {
MyEnum.a,
MyEnum.b,
MyEnum.a,
MyEnum.b
});
}
public int[,] MultidimensionalInit()
{
return new int[16, 4] {
{ 0, 0, 0, 0 },
{ 1, 1, 1, 1 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 1, 1, 1, 1 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 }
};
}
public int[][,] MultidimensionalInit2()
{
return new int[4][,] {
new int[4, 4] {
{ 0, 0, 0, 0 },
{ 1, 1, 1, 1 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 }
},
new int[4, 4] {
{ 0, 0, 0, 0 },
{ 1, 1, 1, 1 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 }
},
new int[4, 4] {
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 }
},
new int[4, 4] {
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 }
}
};
}
public int[][,,] ArrayOfArrayOfArrayInit()
{
return new int[2][,,] {
new int[2, 3, 3] {
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
},
{
{ 11, 12, 13 },
{ 14, 15, 16 },
{ 17, 18, 19 }
}
},
new int[2, 3, 3] {
{
{ 21, 22, 23 },
{ 24, 25, 26 },
{ 27, 28, 29 }
},
{
{ 31, 32, 33 },
{ 34, 35, 36 },
{ 37, 38, 39 }
}
}
};
}
public static void RecursiveArrayInitializer()
{
int[] array = new int[3];
array[0] = 1;
array[1] = 2;
array[2] = array[1] + 1;
array[0] = 0;
}
public static void InvalidIndices(int a)
{
int[] array = new int[1];
array[1] = a;
X(Y(), array);
}
public static void InvalidIndices2(int a)
{
#pragma warning disable 251
int[] array = new int[1];
array[-1] = a;
X(Y(), array);
#pragma warning restore
}
public static void IndicesInWrongOrder(int a, int b)
{
int[] array = new int[5];
array[2] = b;
array[1] = a;
X(Y(), array);
}
public int[] IndicesInWrongOrderConstantsFull()
{
int[] array = new int[3];
array[0] = 0;
array[2] = 1;
array[1] = 2;
return array;
}
public static byte[] ReverseInitializer(int i)
{
byte[] array = new byte[4];
array[3] = (byte)i;
array[2] = (byte)(i >> 8);
array[1] = (byte)(i >> 16);
array[0] = (byte)(i >> 24);
return array;
}
public static void Issue953_MissingNullableSpecifierForArrayInitializer()
{
NoOp(new Guid?[1] { Guid.Empty });
}
private void Issue907_Test3(string text)
{
X(Y(), new Dictionary<string, object> { { "", text } });
}
private int[] Issue1383(int i, int[] array)
{
array = new int[4];
array[i++] = 1;
array[i++] = 2;
return array;
}
private string[,] Issue1382a()
{
return new string[4, 4] {
{ null, "test", "hello", "world" },
{ "test", null, "hello", "world" },
{ "test", "hello", null, "world" },
{ "test", "hello", "world", null }
};
}
private string[,] Issue1382b()
{
return new string[4, 4] {
{ "test", "hello", "world", null },
{ "test", "hello", null, "world" },
{ "test", null, "hello", "world" },
{ null, "test", "hello", "world" }
};
}
private static void OutOfMemory()
{
byte[] array = new byte[int.MaxValue];
array[0] = 1;
Console.WriteLine(array.Length);
}
#endregion
#region Object initializers
public C Test1()
{
C c = new C();
c.L = new List<S>();
c.L.Add(new S(1));
return c;
}
public C Test1Alternative()
{
return TestCall(1, new C {
L = new List<S> {
new S(1)
}
});
}
public C Test2()
{
C c = new C();
c.Z = 1;
c.Z = 2;
return c;
}
public C Test3()
{
C c = new C();
c.Y = new S(1);
c.Y.A = 2;
return c;
}
public C Test3b()
{
return TestCall(0, new C {
Z = 1,
Y = {
A = 2
}
});
}
public C Test4()
{
C c = new C();
c.Y.A = 1;
c.Z = 2;
c.Y.B = 3;
return c;
}
public static void ObjectInitializer()
{
X(Y(), new Data {
a = MyEnum.a
});
}
public static void NotAnObjectInitializer()
{
Data data = new Data();
data.a = MyEnum.a;
X(Y(), data);
}
public static void NotAnObjectInitializerWithEvent()
{
Data data = new Data();
data.TestEvent += delegate {
Console.WriteLine();
};
X(Y(), data);
}
public static void ObjectInitializerAssignCollectionToField()
{
X(Y(), new Data {
a = MyEnum.a,
FieldList = new List<MyEnum2> {
MyEnum2.c,
MyEnum2.d
}
});
}
public static void ObjectInitializerAddToCollectionInField()
{
X(Y(), new Data {
a = MyEnum.a,
FieldList = {
MyEnum2.c,
MyEnum2.d
}
});
}
public static void ObjectInitializerAssignCollectionToProperty()
{
X(Y(), new Data {
a = MyEnum.a,
PropertyList = new List<MyEnum2> {
MyEnum2.c,
MyEnum2.d
}
});
}
public static void ObjectInitializerAddToCollectionInProperty()
{
X(Y(), new Data {
a = MyEnum.a,
PropertyList = {
MyEnum2.c,
MyEnum2.d
}
});
}
public static void ObjectInitializerWithInitializationOfNestedObjects()
{
X(Y(), new Data {
MoreData = {
a = MyEnum.a,
MoreData = {
a = MyEnum.b
}
}
});
}
public static void ObjectInitializerWithInitializationOfDeeplyNestedObjects()
{
X(Y(), new Data {
a = MyEnum.b,
MoreData = {
a = MyEnum.a,
MoreData = {
MoreData = {
MoreData = {
MoreData = {
MoreData = {
MoreData = {
a = MyEnum.b
}
}
}
}
}
}
}
});
}
public static void CollectionInitializerInsideObjectInitializers()
{
X(Y(), new Data {
MoreData = new Data {
a = MyEnum.a,
b = MyEnum.b,
PropertyList = { MyEnum2.c }
}
});
}
public static void NotAStructInitializer_DefaultConstructor()
{
StructData structData = default(StructData);
structData.Field = 1;
structData.Property = 2;
X(Y(), structData);
}
public static void StructInitializer_DefaultConstructor()
{
X(Y(), new StructData {
Field = 1,
Property = 2
});
}
public void InliningOfStFldTarget()
{
s1 = new S {
A = 24,
B = 42
};
s2 = new S {
A = 42,
B = 24
};
}
public static void NotAStructInitializer_ExplicitConstructor()
{
StructData structData = new StructData(0);
structData.Field = 1;
structData.Property = 2;
X(Y(), structData);
}
public static void StructInitializer_ExplicitConstructor()
{
X(Y(), new StructData(0) {
Field = 1,
Property = 2
});
}
public static void StructInitializerWithInitializationOfNestedObjects()
{
X(Y(), new StructData {
MoreData = {
a = MyEnum.a,
FieldList = {
MyEnum2.c,
MyEnum2.d
}
}
});
}
public static void StructInitializerWithinObjectInitializer()
{
X(Y(), new Data {
NestedStruct = new StructData(2) {
Field = 1,
Property = 2
}
});
}
public static void Issue270_NestedInitialisers()
{
NumberFormatInfo[] source = null;
TestCall(0, new Thread(Issue270_NestedInitialisers) {
Priority = ThreadPriority.BelowNormal,
CurrentCulture = new CultureInfo(0) {
DateTimeFormat = new DateTimeFormatInfo {
ShortDatePattern = "ddmmyy"
},
NumberFormat = source.Where((NumberFormatInfo format) => format.CurrencySymbol == "$").First()
}
});
}
public OtherItem2 Issue1345()
{
OtherItem2 otherItem = new OtherItem2();
otherItem.Data.Nullable = 3m;
return otherItem;
}
public OtherItem2 Issue1345b()
{
OtherItem2 otherItem = new OtherItem2();
otherItem.Data2.Nullable = 3m;
return otherItem;
}
#if CS60
public OtherItem2 Issue1345c()
{
OtherItem2 otherItem = new OtherItem2();
otherItem.Data3.Nullable = 3m;
return otherItem;
}
private Data Issue1345_FalsePositive()
{
return new Data {
ReadOnlyPropertyList = {
MyEnum2.c,
MyEnum2.d
}
};
}
#endif
private void Issue1250_Test1(MyEnum value)
{
X(Y(), new C {
Z = (int)value
});
}
private byte[] Issue1314()
{
return new byte[4] { 0, 1, 2, 255 };
}
private void Issue1251_Test(List<Item> list, OtherItem otherItem)
{
list.Add(new Item {
Text = "Text",
Value = otherItem.Value,
Value2 = otherItem.Value2,
Value3 = otherItem.Nullable.ToString(),
Value4 = otherItem.Nullable2.ToString(),
Value5 = otherItem.Nullable3.ToString(),
Value6 = otherItem.Nullable4.ToString()
});
}
private Data Issue1279(int p)
{
if (p == 1)
{
Data data = new Data();
data.a = MyEnum.a;
data.TestEvent += Data_TestEvent;
return data;
}
return null;
}
#if CS90
private Fields RecordWithNestedClass(Fields input)
{
return input with {
A = 42,
I = new Item {
Value7 = input with {
A = 43
}
}
};
}
#endif
private TData GenericObjectInitializer<TData>() where TData : IData, new()
{
return new TData {
Property = 42
};
}
#endregion
#region Collection initializer
public static void ExtensionMethodInCollectionInitializer()
{
#if CS60
X(Y(), new CustomList<int> { { "1", "2" } });
#else
CustomList<int> customList = new CustomList<int>();
customList.Add("1", "2");
X(Y(), customList);
#endif
}
public static void NoCollectionInitializerBecauseOfTypeArguments()
{
CustomList<int> customList = new CustomList<int>();
customList.Add<int>("int");
Console.WriteLine(customList);
}
public static TestCases NoCollectionInitializerBecauseOfMissingIEnumerable()
{
TestCases testCases = new TestCases();
testCases.Add("int");
testCases.Add("string");
return testCases;
}
public static void CollectionInitializerWithParamsMethod()
{
X(Y(), new CustomList<int> { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } });
}
public static void CollectionInitializerList()
{
X(Y(), new List<int> { 1, 2, 3 });
}
public static object RecursiveCollectionInitializer()
{
List<object> list = new List<object>();
list.Add(list);
return list;
}
public static void CollectionInitializerDictionary()
{
X(Y(), new Dictionary<string, int> {
{ "First", 1 },
{ "Second", 2 },
{ "Third", 3 }
});
}
public static void CollectionInitializerDictionaryWithEnumTypes()
{
X(Y(), new Dictionary<MyEnum, MyEnum2> {
{
MyEnum.a,
MyEnum2.c
},
{
MyEnum.b,
MyEnum2.d
}
});
}
public static void NotACollectionInitializer()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
X(Y(), list);
}
#if CS60
public static void SimpleDictInitializer()
{
X(Y(), new Data {
MoreData = {
a = MyEnum.a,
[2] = null
}
});
}
public static void MixedObjectAndDictInitializer()
{
X(Y(), new Data {
MoreData = {
a = MyEnum.a,
[GetInt()] = {
a = MyEnum.b,
FieldList = { MyEnum2.c },
[GetInt(), GetString()] = new Data(),
[2] = null
}
}
});
}
private List<List<int>> NestedListWithIndexInitializer(MyEnum myEnum)
{
return new List<List<int>> {
[0] = { 1, 2, 3 },
[1] = { (int)myEnum }
};
}
private void Issue1250_Test2(MyEnum value)
{
X(Y(), new C { [(int)value] = new S((int)value) });
}
private void Issue1250_Test3(int value)
{
X(Y(), new C { [value] = new S(value) });
}
private void Issue1250_Test4(int value)
{
X(Y(), new C { [(object)value] = new S(value) });
}
public static List<KeyValuePair<string, string>> Issue1390(IEnumerable<string> tokens, bool alwaysAllowAdministrators, char wireDelimiter)
{
return new List<KeyValuePair<string, string>> {
{
"tokens",
string.Join(wireDelimiter.ToString(), tokens),
(Func<string, string>)null
},
{
"alwaysAllowAdministrators",
alwaysAllowAdministrators.ToString(),
(Func<string, string>)null
},
{
"delimiter",
wireDelimiter.ToString(),
(Func<string, string>)null
}
};
}
#endif
#endregion
}
} | ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/InitializerTests.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/InitializerTests.cs",
"repo_id": "ILSpy",
"token_count": 11581
} | 214 |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
public static class Switch
{
public class SetProperty
{
public readonly PropertyInfo Property;
public int Set { get; set; }
public SetProperty(PropertyInfo property)
{
Property = property;
}
}
public class ImplicitString
{
private readonly string s;
public ImplicitString(string s)
{
this.s = s;
}
public static implicit operator string(ImplicitString v)
{
return v.s;
}
}
public class ExplicitString
{
private readonly string s;
public ExplicitString(string s)
{
this.s = s;
}
public static explicit operator string(ExplicitString v)
{
return v.s;
}
}
public enum State
{
False,
True,
Null
}
public enum KnownColor
{
DarkBlue,
DarkCyan,
DarkGoldenrod,
DarkGray,
DarkGreen,
DarkKhaki
}
private static char ch1767;
#if !ROSLYN
public static State SwitchOverNullableBool(bool? value)
{
switch (value)
{
case false:
return State.False;
case true:
return State.True;
case null:
return State.Null;
default:
throw new InvalidOperationException();
}
}
#endif
public static bool? SwitchOverNullableEnum(State? state)
{
switch (state)
{
case State.False:
return false;
case State.True:
return true;
case State.Null:
return null;
default:
throw new InvalidOperationException();
}
}
public static string SparseIntegerSwitch(int i)
{
Console.WriteLine("SparseIntegerSwitch: " + i);
switch (i)
{
case -10000000:
return "-10 mln";
case -100:
return "-hundred";
case -1:
return "-1";
case 0:
return "0";
case 1:
return "1";
case 2:
return "2";
case 4:
return "4";
case 100:
return "hundred";
case 10000:
return "ten thousand";
case 10001:
return "ten thousand and one";
case int.MaxValue:
return "int.MaxValue";
default:
return "something else";
}
}
public static void SparseIntegerSwitch2(int i)
{
switch (i)
{
case 4:
case 10:
case 11:
case 13:
case 21:
case 29:
case 33:
case 49:
case 50:
case 55:
Console.WriteLine();
break;
}
}
public static bool SparseIntegerSwitch3(int i)
{
switch (i)
{
case 0:
case 10:
case 11:
case 12:
case 100:
case 101:
case 200:
return true;
default:
return false;
}
}
public static string SwitchOverNullableInt(int? i)
{
switch (i)
{
case null:
return "null";
case 0:
return "zero";
case 5:
return "five";
case 10:
return "ten";
default:
return "large";
}
}
public static string SwitchOverNullableIntNullCaseCombined(int? i)
{
switch (i)
{
case null:
case 0:
return "zero";
case 5:
return "five";
case 10:
return "ten";
default:
return "large";
}
}
public static string SwitchOverNullableIntShifted(int? i)
{
switch (i + 5)
{
case null:
return "null";
case 0:
return "zero";
case 5:
return "five";
case 10:
return "ten";
default:
return "large";
}
}
public static string SwitchOverNullableIntShiftedNullCaseCombined(int? i)
{
switch (i + 5)
{
case null:
case 0:
return "zero";
case 5:
return "five";
case 10:
return "ten";
default:
return "large";
}
}
public static string SwitchOverNullableIntNoNullCase(int? i)
{
switch (i)
{
case 0:
return "zero";
case 5:
return "five";
case 10:
return "ten";
default:
return "other";
}
}
public static string SwitchOverNullableIntNoNullCaseShifted(int? i)
{
switch (i + 5)
{
case 0:
return "zero";
case 5:
return "five";
case 10:
return "ten";
default:
return "other";
}
}
public static void SwitchOverInt(int i)
{
switch (i)
{
case 0:
Console.WriteLine("zero");
break;
case 5:
Console.WriteLine("five");
break;
case 10:
Console.WriteLine("ten");
break;
case 15:
Console.WriteLine("fifteen");
break;
case 20:
Console.WriteLine("twenty");
break;
case 25:
Console.WriteLine("twenty-five");
break;
case 30:
Console.WriteLine("thirty");
break;
}
}
// SwitchDetection.UseCSharpSwitch requires more complex heuristic to identify this when compiled with Roslyn
public static void CompactSwitchOverInt(int i)
{
switch (i)
{
case 0:
case 1:
case 2:
Console.WriteLine("012");
break;
case 3:
Console.WriteLine("3");
break;
default:
Console.WriteLine("default");
break;
}
Console.WriteLine("end");
}
public static string ShortSwitchOverString(string text)
{
Console.WriteLine("ShortSwitchOverString: " + text);
switch (text)
{
case "First case":
return "Text1";
case "Second case":
return "Text2";
case "Third case":
return "Text3";
default:
return "Default";
}
}
public static string ShortSwitchOverStringWithNullCase(string text)
{
Console.WriteLine("ShortSwitchOverStringWithNullCase: " + text);
switch (text)
{
case "First case":
return "Text1";
case "Second case":
return "Text2";
case null:
return "null";
default:
return "Default";
}
}
public static string SwitchOverString1(string text)
{
Console.WriteLine("SwitchOverString1: " + text);
switch (text)
{
case "First case":
return "Text1";
case "Second case":
case "2nd case":
return "Text2";
case "Third case":
return "Text3";
case "Fourth case":
return "Text4";
case "Fifth case":
return "Text5";
case "Sixth case":
return "Text6";
case null:
return null;
default:
return "Default";
}
}
public static string SwitchOverString2()
{
Console.WriteLine("SwitchOverString2:");
switch (Environment.UserName)
{
case "First case":
return "Text1";
case "Second case":
return "Text2";
case "Third case":
return "Text3";
case "Fourth case":
return "Text4";
case "Fifth case":
return "Text5";
case "Sixth case":
return "Text6";
case "Seventh case":
return "Text7";
case "Eighth case":
return "Text8";
case "Ninth case":
return "Text9";
case "Tenth case":
return "Text10";
case "Eleventh case":
return "Text11";
default:
return "Default";
}
}
public static string SwitchOverImplicitString(ImplicitString s)
{
// we emit an explicit cast, because the rules used by the C# compiler are counter-intuitive:
// The C# compiler does *not* take the type of the switch labels into account at all.
switch ((string)s)
{
case "First case":
return "Text1";
case "Second case":
return "Text2";
case "Third case":
return "Text3";
case "Fourth case":
return "Text4";
case "Fifth case":
return "Text5";
case "Sixth case":
return "Text6";
case "Seventh case":
return "Text7";
case "Eighth case":
return "Text8";
case "Ninth case":
return "Text9";
case "Tenth case":
return "Text10";
case "Eleventh case":
return "Text11";
default:
return "Default";
}
}
public static string SwitchOverExplicitString(ExplicitString s)
{
switch ((string)s)
{
case "First case":
return "Text1";
case "Second case":
return "Text2";
case "Third case":
return "Text3";
case "Fourth case":
return "Text4";
case "Fifth case":
return "Text5";
case "Sixth case":
return "Text6";
case "Seventh case":
return "Text7";
case "Eighth case":
return "Text8";
case "Ninth case":
return "Text9";
case "Tenth case":
return "Text10";
case "Eleventh case":
return "Text11";
default:
return "Default";
}
}
#if !ROSLYN
public static string SwitchOverBool(bool b)
{
Console.WriteLine("SwitchOverBool: " + b);
switch (b)
{
case true:
return bool.TrueString;
case false:
return bool.FalseString;
default:
return null;
}
}
#endif
public static void SwitchInLoop(int i)
{
Console.WriteLine("SwitchInLoop: " + i);
while (true)
{
switch (i)
{
case 1:
Console.WriteLine("one");
break;
case 2:
Console.WriteLine("two");
break;
//case 3:
// Console.WriteLine("three");
// continue;
case 4:
Console.WriteLine("four");
return;
default:
Console.WriteLine("default");
Console.WriteLine("more code");
return;
}
i++;
}
}
public static void SwitchWithGoto(int i)
{
Console.WriteLine("SwitchWithGoto: " + i);
switch (i)
{
case 1:
Console.WriteLine("one");
goto default;
case 2:
Console.WriteLine("two");
goto case 3;
case 3:
Console.WriteLine("three");
break;
case 4:
Console.WriteLine("four");
return;
default:
Console.WriteLine("default");
break;
}
Console.WriteLine("End of method");
}
// Needs to be long enough to generate a hashtable
public static void SwitchWithGotoString(string s)
{
Console.WriteLine("SwitchWithGotoString: " + s);
switch (s)
{
case "1":
Console.WriteLine("one");
goto default;
case "2":
Console.WriteLine("two");
goto case "3";
case "3":
Console.WriteLine("three");
break;
case "4":
Console.WriteLine("four");
return;
case "5":
Console.WriteLine("five");
return;
case "6":
Console.WriteLine("six");
return;
case "7":
Console.WriteLine("seven");
return;
case "8":
Console.WriteLine("eight");
return;
case "9":
Console.WriteLine("nine");
return;
default:
Console.WriteLine("default");
break;
}
Console.WriteLine("End of method");
}
public static void SwitchWithGotoComplex(string s)
{
Console.WriteLine("SwitchWithGotoComplex: " + s);
switch (s)
{
case "1":
Console.WriteLine("one");
goto case "8";
case "2":
Console.WriteLine("two");
goto case "3";
case "3":
Console.WriteLine("three");
if (s.Length != 2)
{
break;
}
goto case "5";
case "4":
Console.WriteLine("four");
goto case "5";
case "5":
Console.WriteLine("five");
goto case "8";
case "6":
Console.WriteLine("six");
goto case "5";
case "8":
Console.WriteLine("eight");
return;
// add a default case so that case "7": isn't redundant
default:
Console.WriteLine("default");
break;
// note that goto case "7" will decompile as break;
// cases with a single break have the highest IL offset and are moved to the bottom
case "7":
break;
}
Console.WriteLine("End of method");
}
private static SetProperty[] GetProperties()
{
return new SetProperty[0];
}
public static void SwitchOnStringInForLoop()
{
List<SetProperty> list = new List<SetProperty>();
List<SetProperty> list2 = new List<SetProperty>();
SetProperty[] properties = GetProperties();
for (int i = 0; i < properties.Length; i++)
{
Console.WriteLine("In for-loop");
SetProperty setProperty = properties[i];
switch (setProperty.Property.Name)
{
case "Name1":
setProperty.Set = 1;
list.Add(setProperty);
break;
case "Name2":
setProperty.Set = 2;
list.Add(setProperty);
break;
case "Name3":
setProperty.Set = 3;
list.Add(setProperty);
break;
case "Name4":
setProperty.Set = 4;
list.Add(setProperty);
break;
case "Name5":
case "Name6":
list.Add(setProperty);
break;
default:
list2.Add(setProperty);
break;
}
}
}
public static void SwitchInTryBlock(string value)
{
try
{
switch (value.Substring(5))
{
case "Name1":
Console.WriteLine("1");
break;
case "Name2":
Console.WriteLine("Name_2");
break;
case "Name3":
Console.WriteLine("Name_3");
break;
case "Name4":
Console.WriteLine("No. 4");
break;
case "Name5":
case "Name6":
Console.WriteLine("5+6");
break;
default:
Console.WriteLine("default");
break;
}
}
catch (Exception)
{
Console.WriteLine("catch block");
}
}
public static void SwitchWithComplexCondition(string[] args)
{
switch ((args.Length == 0) ? "dummy" : args[0])
{
case "a":
Console.WriteLine("a");
break;
case "b":
Console.WriteLine("b");
break;
case "c":
Console.WriteLine("c");
break;
case "d":
Console.WriteLine("d");
break;
}
Console.WriteLine("end");
}
public static void SwitchWithArray(string[] args)
{
switch (args[0])
{
case "a":
Console.WriteLine("a");
break;
case "b":
Console.WriteLine("b");
break;
case "c":
Console.WriteLine("c");
break;
case "d":
Console.WriteLine("d");
break;
}
Console.WriteLine("end");
}
public static void SwitchWithContinue1(int i, bool b)
{
while (true)
{
switch (i)
{
#if OPT
case 1:
continue;
#endif
case 0:
if (b)
{
continue;
}
break;
case 2:
if (!b)
{
continue;
}
break;
#if !OPT
case 1:
continue;
#endif
}
Console.WriteLine();
}
}
// while condition, return and break cases
public static void SwitchWithContinue2(int i, bool b)
{
while (i < 10)
{
switch (i)
{
case 0:
if (b)
{
Console.WriteLine("0b");
continue;
}
Console.WriteLine("0!b");
break;
case 2:
#if OPT
if (b)
{
Console.WriteLine("2b");
return;
}
Console.WriteLine("2!b");
continue;
#else
if (!b)
{
Console.WriteLine("2!b");
continue;
}
Console.WriteLine("2b");
return;
#endif
default:
Console.WriteLine("default");
break;
case 3:
break;
case 1:
continue;
}
Console.WriteLine("loop-tail");
i++;
}
}
// for loop version
public static void SwitchWithContinue3(bool b)
{
for (int i = 0; i < 10; i++)
{
switch (i)
{
case 0:
if (b)
{
Console.WriteLine("0b");
continue;
}
Console.WriteLine("0!b");
break;
case 2:
#if OPT
if (b)
{
Console.WriteLine("2b");
return;
}
Console.WriteLine("2!b");
continue;
#else
if (!b)
{
Console.WriteLine("2!b");
continue;
}
Console.WriteLine("2b");
return;
#endif
default:
Console.WriteLine("default");
break;
case 3:
break;
case 1:
continue;
}
Console.WriteLine("loop-tail");
}
}
// foreach version
public static void SwitchWithContinue4(bool b)
{
foreach (int item in Enumerable.Range(0, 10))
{
Console.WriteLine("loop: " + item);
switch (item)
{
case 1:
if (b)
{
continue;
}
break;
case 3:
if (!b)
{
continue;
}
return;
case 4:
Console.WriteLine(4);
goto case 7;
case 5:
Console.WriteLine(5);
goto default;
case 6:
if (b)
{
continue;
}
goto case 3;
case 7:
if (item % 2 == 0)
{
goto case 3;
}
if (!b)
{
continue;
}
goto case 8;
case 8:
if (b)
{
continue;
}
goto case 5;
default:
Console.WriteLine("default");
break;
case 2:
continue;
}
Console.WriteLine("break: " + item);
}
}
// internal if statement, loop increment block not dominated by the switch head
public static void SwitchWithContinue5(bool b)
{
for (int i = 0; i < 10; i++)
{
if (i < 5)
{
switch (i)
{
case 0:
if (b)
{
Console.WriteLine("0b");
continue;
}
Console.WriteLine("0!b");
break;
case 2:
#if OPT
if (b)
{
Console.WriteLine("2b");
return;
}
Console.WriteLine("2!b");
continue;
#else
if (!b)
{
Console.WriteLine("2!b");
continue;
}
Console.WriteLine("2b");
return;
#endif
default:
Console.WriteLine("default");
break;
case 3:
break;
case 1:
continue;
}
Console.WriteLine("break-target");
}
Console.WriteLine("loop-tail");
}
}
// do-while loop version
public static void SwitchWithContinue6(int i, bool b)
{
do
{
switch (i)
{
case 0:
if (!b)
{
Console.WriteLine("0!b");
break;
}
Console.WriteLine("0b");
// ConditionDetection doesn't recognise Do-While continues yet
continue;
case 2:
if (b)
{
Console.WriteLine("2b");
return;
}
Console.WriteLine("2!b");
continue;
default:
Console.WriteLine("default");
break;
case 3:
break;
case 1:
continue;
}
Console.WriteLine("loop-tail");
} while (++i < 10);
}
// double break from switch to loop exit requires additional pattern matching in HighLevelLoopTransform
public static void SwitchWithContinue7()
{
for (int num = 0; num >= 0; num--)
{
Console.WriteLine("loop-head");
switch (num)
{
default:
Console.WriteLine("default");
break;
case 0:
continue;
case 1:
break;
}
break;
}
Console.WriteLine("end");
}
public static void SwitchWithContinueInDoubleLoop()
{
bool value = false;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
switch (i + j)
{
case 1:
case 3:
case 5:
case 7:
case 11:
case 13:
case 17:
break;
default:
continue;
}
value = true;
break;
}
}
Console.WriteLine(value);
}
public static void SwitchLoopNesting()
{
for (int i = 0; i < 10; i++)
{
switch (i)
{
case 0:
Console.WriteLine(0);
break;
case 1:
Console.WriteLine(1);
break;
default:
if (i % 2 == 0)
{
while (i % 3 != 0)
{
Console.WriteLine(i++);
}
}
Console.WriteLine();
break;
}
if (i > 4)
{
Console.WriteLine("high");
}
else
{
Console.WriteLine("low");
}
}
}
// These decompile poorly into switch statements and should be left as is
#region Overagressive Switch Use
#if ROSLYN || OPT
public static void SingleIf1(int i, bool a)
{
if (i == 1 || (i == 2 && a))
{
Console.WriteLine(1);
}
Console.WriteLine(2);
}
#endif
public static void SingleIf2(int i, bool a, bool b)
{
if (i == 1 || (i == 2 && a) || (i == 3 && b))
{
Console.WriteLine(1);
}
Console.WriteLine(2);
}
public static void SingleIf3(int i, bool a, bool b)
{
if (a || i == 1 || (i == 2 && b))
{
Console.WriteLine(1);
}
Console.WriteLine(2);
}
public static void SingleIf4(int i, bool a)
{
if (i == 1 || i == 2 || (i != 3 && a) || i != 4)
{
Console.WriteLine(1);
}
Console.WriteLine(2);
}
public static void NestedIf(int i)
{
if (i != 1)
{
if (i == 2)
{
Console.WriteLine(2);
}
Console.WriteLine("default");
}
Console.WriteLine();
}
public static void IfChainWithCondition(int i)
{
if (i == 0)
{
Console.WriteLine(0);
}
else if (i == 1)
{
Console.WriteLine(1);
}
else if (i == 2)
{
Console.WriteLine(2);
}
else if (i == 3)
{
Console.WriteLine(3);
}
else if (i == 4)
{
Console.WriteLine(4);
}
else if (i == 5 && Console.CapsLock)
{
Console.WriteLine("5A");
}
else
{
Console.WriteLine("default");
}
Console.WriteLine();
}
public static bool SwitchlikeIf(int i, int j)
{
if (i != 0 && j != 0)
{
if (i == -1 && j == -1)
{
Console.WriteLine("-1, -1");
}
if (i == -1 && j == 1)
{
Console.WriteLine("-1, 1");
}
if (i == 1 && j == -1)
{
Console.WriteLine("1, -1");
}
if (i == 1 && j == 1)
{
Console.WriteLine("1, 1");
}
return false;
}
if (i != 0)
{
if (i == -1)
{
Console.WriteLine("-1, 0");
}
if (i == 1)
{
Console.WriteLine("1, 0");
}
return false;
}
if (j != 0)
{
if (j == -1)
{
Console.WriteLine("0, -1");
}
if (j == 1)
{
Console.WriteLine("0, 1");
}
return false;
}
return true;
}
public static bool SwitchlikeIf2(int i)
{
if (i != 0)
{
// note that using else-if in this chain creates a nice-looking switch here (as expected)
if (i == 1)
{
Console.WriteLine(1);
}
if (i == 2)
{
Console.WriteLine(2);
}
if (i == 3)
{
Console.WriteLine(3);
}
return false;
}
return false;
}
public static void SingleIntervalIf(char c)
{
if (c >= 'A' && c <= 'Z')
{
Console.WriteLine("alphabet");
}
Console.WriteLine("end");
}
public static bool Loop8(char c, bool b, Func<char> getChar)
{
if (b)
{
while ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
c = getChar();
}
}
return true;
}
public static void Loop9(Func<char> getChar)
{
char c;
do
{
c = getChar();
} while (c != -1 && c != '\n' && c != '\u2028' && c != '\u2029');
}
#endregion
// Ensure correctness of SwitchDetection.UseCSharpSwitch control flow heuristics
public static void SwitchWithBreakCase(int i, bool b)
{
if (b)
{
switch (i)
{
case 1:
Console.WriteLine(1);
break;
default:
Console.WriteLine("default");
break;
case 2:
break;
}
Console.WriteLine("b");
}
Console.WriteLine("end");
}
public static void SwitchWithReturnAndBreak(int i, bool b)
{
switch (i)
{
case 0:
if (b)
{
return;
}
break;
case 1:
if (!b)
{
return;
}
break;
}
Console.WriteLine();
}
public static int SwitchWithReturnAndBreak2(int i, bool b)
{
switch (i)
{
case 4:
case 33:
Console.WriteLine();
return 1;
case 334:
if (b)
{
return 2;
}
break;
case 395:
case 410:
case 455:
Console.WriteLine();
break;
}
Console.WriteLine();
return 0;
}
public static void SwitchWithReturnAndBreak3(int i)
{
switch (i)
{
default:
return;
case 0:
Console.WriteLine(0);
break;
case 1:
Console.WriteLine(1);
break;
}
Console.WriteLine();
}
public static string Issue1621(int x)
{
if (x == 5)
{
return "5";
}
switch (x)
{
case 1:
return "1";
case 2:
case 6:
case 7:
return "2-6-7";
case 3:
return "3";
case 4:
return "4";
case 5:
return "unreachable";
default:
throw new Exception();
}
}
public static int Issue1602(string x)
{
switch (x)
{
case null:
return 0;
case "":
return -1;
case "A":
return 65;
case "B":
return 66;
case "C":
return 67;
case "D":
return 68;
case "E":
return 69;
case "F":
return 70;
default:
throw new ArgumentOutOfRangeException();
}
}
public static void Issue1745(string aaa)
{
switch (aaa)
{
case "a":
case "b":
case "c":
case "d":
case "e":
case "f":
Console.WriteLine(aaa);
break;
case null:
Console.WriteLine("<null>");
break;
case "":
Console.WriteLine("<empty>");
break;
}
}
public static bool DoNotRemoveAssignmentBeforeSwitch(string x, out ConsoleKey key)
{
#if NET40 || !ROSLYN
key = (ConsoleKey)0;
#else
key = ConsoleKey.None;
#endif
switch (x)
{
case "A":
key = ConsoleKey.A;
break;
case "B":
key = ConsoleKey.B;
break;
case "C":
key = ConsoleKey.C;
break;
}
#if NET40 || !ROSLYN
return key != (ConsoleKey)0;
#else
return key != ConsoleKey.None;
#endif
}
public static void Issue1767(string s)
{
switch (s)
{
case "a":
ch1767 = s[0];
break;
case "b":
ch1767 = s[0];
break;
case "c":
ch1767 = s[0];
break;
case "d":
ch1767 = s[0];
break;
case "e":
ch1767 = s[0];
break;
case "f":
ch1767 = s[0];
break;
}
}
public static void Issue2763(int value)
{
switch ((KnownColor)value)
{
case KnownColor.DarkBlue:
Console.WriteLine("DarkBlue");
break;
case KnownColor.DarkCyan:
Console.WriteLine("DarkCyan");
break;
case KnownColor.DarkGoldenrod:
Console.WriteLine("DarkGoldenrod");
break;
case KnownColor.DarkGray:
Console.WriteLine("DarkGray");
break;
case KnownColor.DarkGreen:
Console.WriteLine("DarkGreen");
break;
case KnownColor.DarkKhaki:
Console.WriteLine("DarkKhaki");
break;
}
}
#if CS110 && NET70
public static string SwitchOverReadOnlySpanChar1(ReadOnlySpan<char> text)
{
Console.WriteLine("SwitchOverReadOnlySpanChar1:");
switch (text)
{
case "First case":
return "Text1";
case "Second case":
case "2nd case":
return "Text2";
case "Third case":
return "Text3";
case "Fourth case":
return "Text4";
case "Fifth case":
return "Text5";
case "Sixth case":
return "Text6";
default:
return "Default";
}
}
public static string SwitchOverSpanChar1(Span<char> text)
{
Console.WriteLine("SwitchOverSpanChar1:");
switch (text)
{
case "First case":
return "Text1";
case "Second case":
case "2nd case":
return "Text2";
case "Third case":
return "Text3";
case "Fourth case":
return "Text4";
case "Fifth case":
return "Text5";
case "Sixth case":
return "Text6";
default:
return "Default";
}
}
#endif
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/Switch.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/Switch.cs",
"repo_id": "ILSpy",
"token_count": 14000
} | 215 |
using System;
namespace ICSharpCode.Decompiler.Tests.TestCases.Ugly
{
public class DisplayClass
{
public Program thisField;
public int field1;
public string field2;
}
public class NestedDisplayClass
{
public DisplayClass field3;
public int field1;
public string field2;
}
public class Program
{
public int Rand()
{
throw new NotImplementedException();
}
public void Test1()
{
int field1 = 42;
string field2 = "Hello World!";
Console.WriteLine("{0} {1}", field1, field2);
}
public void Test2()
{
DisplayClass displayClass = new DisplayClass {
field1 = 42,
field2 = "Hello World!"
};
Console.WriteLine("{0} {1}", displayClass.field1, displayClass.GetHashCode());
}
public void Test3()
{
DisplayClass displayClass = new DisplayClass {
field1 = 42,
field2 = "Hello World!"
};
Console.WriteLine("{0} {1}", displayClass.field1, displayClass);
}
public void Test4()
{
DisplayClass displayClass = new DisplayClass {
thisField = this,
field1 = 42,
field2 = "Hello World!"
};
int field1 = 4711;
string field2 = "ILSpy";
DisplayClass field3;
if (displayClass.field1 > 100)
{
field3 = displayClass;
}
else
{
field3 = null;
}
Console.WriteLine("{0} {1}", displayClass, field3);
}
public void Test5()
{
DisplayClass displayClass = new DisplayClass {
thisField = this,
field1 = 42,
field2 = "Hello World!"
};
int field1 = 4711;
string field2 = "ILSpy";
DisplayClass field3;
if (displayClass.field1 > 100)
{
field3 = displayClass;
}
else
{
field3 = null;
}
Console.WriteLine("{0} {1}", field2 + field1, field3);
}
public void Issue1898(int i)
{
DisplayClass displayClass = new DisplayClass {
thisField = this,
field1 = i
};
int field1 = default(int);
string field2 = default(string);
DisplayClass field3 = default(DisplayClass);
while (true)
{
switch (Rand())
{
case 1:
field1 = Rand();
continue;
case 2:
field2 = Rand().ToString();
continue;
case 3:
field3 = displayClass;
continue;
}
Console.WriteLine(field1);
Console.WriteLine(field2);
Console.WriteLine(field3);
}
}
public void Test6(int i)
{
int field1 = i;
string field2 = "Hello World!";
if (i < 0)
{
i = -i;
}
Console.WriteLine("{0} {1}", field1, field2);
}
public void Test6b(int i)
{
int num = i;
int field1 = num;
string field2 = "Hello World!";
if (num < 0)
{
num = -num;
}
Console.WriteLine("{0} {1}", field1, field2);
}
public void Test7(int i)
{
int field1 = i;
string field2 = "Hello World!";
Console.WriteLine("{0} {1} {2}", field1++, field2, i);
}
public void Test8(int i)
{
int field1 = i;
string field2 = "Hello World!";
i = 42;
Console.WriteLine("{0} {1}", field1, field2);
}
public void Test8b(int i)
{
int num = i;
int field1 = num;
string field2 = "Hello World!";
num = 42;
Console.WriteLine("{0} {1}", field1, field2);
}
// public void Test9()
// {
// Program thisField = this;
// int field1 = 1;
// string field2 = "Hello World!";
// thisField = new Program();
// Console.WriteLine("{0} {1}", this, thisField);
// }
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/AggressiveScalarReplacementOfAggregates.Expected.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/AggressiveScalarReplacementOfAggregates.Expected.cs",
"repo_id": "ILSpy",
"token_count": 1524
} | 216 |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace ICSharpCode.Decompiler.Tests.TestCases.Ugly
{
public sealed class Handle
{
private readonly Func<int> _func;
public Handle(Func<int> func)
{
_func = func;
}
}
public static class NoLocalFunctions
{
[StructLayout(LayoutKind.Auto)]
[CompilerGenerated]
private struct _003C_003Ec__DisplayClass1_0
{
public int x;
}
[CompilerGenerated]
private sealed class _003C_003Ec__DisplayClass2_0
{
public int x;
internal int _003CSimpleCaptureWithRef_003Eg__F_007C0()
{
return 42 + x;
}
}
private static void UseLocalFunctionReference()
{
#if OPT
new Handle(new Func<int>(_003CUseLocalFunctionReference_003Eg__F_007C0_0));
#else
Handle handle = new Handle(new Func<int>(_003CUseLocalFunctionReference_003Eg__F_007C0_0));
#endif
}
private static void SimpleCapture()
{
_003C_003Ec__DisplayClass1_0 A_ = default(_003C_003Ec__DisplayClass1_0);
A_.x = 1;
_003CSimpleCapture_003Eg__F_007C1_0(ref A_);
}
private static void SimpleCaptureWithRef()
{
_003C_003Ec__DisplayClass2_0 _003C_003Ec__DisplayClass2_ = new _003C_003Ec__DisplayClass2_0();
_003C_003Ec__DisplayClass2_.x = 1;
#if OPT
new Handle(new Func<int>(_003C_003Ec__DisplayClass2_._003CSimpleCaptureWithRef_003Eg__F_007C0));
#else
Handle handle = new Handle(new Func<int>(_003C_003Ec__DisplayClass2_._003CSimpleCaptureWithRef_003Eg__F_007C0));
#endif
}
[CompilerGenerated]
internal static int _003CUseLocalFunctionReference_003Eg__F_007C0_0()
{
return 42;
}
[CompilerGenerated]
private static int _003CSimpleCapture_003Eg__F_007C1_0(ref _003C_003Ec__DisplayClass1_0 A_0)
{
return 42 + A_0.x;
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoLocalFunctions.Expected.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoLocalFunctions.Expected.cs",
"repo_id": "ILSpy",
"token_count": 752
} | 217 |
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Namespace ICSharpCode.Decompiler.Tests.TestCases.VBPretty
Public Class Async
Private memberField As Integer
Private Shared Function [True]() As Boolean
Return True
End Function
Public Async Sub SimpleVoidMethod()
Console.WriteLine("Before")
Await Task.Delay(TimeSpan.FromSeconds(1.0))
Console.WriteLine("After")
End Sub
Public Async Sub VoidMethodWithoutAwait()
Console.WriteLine("No Await")
End Sub
Public Async Sub EmptyVoidMethod()
End Sub
Public Async Sub AwaitYield()
Await Task.Yield()
End Sub
Public Async Sub AwaitDefaultYieldAwaitable()
Await CType(Nothing, YieldAwaitable)
End Sub
Public Async Sub AwaitDefaultHopToThreadPool()
' unlike YieldAwaitable which implements ICriticalNotifyCompletion,
' the HopToThreadPoolAwaitable struct only implements
' INotifyCompletion, so this results in different codegen
Await CType(Nothing, HopToThreadPoolAwaitable)
End Sub
Public Async Function SimpleVoidTaskMethod() As Task
Console.WriteLine("Before")
Await Task.Delay(TimeSpan.FromSeconds(1.0))
Console.WriteLine("After")
End Function
Public Async Function TaskMethodWithoutAwait() As Task
Console.WriteLine("No Await")
End Function
Public Async Function CapturingThis() As Task
Await Task.Delay(memberField)
End Function
Public Async Function CapturingThisWithoutAwait() As Task
Console.WriteLine(memberField)
End Function
Public Async Function SimpleBoolTaskMethod() As Task(Of Boolean)
Console.WriteLine("Before")
Await Task.Delay(TimeSpan.FromSeconds(1.0))
Console.WriteLine("After")
Return True
End Function
Public Async Sub TwoAwaitsWithDifferentAwaiterTypes()
Console.WriteLine("Before")
If Await SimpleBoolTaskMethod() Then
Await Task.Delay(TimeSpan.FromSeconds(1.0))
End If
Console.WriteLine("After")
End Sub
Public Async Sub AwaitInLoopCondition()
While Await SimpleBoolTaskMethod()
Console.WriteLine("Body")
End While
End Sub
Public Async Function Issue2366a() As Task
While True
Try
Await Task.CompletedTask
Catch
End Try
End While
End Function
Public Shared Async Function GetIntegerSumAsync(ByVal items As IEnumerable(Of Integer)) As Task(Of Integer)
Await Task.Delay(100)
Dim num = 0
For Each item In items
num += item
Next
Return num
End Function
Public Async Function AsyncCatch(ByVal b As Boolean, ByVal task1 As Task(Of Integer), ByVal task2 As Task(Of Integer)) As Task
Try
Console.WriteLine("Start try")
Await task1
Console.WriteLine("End try")
Catch ex As Exception
Console.WriteLine("No await")
End Try
End Function
Public Async Function AsyncCatchThrow(ByVal b As Boolean, ByVal task1 As Task(Of Integer), ByVal task2 As Task(Of Integer)) As Task
Try
Console.WriteLine("Start try")
Await task1
Console.WriteLine("End try")
Catch ex As Exception
Console.WriteLine("No await")
Throw
End Try
End Function
Public Async Function AsyncFinally(ByVal b As Boolean, ByVal task1 As Task(Of Integer), ByVal task2 As Task(Of Integer)) As Task
Try
Console.WriteLine("Start try")
Await task1
Console.WriteLine("End try")
Finally
Console.WriteLine("No await")
End Try
End Function
Public Shared Async Function AlwaysThrow() As Task
Throw New Exception
End Function
Public Shared Async Function InfiniteLoop() As Task
While True
End While
End Function
Public Shared Async Function InfiniteLoopWithAwait() As Task
While True
Await Task.Delay(10)
End While
End Function
Public Async Function AsyncWithLocalVar() As Task
Dim a As Object = New Object()
Await UseObj(a)
Await UseObj(a)
End Function
Public Shared Async Function UseObj(ByVal a As Object) As Task
End Function
End Class
Public Structure AsyncInStruct
Private i As Integer
Public Async Function Test(ByVal xx As AsyncInStruct) As Task(Of Integer)
xx.i += 1
i += 1
Await Task.Yield()
Return i + xx.i
End Function
End Structure
Public Structure HopToThreadPoolAwaitable
Implements INotifyCompletion
Public Property IsCompleted As Boolean
Public Function GetAwaiter() As HopToThreadPoolAwaitable
Return Me
End Function
Public Sub OnCompleted(ByVal continuation As Action) Implements INotifyCompletion.OnCompleted
Task.Run(continuation)
End Sub
Public Sub GetResult()
End Sub
End Structure
End Namespace
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Async.vb/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Async.vb",
"repo_id": "ILSpy",
"token_count": 1894
} | 218 |
Imports System
Imports System.Collections.Generic
Namespace ICSharpCode.Decompiler.Tests.TestCases.VBPretty
Friend Structure StructWithYieldReturn
Private val As Integer
Public Iterator Function Count() As IEnumerable(Of Integer)
Yield val
Yield val
End Function
End Structure
Public Class YieldReturnPrettyTest
Private fieldOnThis As Integer
Public Shared ReadOnly Iterator Property YieldChars As IEnumerable(Of Char)
Get
Yield "a"c
Yield "b"c
Yield "c"c
End Get
End Property
Friend Shared Sub Print(Of T)(ByVal name As String, ByVal enumerator As IEnumerator(Of T))
Console.WriteLine(name + ": Test start")
While enumerator.MoveNext()
Console.WriteLine(name + ": " + enumerator.Current.ToString())
End While
End Sub
Public Shared Iterator Function SimpleYieldReturn() As IEnumerable(Of String)
Yield "A"
Yield "B"
Yield "C"
End Function
Public Shared Iterator Function SimpleYieldReturnEnumerator() As IEnumerator(Of String)
Yield "A"
Yield "B"
Yield "C"
End Function
Public Iterator Function YieldReturnParameters(ByVal p As Integer) As IEnumerable(Of Integer)
Yield p
Yield fieldOnThis
End Function
Public Iterator Function YieldReturnParametersEnumerator(ByVal p As Integer) As IEnumerator(Of Integer)
Yield p
Yield fieldOnThis
End Function
Public Shared Iterator Function YieldReturnInLoop() As IEnumerable(Of Integer)
For i = 0 To 99
Yield i
Next
End Function
Public Shared Iterator Function YieldReturnWithTryFinally() As IEnumerable(Of Integer)
Yield 0
Try
Yield 1
Finally
Console.WriteLine("Finally!")
End Try
Yield 2
End Function
Public Shared Iterator Function YieldReturnWithNestedTryFinally(ByVal breakInMiddle As Boolean) As IEnumerable(Of String)
Console.WriteLine("Start of method - 1")
Yield "Start of method"
Console.WriteLine("Start of method - 2")
Try
Console.WriteLine("Within outer try - 1")
Yield "Within outer try"
Console.WriteLine("Within outer try - 2")
Try
Console.WriteLine("Within inner try - 1")
Yield "Within inner try"
Console.WriteLine("Within inner try - 2")
If breakInMiddle Then
Console.WriteLine("Breaking...")
Return
End If
Console.WriteLine("End of inner try - 1")
Yield "End of inner try"
Console.WriteLine("End of inner try - 2")
Finally
Console.WriteLine("Inner Finally")
End Try
Console.WriteLine("End of outer try - 1")
Yield "End of outer try"
Console.WriteLine("End of outer try - 2")
Finally
Console.WriteLine("Outer Finally")
End Try
Console.WriteLine("End of method - 1")
Yield "End of method"
Console.WriteLine("End of method - 2")
End Function
Public Shared Iterator Function YieldReturnWithTwoNonNestedFinallyBlocks(ByVal input As IEnumerable(Of String)) As IEnumerable(Of String)
' outer try-finally block
For Each line In input
' nested try-finally block
Try
Yield line
Finally
Console.WriteLine("Processed " & line)
End Try
Next
Yield "A"
Yield "B"
Yield "C"
Yield "D"
Yield "E"
Yield "F"
' outer try-finally block
For Each item In input
Yield item.ToUpper()
Next
End Function
Public Shared Iterator Function GetEvenNumbers(ByVal n As Integer) As IEnumerable(Of Integer)
For i = 0 To n - 1
If i Mod 2 = 0 Then
Yield i
End If
Next
End Function
Public Shared Iterator Function ExceptionHandling() As IEnumerable(Of Char)
Yield "a"c
Try
Console.WriteLine("1 - try")
Catch __unusedException1__ As Exception
Console.WriteLine("1 - catch")
End Try
Yield "b"c
Try
Try
Console.WriteLine("2 - try")
Finally
Console.WriteLine("2 - finally")
End Try
Yield "c"c
Finally
Console.WriteLine("outer finally")
End Try
End Function
Public Shared Iterator Function YieldBreakInCatch() As IEnumerable(Of Integer)
Yield 0
Try
Console.WriteLine("In Try")
Catch
' yield return is not allowed in catch, but yield break is
Return
End Try
Yield 1
End Function
Public Shared Iterator Function YieldBreakInCatchInTryFinally() As IEnumerable(Of Integer)
Try
Yield 0
Try
Console.WriteLine("In Try")
Catch
' yield return is not allowed in catch, but yield break is
' Note that pre-roslyn, this code triggers a compiler bug:
' If the finally block throws an exception, it ends up getting
' called a second time.
Return
End Try
Yield 1
Finally
Console.WriteLine("Finally")
End Try
End Function
Public Shared Iterator Function YieldBreakInTryCatchInTryFinally() As IEnumerable(Of Integer)
Try
Yield 0
Try
Console.WriteLine("In Try")
' same compiler bug as in YieldBreakInCatchInTryFinally
Return
Catch
Console.WriteLine("Catch")
End Try
Yield 1
Finally
Console.WriteLine("Finally")
End Try
End Function
Public Shared Iterator Function YieldBreakInTryFinallyInTryFinally(ByVal b As Boolean) As IEnumerable(Of Integer)
Try
Yield 0
Try
Console.WriteLine("In Try")
If b Then
' same compiler bug as in YieldBreakInCatchInTryFinally
Return
End If
Finally
Console.WriteLine("Inner Finally")
End Try
Yield 1
Finally
Console.WriteLine("Finally")
End Try
End Function
Public Shared Iterator Function YieldBreakOnly() As IEnumerable(Of Integer)
Return
End Function
Public Shared Iterator Function UnconditionalThrowInTryFinally() As IEnumerable(Of Integer)
' Here, MoveNext() doesn't call the finally methods at all
' (only indirectly via Dispose())
Try
Yield 0
Throw New NotImplementedException()
Finally
Console.WriteLine("Finally")
End Try
End Function
Public Shared Iterator Function NestedTryFinallyStartingOnSamePosition() As IEnumerable(Of Integer)
' The first user IL instruction is already in 2 nested try blocks.
Try
Try
Yield 0
Finally
Console.WriteLine("Inner Finally")
End Try
Finally
Console.WriteLine("Outer Finally")
End Try
End Function
#If ROSLYN Then
Public Shared Iterator Function LocalInFinally(Of T As IDisposable)(ByVal a As T) As IEnumerable(Of Integer)
Yield 1
Try
Yield 2
Finally
Dim val = a
val.Dispose()
val.Dispose()
End Try
Yield 3
End Function
#End If
Public Shared Iterator Function GenericYield(Of T As New)() As IEnumerable(Of T)
Dim val As T = New T()
For i = 0 To 2
Yield val
Next
End Function
Public Shared Iterator Function MultipleYieldBreakInTryFinally(ByVal i As Integer) As IEnumerable(Of Integer)
Try
If i = 2 Then
Return
End If
While i < 40
If i Mod 2 = 0 Then
Return
End If
i += 1
Yield i
End While
Finally
Console.WriteLine("finally")
End Try
Console.WriteLine("normal exit")
End Function
Friend Iterator Function ForLoopWithYieldReturn(ByVal [end] As Integer, ByVal evil As Integer) As IEnumerable(Of Integer)
' This loop needs to pick the implicit "yield break;" as exit point
' in order to produce pretty code; not the "throw" which would
' be a less-pretty option.
For i = 0 To [end] - 1
If i = evil Then
Throw New InvalidOperationException("Found evil number")
End If
Yield i
Next
End Function
End Class
End Namespace
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/YieldReturn.vb/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/YieldReturn.vb",
"repo_id": "ILSpy",
"token_count": 4217
} | 219 |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ICSharpCode.Decompiler.CSharp.Resolver;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.IL.Transforms;
using ICSharpCode.Decompiler.Semantics;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.CSharp
{
struct CallBuilder
{
struct ExpectedTargetDetails
{
public OpCode CallOpCode;
public bool NeedsBoxingConversion;
}
struct ArgumentList
{
public TranslatedExpression[] Arguments;
public IParameter[] ExpectedParameters;
public string[] ParameterNames;
public string[] ArgumentNames;
public int FirstOptionalArgumentIndex;
public BitSet IsPrimitiveValue;
public IReadOnlyList<int> ArgumentToParameterMap;
public bool AddNamesToPrimitiveValues;
public bool UseImplicitlyTypedOut;
public bool IsExpandedForm;
public int Length => Arguments.Length;
private int GetActualArgumentCount()
{
if (FirstOptionalArgumentIndex < 0)
return Arguments.Length;
return FirstOptionalArgumentIndex;
}
public IList<ResolveResult> GetArgumentResolveResults(int skipCount = 0)
{
var expectedParameters = ExpectedParameters;
var useImplicitlyTypedOut = UseImplicitlyTypedOut;
return Arguments
.SelectWithIndex(GetResolveResult)
.Skip(skipCount)
.Take(GetActualArgumentCount())
.ToArray();
ResolveResult GetResolveResult(int index, TranslatedExpression expression)
{
var param = expectedParameters[index];
if (useImplicitlyTypedOut && param.IsOut && expression.Type is ByReferenceType brt)
return new OutVarResolveResult(brt.ElementType);
return expression.ResolveResult;
}
}
public IList<ResolveResult> GetArgumentResolveResultsDirect(int skipCount = 0)
{
return Arguments
.Skip(skipCount)
.Take(GetActualArgumentCount())
.Select(a => a.ResolveResult)
.ToArray();
}
public IEnumerable<Expression> GetArgumentExpressions(int skipCount = 0)
{
if (AddNamesToPrimitiveValues && IsPrimitiveValue.Any() && !IsExpandedForm
&& !ParameterNames.Any(p => string.IsNullOrEmpty(p)))
{
Debug.Assert(skipCount == 0);
if (ArgumentNames == null)
{
ArgumentNames = new string[Arguments.Length];
}
for (int i = 0; i < Arguments.Length; i++)
{
if (IsPrimitiveValue[i] && ArgumentNames[i] == null)
{
ArgumentNames[i] = ParameterNames[i];
}
}
}
int argumentCount = GetActualArgumentCount();
var useImplicitlyTypedOut = UseImplicitlyTypedOut;
if (ArgumentNames == null)
{
return Arguments.Skip(skipCount).Take(argumentCount).Select(arg => AddAnnotations(arg.Expression));
}
else
{
Debug.Assert(skipCount == 0);
return Arguments.Take(argumentCount).Zip(ArgumentNames.Take(argumentCount),
(arg, name) => {
if (name == null)
return AddAnnotations(arg.Expression);
else
return new NamedArgumentExpression(name, AddAnnotations(arg.Expression));
});
}
Expression AddAnnotations(Expression expression)
{
if (!useImplicitlyTypedOut)
return expression;
if (expression.GetResolveResult() is ByReferenceResolveResult brrr
&& brrr.IsOut)
{
expression.AddAnnotation(UseImplicitlyTypedOutAnnotation.Instance);
}
return expression;
}
}
public bool CanInferAnonymousTypePropertyNamesFromArguments()
{
for (int i = 0; i < Arguments.Length; i++)
{
string inferredName;
switch (Arguments[i].Expression)
{
case IdentifierExpression identifier:
inferredName = identifier.Identifier;
break;
case MemberReferenceExpression member:
inferredName = member.MemberName;
break;
default:
inferredName = null;
break;
}
if (inferredName != ExpectedParameters[i].Name)
{
return false;
}
}
return true;
}
[Conditional("DEBUG")]
public void CheckNoNamedOrOptionalArguments()
{
Debug.Assert(ArgumentToParameterMap == null && ArgumentNames == null && FirstOptionalArgumentIndex < 0);
}
}
readonly DecompilerSettings settings;
readonly ExpressionBuilder expressionBuilder;
readonly CSharpResolver resolver;
readonly IDecompilerTypeSystem typeSystem;
public CallBuilder(ExpressionBuilder expressionBuilder, IDecompilerTypeSystem typeSystem, DecompilerSettings settings)
{
this.expressionBuilder = expressionBuilder;
this.resolver = expressionBuilder.resolver;
this.settings = settings;
this.typeSystem = typeSystem;
}
public TranslatedExpression Build(CallInstruction inst, IType typeHint = null)
{
if (inst is NewObj newobj && IL.Transforms.DelegateConstruction.MatchDelegateConstruction(newobj, out _, out _, out _))
{
return HandleDelegateConstruction(newobj);
}
if (settings.TupleTypes && TupleTransform.MatchTupleConstruction(inst as NewObj, out var tupleElements) && tupleElements.Length >= 2)
{
var elementTypes = TupleType.GetTupleElementTypes(inst.Method.DeclaringType);
var elementNames = typeHint is TupleType tt ? tt.ElementNames : default;
Debug.Assert(!elementTypes.IsDefault, "MatchTupleConstruction should not succeed unless we got a valid tuple type.");
Debug.Assert(elementTypes.Length == tupleElements.Length);
var tuple = new TupleExpression();
var elementRRs = new List<ResolveResult>();
foreach (var (index, element, elementType) in tupleElements.ZipWithIndex(elementTypes))
{
var translatedElement = expressionBuilder.Translate(element, elementType)
.ConvertTo(elementType, expressionBuilder, allowImplicitConversion: true);
if (elementNames.IsDefaultOrEmpty || elementNames.ElementAtOrDefault(index) is not string { Length: > 0 } name)
{
tuple.Elements.Add(translatedElement.Expression);
}
else
{
tuple.Elements.Add(new NamedArgumentExpression(name, translatedElement.Expression));
}
elementRRs.Add(translatedElement.ResolveResult);
}
return tuple.WithRR(new TupleResolveResult(
expressionBuilder.compilation,
elementRRs.ToImmutableArray(),
elementNames,
valueTupleAssembly: inst.Method.DeclaringType.GetDefinition()?.ParentModule
)).WithILInstruction(inst);
}
return Build(inst.OpCode, inst.Method, inst.Arguments, constrainedTo: inst.ConstrainedTo)
.WithILInstruction(inst);
}
public ExpressionWithResolveResult Build(OpCode callOpCode, IMethod method,
IReadOnlyList<ILInstruction> callArguments,
IReadOnlyList<int> argumentToParameterMap = null,
IType constrainedTo = null)
{
if (method.IsExplicitInterfaceImplementation && callOpCode == OpCode.Call)
{
// Direct non-virtual call to explicit interface implementation.
// This can't really be represented in C#, but at least in the case where
// the class is sealed, we can equivalently call the interface member instead:
var interfaceMembers = method.ExplicitlyImplementedInterfaceMembers.ToList();
if (method.DeclaringTypeDefinition?.Kind == TypeKind.Class && method.DeclaringTypeDefinition.IsSealed && interfaceMembers.Count == 1)
{
method = (IMethod)interfaceMembers.Single();
callOpCode = OpCode.CallVirt;
}
}
// Used for Call, CallVirt and NewObj
var expectedTargetDetails = new ExpectedTargetDetails {
CallOpCode = callOpCode
};
ILFunction localFunction = null;
if (method.IsLocalFunction)
{
localFunction = expressionBuilder.ResolveLocalFunction(method);
Debug.Assert(localFunction != null);
}
TranslatedExpression target;
if (callOpCode == OpCode.NewObj)
{
target = default(TranslatedExpression); // no target
}
else if (localFunction != null)
{
var ide = new IdentifierExpression(localFunction.Name);
if (method.TypeArguments.Count > 0)
{
ide.TypeArguments.AddRange(method.TypeArguments.Select(expressionBuilder.ConvertType));
}
ide.AddAnnotation(localFunction);
target = ide.WithoutILInstruction()
.WithRR(ToMethodGroup(method, localFunction));
}
else
{
target = expressionBuilder.TranslateTarget(
callArguments.FirstOrDefault(),
nonVirtualInvocation: callOpCode == OpCode.Call || method.IsConstructor,
memberStatic: method.IsStatic,
memberDeclaringType: constrainedTo ?? method.DeclaringType);
if (constrainedTo == null
&& target.Expression is CastExpression cast
&& target.ResolveResult is ConversionResolveResult conversion
&& target.Type.IsKnownType(KnownTypeCode.Object)
&& conversion.Conversion.IsBoxingConversion)
{
// boxing conversion on call target?
// let's see if we can make that implicit:
target = target.UnwrapChild(cast.Expression);
// we'll need to make sure the boxing effect is preserved
expectedTargetDetails.NeedsBoxingConversion = true;
}
}
int firstParamIndex = (method.IsStatic || callOpCode == OpCode.NewObj) ? 0 : 1;
Debug.Assert(firstParamIndex == 0 || argumentToParameterMap == null
|| argumentToParameterMap[0] == -1);
var argumentList = BuildArgumentList(expectedTargetDetails, target.ResolveResult, method,
firstParamIndex, callArguments, argumentToParameterMap);
if (localFunction != null)
{
return new InvocationExpression(target, argumentList.GetArgumentExpressions())
.WithRR(new CSharpInvocationResolveResult(target.ResolveResult, method,
argumentList.GetArgumentResolveResults(), isExpandedForm: argumentList.IsExpandedForm));
}
if (method is VarArgInstanceMethod)
{
argumentList.FirstOptionalArgumentIndex = -1;
argumentList.AddNamesToPrimitiveValues = false;
argumentList.UseImplicitlyTypedOut = false;
int regularParameterCount = ((VarArgInstanceMethod)method).RegularParameterCount;
var argListArg = new UndocumentedExpression();
argListArg.UndocumentedExpressionType = UndocumentedExpressionType.ArgList;
int paramIndex = regularParameterCount;
var builder = expressionBuilder;
Debug.Assert(argumentToParameterMap == null && argumentList.ArgumentNames == null);
argListArg.Arguments.AddRange(argumentList.Arguments.Skip(regularParameterCount).Select(arg => arg.ConvertTo(argumentList.ExpectedParameters[paramIndex++].Type, builder).Expression));
var argListRR = new ResolveResult(SpecialType.ArgList);
argumentList.Arguments = argumentList.Arguments.Take(regularParameterCount)
.Concat(new[] { argListArg.WithoutILInstruction().WithRR(argListRR) }).ToArray();
method = ((VarArgInstanceMethod)method).BaseMethod;
argumentList.ExpectedParameters = method.Parameters.ToArray();
}
if (settings.Ranges)
{
if (HandleRangeConstruction(out var result, callOpCode, method, target, argumentList))
{
return result;
}
}
if (callOpCode == OpCode.NewObj)
{
return HandleConstructorCall(expectedTargetDetails, target.ResolveResult, method, argumentList);
}
if (method.Name == "Invoke" && method.DeclaringType.Kind == TypeKind.Delegate && !IsNullConditional(target))
{
return new InvocationExpression(target, argumentList.GetArgumentExpressions())
.WithRR(new CSharpInvocationResolveResult(target.ResolveResult, method,
argumentList.GetArgumentResolveResults(), isExpandedForm: argumentList.IsExpandedForm, isDelegateInvocation: true));
}
if (settings.StringInterpolation && IsInterpolatedStringCreation(method, argumentList) &&
TryGetStringInterpolationTokens(argumentList, out string format, out var tokens))
{
var arguments = argumentList.Arguments;
var content = new List<InterpolatedStringContent>();
bool unpackSingleElementArray = !argumentList.IsExpandedForm && argumentList.Length == 2
&& argumentList.Arguments[1].Expression is ArrayCreateExpression ace
&& ace.Initializer?.Elements.Count == 1;
void UnpackSingleElementArray(ref TranslatedExpression argument)
{
if (!unpackSingleElementArray)
return;
var arrayCreation = (ArrayCreateExpression)argumentList.Arguments[1].Expression;
var arrayCreationRR = (ArrayCreateResolveResult)argumentList.Arguments[1].ResolveResult;
var element = arrayCreation.Initializer.Elements.First().Detach();
argument = new TranslatedExpression(element, arrayCreationRR.InitializerElements.First());
}
if (tokens.Count > 0)
{
foreach (var (kind, index, alignment, text) in tokens)
{
TranslatedExpression argument;
switch (kind)
{
case TokenKind.String:
content.Add(new InterpolatedStringText(text));
break;
case TokenKind.Argument:
argument = arguments[index + 1];
UnpackSingleElementArray(ref argument);
content.Add(new Interpolation(argument));
break;
case TokenKind.ArgumentWithFormat:
argument = arguments[index + 1];
UnpackSingleElementArray(ref argument);
content.Add(new Interpolation(argument, suffix: text));
break;
case TokenKind.ArgumentWithAlignment:
argument = arguments[index + 1];
UnpackSingleElementArray(ref argument);
content.Add(new Interpolation(argument, alignment));
break;
case TokenKind.ArgumentWithAlignmentAndFormat:
argument = arguments[index + 1];
UnpackSingleElementArray(ref argument);
content.Add(new Interpolation(argument, alignment, text));
break;
}
}
var formattableStringType = expressionBuilder.compilation.FindType(KnownTypeCode.FormattableString);
var isrr = new InterpolatedStringResolveResult(expressionBuilder.compilation.FindType(KnownTypeCode.String),
format, argumentList.GetArgumentResolveResults(1).ToArray());
var expr = new InterpolatedStringExpression();
expr.Content.AddRange(content);
if (method.Name == "Format")
return expr.WithRR(isrr);
return new CastExpression(expressionBuilder.ConvertType(formattableStringType),
expr.WithRR(isrr))
.WithRR(new ConversionResolveResult(formattableStringType, isrr, Conversion.ImplicitInterpolatedStringConversion));
}
}
int allowedParamCount = (method.ReturnType.IsKnownType(KnownTypeCode.Void) ? 1 : 0);
if (method.IsAccessor && (method.AccessorOwner.SymbolKind == SymbolKind.Indexer || argumentList.ExpectedParameters.Length == allowedParamCount))
{
argumentList.CheckNoNamedOrOptionalArguments();
return HandleAccessorCall(expectedTargetDetails, method, target, argumentList.Arguments.ToList(), argumentList.ArgumentNames);
}
if (IsDelegateEqualityComparison(method, argumentList.Arguments))
{
argumentList.CheckNoNamedOrOptionalArguments();
return HandleDelegateEqualityComparison(method, argumentList.Arguments)
.WithRR(new CSharpInvocationResolveResult(target.ResolveResult, method,
argumentList.GetArgumentResolveResults(), isExpandedForm: argumentList.IsExpandedForm));
}
if (method.IsOperator && method.Name == "op_Implicit" && argumentList.Length == 1)
{
argumentList.CheckNoNamedOrOptionalArguments();
return HandleImplicitConversion(method, argumentList.Arguments[0]);
}
var transform = GetRequiredTransformationsForCall(expectedTargetDetails, method, ref target,
ref argumentList, CallTransformation.All, out IParameterizedMember foundMethod);
// Note: after this, 'method' and 'foundMethod' may differ,
// but as far as allowed by IsAppropriateCallTarget().
// Need to update list of parameter names, because foundMethod is different and thus might use different names.
if (!method.Equals(foundMethod) && argumentList.ParameterNames.Length >= foundMethod.Parameters.Count)
{
for (int i = 0; i < foundMethod.Parameters.Count; i++)
{
argumentList.ParameterNames[i] = foundMethod.Parameters[i].Name;
}
}
Expression targetExpr;
string methodName = method.Name;
AstNodeCollection<AstType> typeArgumentList;
if ((transform & CallTransformation.NoOptionalArgumentAllowed) != 0)
{
argumentList.FirstOptionalArgumentIndex = -1;
}
if ((transform & CallTransformation.RequireTarget) != 0)
{
targetExpr = new MemberReferenceExpression(target.Expression, methodName);
typeArgumentList = ((MemberReferenceExpression)targetExpr).TypeArguments;
// HACK : convert this.Dispose() to ((IDisposable)this).Dispose(), if Dispose is an explicitly implemented interface method.
// settings.AlwaysCastTargetsOfExplicitInterfaceImplementationCalls == true is used in Windows Forms' InitializeComponent methods.
if (method.IsExplicitInterfaceImplementation && (target.Expression is ThisReferenceExpression || settings.AlwaysCastTargetsOfExplicitInterfaceImplementationCalls))
{
var interfaceMember = method.ExplicitlyImplementedInterfaceMembers.First();
var castExpression = new CastExpression(expressionBuilder.ConvertType(interfaceMember.DeclaringType), target.Expression.Detach());
methodName = interfaceMember.Name;
targetExpr = new MemberReferenceExpression(castExpression, methodName);
typeArgumentList = ((MemberReferenceExpression)targetExpr).TypeArguments;
}
}
else
{
targetExpr = new IdentifierExpression(methodName);
typeArgumentList = ((IdentifierExpression)targetExpr).TypeArguments;
}
if ((transform & CallTransformation.RequireTypeArguments) != 0 && (!settings.AnonymousTypes || !method.TypeArguments.Any(a => a.ContainsAnonymousType())))
typeArgumentList.AddRange(method.TypeArguments.Select(expressionBuilder.ConvertType));
return new InvocationExpression(targetExpr, argumentList.GetArgumentExpressions())
.WithRR(new CSharpInvocationResolveResult(target.ResolveResult, foundMethod,
argumentList.GetArgumentResolveResultsDirect(), isExpandedForm: argumentList.IsExpandedForm));
}
/// <summary>
/// Converts a call to an Add method to a collection initializer expression.
/// </summary>
public ExpressionWithResolveResult BuildCollectionInitializerExpression(OpCode callOpCode, IMethod method,
InitializedObjectResolveResult target, IReadOnlyList<ILInstruction> callArguments)
{
// (see ECMA-334, section 12.7.11.4):
// The collection object to which a collection initializer is applied shall be of a type that implements
// System.Collections.IEnumerable or a compile-time error occurs. For each specified element in order,
// the collection initializer invokes an Add method on the target object with the expression list of the
// element initializer as argument list, applying normal overload resolution for each invocation. Thus, the
// collection object shall contain an applicable Add method for each element initializer.
// The list of applicable methods includes all methods (as of C# 6.0 extension methods, too) named 'Add'
// that can be invoked on the target object, with the following exceptions:
// - Methods with ref or out parameters may not be used,
// - methods that have type parameters, that cannot be inferred from the parameter list may not be used,
// - vararg methods may not be used.
// - named arguments are not supported.
// However, note that params methods may be used.
// At this point, we assume that 'method' fulfills all the conditions mentioned above. We just need to make
// sure that the correct method is called by resolving any ambiguities by inserting casts, if necessary.
ExpectedTargetDetails expectedTargetDetails = new ExpectedTargetDetails { CallOpCode = callOpCode };
var unused = new IdentifierExpression("initializedObject").WithRR(target).WithoutILInstruction();
var args = callArguments.ToList();
if (method.IsExtensionMethod)
args.Insert(0, new Nop());
var argumentList = BuildArgumentList(expectedTargetDetails, target, method,
firstParamIndex: 0, args, null);
argumentList.ArgumentNames = null;
argumentList.AddNamesToPrimitiveValues = false;
argumentList.UseImplicitlyTypedOut = false;
var transform = GetRequiredTransformationsForCall(expectedTargetDetails, method, ref unused,
ref argumentList, CallTransformation.None, out _);
Debug.Assert(transform == CallTransformation.None || transform == CallTransformation.NoOptionalArgumentAllowed);
// Calls with only one argument do not need an array initializer expression to wrap them.
// Any special cases are handled by the caller (i.e., ExpressionBuilder.TranslateObjectAndCollectionInitializer)
// Note: we intentionally ignore the firstOptionalArgumentIndex in this case.
int skipCount;
if (method.IsExtensionMethod)
{
if (argumentList.Arguments.Length == 2)
return argumentList.Arguments[1];
skipCount = 1;
}
else
{
if (argumentList.Arguments.Length == 1)
return argumentList.Arguments[0];
skipCount = 0;
}
if ((transform & CallTransformation.NoOptionalArgumentAllowed) != 0)
argumentList.FirstOptionalArgumentIndex = -1;
return new ArrayInitializerExpression(argumentList.GetArgumentExpressions(skipCount))
.WithRR(new CSharpInvocationResolveResult(target, method, argumentList.GetArgumentResolveResults(skipCount).ToArray(),
isExtensionMethodInvocation: method.IsExtensionMethod, isExpandedForm: argumentList.IsExpandedForm));
}
public ExpressionWithResolveResult BuildDictionaryInitializerExpression(OpCode callOpCode, IMethod method,
InitializedObjectResolveResult target, IReadOnlyList<ILInstruction> indices, ILInstruction value = null)
{
if (method is null)
throw new ArgumentNullException(nameof(method));
ExpectedTargetDetails expectedTargetDetails = new ExpectedTargetDetails { CallOpCode = callOpCode };
var callArguments = new List<ILInstruction>();
callArguments.Add(new LdNull());
callArguments.AddRange(indices);
callArguments.Add(value ?? new Nop());
var argumentList = BuildArgumentList(expectedTargetDetails, target, method, 1, callArguments, null);
var unused = new IdentifierExpression("initializedObject").WithRR(target).WithoutILInstruction();
var assignment = HandleAccessorCall(expectedTargetDetails, method, unused,
argumentList.Arguments.ToList(), argumentList.ArgumentNames);
if (((AssignmentExpression)assignment).Left is IndexerExpression indexer && !indexer.Target.IsNull)
indexer.Target.Remove();
if (value != null)
return assignment;
return new ExpressionWithResolveResult(((AssignmentExpression)assignment).Left.Detach());
}
private static bool IsInterpolatedStringCreation(IMethod method, ArgumentList argumentList)
{
return method.IsStatic && (
(method.DeclaringType.IsKnownType(KnownTypeCode.String) && method.Name == "Format") ||
(method.Name == "Create" && method.DeclaringType.Name == "FormattableStringFactory" &&
method.DeclaringType.Namespace == "System.Runtime.CompilerServices")
)
&& argumentList.ArgumentNames == null // Argument names are not allowed
&& (
argumentList.IsExpandedForm // Must be expanded form
|| !method.Parameters.Last().IsParams // -or- not a params overload
|| (argumentList.Length == 2 && argumentList.Arguments[1].Expression is ArrayCreateExpression) // -or- an array literal
);
}
private bool TryGetStringInterpolationTokens(ArgumentList argumentList, out string format, out List<(TokenKind Kind, int Index, int Alignment, string Format)> tokens)
{
tokens = null;
format = null;
TranslatedExpression[] arguments = argumentList.Arguments;
if (arguments.Length == 0 || argumentList.ArgumentNames != null || argumentList.ArgumentToParameterMap != null)
return false;
if (!(arguments[(int)0].ResolveResult is ConstantResolveResult crr && crr.Type.IsKnownType((KnownTypeCode)KnownTypeCode.String)))
return false;
if (!arguments.Skip(1).All(a => !a.Expression.DescendantsAndSelf.OfType<PrimitiveExpression>().Any(p => p.Value is string)))
return false;
tokens = new List<(TokenKind Kind, int Index, int Alignment, string Format)>();
int i = 0;
format = (string)crr.ConstantValue;
foreach (var (kind, data) in TokenizeFormatString(format))
{
int index;
string[] arg;
switch (kind)
{
case TokenKind.Error:
return false;
case TokenKind.String:
tokens.Add((kind, -1, 0, data));
break;
case TokenKind.Argument:
if (!int.TryParse(data, out index) || index != i)
return false;
i++;
tokens.Add((kind, index, 0, null));
break;
case TokenKind.ArgumentWithFormat:
arg = data.Split(new[] { ':' }, 2);
if (arg.Length != 2 || arg[1].Length == 0)
return false;
if (!int.TryParse(arg[0], out index) || index != i)
return false;
i++;
tokens.Add((kind, index, 0, arg[1]));
break;
case TokenKind.ArgumentWithAlignment:
arg = data.Split(new[] { ',' }, 2);
if (arg.Length != 2 || arg[1].Length == 0)
return false;
if (!int.TryParse(arg[0], out index) || index != i)
return false;
if (!int.TryParse(arg[1], out int alignment))
return false;
i++;
tokens.Add((kind, index, alignment, null));
break;
case TokenKind.ArgumentWithAlignmentAndFormat:
arg = data.Split(new[] { ',', ':' }, 3);
if (arg.Length != 3 || arg[1].Length == 0 || arg[2].Length == 0)
return false;
if (!int.TryParse(arg[0], out index) || index != i)
return false;
if (!int.TryParse(arg[1], out alignment))
return false;
i++;
tokens.Add((kind, index, alignment, arg[2]));
break;
default:
return false;
}
}
return i == arguments.Length - 1;
}
private enum TokenKind
{
Error,
String,
Argument,
ArgumentWithFormat,
ArgumentWithAlignment,
ArgumentWithAlignmentAndFormat,
}
private IEnumerable<(TokenKind, string)> TokenizeFormatString(string value)
{
int pos = -1;
int Peek(int steps = 1)
{
if (pos + steps < value.Length)
return value[pos + steps];
return -1;
}
int Next()
{
int val = Peek();
pos++;
return val;
}
int next;
TokenKind kind = TokenKind.String;
StringBuilder sb = new StringBuilder();
while ((next = Next()) > -1)
{
switch ((char)next)
{
case '{':
if (Peek() == '{')
{
kind = TokenKind.String;
sb.Append("{{");
Next();
}
else
{
if (sb.Length > 0)
{
yield return (kind, sb.ToString());
}
kind = TokenKind.Argument;
sb.Clear();
}
break;
case '}':
if (kind != TokenKind.String)
{
yield return (kind, sb.ToString());
sb.Clear();
kind = TokenKind.String;
}
else if (Peek() == '}')
{
sb.Append("}}");
Next();
}
else
{
yield return (TokenKind.Error, null);
}
break;
case ':':
if (kind == TokenKind.Argument)
{
kind = TokenKind.ArgumentWithFormat;
}
else if (kind == TokenKind.ArgumentWithAlignment)
{
kind = TokenKind.ArgumentWithAlignmentAndFormat;
}
sb.Append(':');
break;
case ',':
if (kind == TokenKind.Argument)
{
kind = TokenKind.ArgumentWithAlignment;
}
sb.Append(',');
break;
default:
sb.Append((char)next);
break;
}
}
if (sb.Length > 0)
{
if (kind == TokenKind.String)
yield return (kind, sb.ToString());
else
yield return (TokenKind.Error, null);
}
}
private ArgumentList BuildArgumentList(ExpectedTargetDetails expectedTargetDetails, ResolveResult target, IMethod method,
int firstParamIndex, IReadOnlyList<ILInstruction> callArguments, IReadOnlyList<int> argumentToParameterMap)
{
ArgumentList list = new ArgumentList();
// Translate arguments to the expected parameter types
var arguments = new List<TranslatedExpression>(method.Parameters.Count);
string[] argumentNames = null;
Debug.Assert(callArguments.Count == firstParamIndex + method.Parameters.Count);
var expectedParameters = new List<IParameter>(method.Parameters.Count); // parameters, but in argument order
bool isExpandedForm = false;
BitSet isPrimitiveValue = new BitSet(method.Parameters.Count);
// Optional arguments:
// This value has the following values:
// -2 - there are no optional arguments
// -1 - optional arguments are forbidden
// >= 0 - the index of the first argument that can be removed, because it is optional
// and is the default value of the parameter.
int firstOptionalArgumentIndex = expressionBuilder.settings.OptionalArguments ? -2 : -1;
for (int i = firstParamIndex; i < callArguments.Count; i++)
{
IParameter parameter;
if (argumentToParameterMap != null)
{
if (argumentNames == null && argumentToParameterMap[i] != i - firstParamIndex)
{
// Starting at the first argument that is out-of-place,
// assign names to that argument and all following arguments:
argumentNames = new string[method.Parameters.Count];
}
parameter = method.Parameters[argumentToParameterMap[i]];
if (argumentNames != null && AssignVariableNames.IsValidName(parameter.Name))
{
argumentNames[arguments.Count] = parameter.Name;
}
}
else
{
parameter = method.Parameters[i - firstParamIndex];
}
var arg = expressionBuilder.Translate(callArguments[i], parameter.Type);
if (IsPrimitiveValueThatShouldBeNamedArgument(arg, method, parameter))
{
isPrimitiveValue.Set(arguments.Count);
}
if (IsOptionalArgument(parameter, arg))
{
if (firstOptionalArgumentIndex == -2)
firstOptionalArgumentIndex = i - firstParamIndex;
}
else
{
firstOptionalArgumentIndex = -2;
}
if (parameter.IsParams && i + 1 == callArguments.Count && argumentToParameterMap == null)
{
// Parameter is marked params
// If the argument is an array creation, inline all elements into the call and add missing default values.
// Otherwise handle it normally.
if (TransformParamsArgument(expectedTargetDetails, target, method, parameter,
arg, ref expectedParameters, ref arguments))
{
Debug.Assert(argumentNames == null);
firstOptionalArgumentIndex = -1;
isExpandedForm = true;
continue;
}
}
IType parameterType;
if (parameter.Type.Kind == TypeKind.Dynamic)
{
parameterType = expressionBuilder.compilation.FindType(KnownTypeCode.Object);
}
else
{
parameterType = parameter.Type;
}
arg = arg.ConvertTo(parameterType, expressionBuilder, allowImplicitConversion: arg.Type.Kind != TypeKind.Dynamic);
if (parameter.ReferenceKind != ReferenceKind.None)
{
arg = ExpressionBuilder.ChangeDirectionExpressionTo(arg, parameter.ReferenceKind);
}
arguments.Add(arg);
expectedParameters.Add(parameter);
}
list.ExpectedParameters = expectedParameters.ToArray();
list.Arguments = arguments.ToArray();
list.ParameterNames = expectedParameters.SelectArray(p => p.Name);
list.ArgumentNames = argumentNames;
list.ArgumentToParameterMap = argumentToParameterMap;
list.IsExpandedForm = isExpandedForm;
list.IsPrimitiveValue = isPrimitiveValue;
list.FirstOptionalArgumentIndex = firstOptionalArgumentIndex;
list.UseImplicitlyTypedOut = true;
list.AddNamesToPrimitiveValues = expressionBuilder.settings.NamedArguments && expressionBuilder.settings.NonTrailingNamedArguments;
return list;
}
private bool IsPrimitiveValueThatShouldBeNamedArgument(TranslatedExpression arg, IMethod method, IParameter p)
{
if (!arg.ResolveResult.IsCompileTimeConstant || method.DeclaringType.IsKnownType(KnownTypeCode.NullableOfT))
return false;
return p.Type.IsKnownType(KnownTypeCode.Boolean);
}
private bool TransformParamsArgument(ExpectedTargetDetails expectedTargetDetails, ResolveResult targetResolveResult,
IMethod method, IParameter parameter, TranslatedExpression arg, ref List<IParameter> expectedParameters,
ref List<TranslatedExpression> arguments)
{
if (CheckArgument(out int length, out IType elementType))
{
var expandedParameters = new List<IParameter>(expectedParameters);
var expandedArguments = new List<TranslatedExpression>(arguments);
if (length > 0)
{
var arrayElements = ((ArrayCreateExpression)arg.Expression).Initializer.Elements.ToArray();
for (int j = 0; j < length; j++)
{
expandedParameters.Add(new DefaultParameter(elementType, parameter.Name + j));
if (j < arrayElements.Length)
expandedArguments.Add(new TranslatedExpression(arrayElements[j]));
else
expandedArguments.Add(expressionBuilder.GetDefaultValueExpression(elementType).WithoutILInstruction());
}
}
if (IsUnambiguousCall(expectedTargetDetails, method, targetResolveResult, Empty<IType>.Array,
expandedArguments.SelectArray(a => a.ResolveResult), argumentNames: null,
firstOptionalArgumentIndex: -1, out _,
out var bestCandidateIsExpandedForm) == OverloadResolutionErrors.None && bestCandidateIsExpandedForm)
{
expectedParameters = expandedParameters;
arguments = expandedArguments.SelectList(a => new TranslatedExpression(a.Expression.Detach()));
return true;
}
}
return false;
bool CheckArgument(out int len, out IType t)
{
len = 0;
t = null;
if (arg.ResolveResult is CSharpInvocationResolveResult csirr &&
csirr.Arguments.Count == 0 && csirr.Member is IMethod emptyMethod &&
emptyMethod.IsStatic &&
"System.Array.Empty" == emptyMethod.FullName &&
emptyMethod.TypeArguments.Count == 1)
{
t = emptyMethod.TypeArguments[0];
return true;
}
if (arg.ResolveResult is ArrayCreateResolveResult acrr &&
acrr.SizeArguments.Count == 1 &&
acrr.SizeArguments[0].IsCompileTimeConstant &&
acrr.SizeArguments[0].ConstantValue is int l)
{
len = l;
t = ((ArrayType)acrr.Type).ElementType;
return true;
}
return false;
}
}
bool IsOptionalArgument(IParameter parameter, TranslatedExpression arg)
{
if (!parameter.IsOptional || !arg.ResolveResult.IsCompileTimeConstant)
return false;
if (parameter.GetAttributes().Any(a => a.AttributeType.IsKnownType(KnownAttribute.CallerMemberName)
|| a.AttributeType.IsKnownType(KnownAttribute.CallerFilePath)
|| a.AttributeType.IsKnownType(KnownAttribute.CallerLineNumber)))
return false;
return object.Equals(parameter.GetConstantValue(), arg.ResolveResult.ConstantValue);
}
[Flags]
enum CallTransformation
{
None = 0,
RequireTarget = 1,
RequireTypeArguments = 2,
NoOptionalArgumentAllowed = 4,
All = 7
}
private CallTransformation GetRequiredTransformationsForCall(ExpectedTargetDetails expectedTargetDetails, IMethod method,
ref TranslatedExpression target, ref ArgumentList argumentList, CallTransformation allowedTransforms, out IParameterizedMember foundMethod)
{
CallTransformation transform = CallTransformation.None;
// initialize requireTarget flag
bool requireTarget;
ResolveResult targetResolveResult;
if ((allowedTransforms & CallTransformation.RequireTarget) != 0)
{
if (settings.AlwaysQualifyMemberReferences || expressionBuilder.HidesVariableWithName(method.Name))
{
requireTarget = true;
}
else
{
if (method.IsLocalFunction)
requireTarget = false;
else if (method.IsStatic)
requireTarget = !expressionBuilder.IsCurrentOrContainingType(method.DeclaringTypeDefinition) || method.Name == ".cctor";
else if (method.Name == ".ctor")
requireTarget = true; // always use target for base/this-ctor-call, the constructor initializer pattern depends on this
else if (target.Expression is BaseReferenceExpression)
requireTarget = (expectedTargetDetails.CallOpCode != OpCode.CallVirt && method.IsVirtual);
else
requireTarget = target.Expression is not ThisReferenceExpression;
}
targetResolveResult = requireTarget ? target.ResolveResult : null;
}
else
{
// HACK: this is a special case for collection initializer calls, they do not allow a target to be
// emitted, but we still need it for overload resolution.
requireTarget = true;
targetResolveResult = target.ResolveResult;
}
// initialize requireTypeArguments flag
bool requireTypeArguments;
IType[] typeArguments;
bool appliedRequireTypeArgumentsShortcut = false;
if (method.TypeParameters.Count > 0 && (allowedTransforms & CallTransformation.RequireTypeArguments) != 0
&& !IsPossibleExtensionMethodCallOnNull(method, argumentList.Arguments))
{
// The ambiguity resolution below only adds type arguments as last resort measure, however there are
// methods, such as Enumerable.OfType<TResult>(IEnumerable input) that always require type arguments,
// as those cannot be inferred from the parameters, which leads to bloated expressions full of extra casts
// that are no longer required once we add the type arguments.
// We lend overload resolution a hand by detecting such cases beforehand and requiring type arguments,
// if necessary.
if (!CanInferTypeArgumentsFromArguments(method, argumentList, expressionBuilder.typeInference))
{
requireTypeArguments = true;
typeArguments = method.TypeArguments.ToArray();
appliedRequireTypeArgumentsShortcut = true;
}
else
{
requireTypeArguments = false;
typeArguments = Empty<IType>.Array;
}
}
else
{
requireTypeArguments = false;
typeArguments = Empty<IType>.Array;
}
bool targetCasted = false;
bool argumentsCasted = false;
bool originalRequireTarget = requireTarget;
bool skipTargetCast = method.Accessibility <= Accessibility.Protected && expressionBuilder.IsBaseTypeOfCurrentType(method.DeclaringTypeDefinition);
OverloadResolutionErrors errors;
while ((errors = IsUnambiguousCall(expectedTargetDetails, method, targetResolveResult, typeArguments,
argumentList.GetArgumentResolveResults().ToArray(), argumentList.ArgumentNames, argumentList.FirstOptionalArgumentIndex, out foundMethod,
out var bestCandidateIsExpandedForm)) != OverloadResolutionErrors.None || bestCandidateIsExpandedForm != argumentList.IsExpandedForm)
{
switch (errors)
{
case OverloadResolutionErrors.OutVarTypeMismatch:
Debug.Assert(argumentList.UseImplicitlyTypedOut);
argumentList.UseImplicitlyTypedOut = false;
continue;
case OverloadResolutionErrors.TypeInferenceFailed:
if ((allowedTransforms & CallTransformation.RequireTypeArguments) != 0)
{
goto case OverloadResolutionErrors.WrongNumberOfTypeArguments;
}
goto default;
case OverloadResolutionErrors.WrongNumberOfTypeArguments:
Debug.Assert((allowedTransforms & CallTransformation.RequireTypeArguments) != 0);
if (requireTypeArguments)
goto default;
requireTypeArguments = true;
typeArguments = method.TypeArguments.ToArray();
continue;
case OverloadResolutionErrors.MissingArgumentForRequiredParameter:
if (argumentList.FirstOptionalArgumentIndex == -1)
goto default;
argumentList.FirstOptionalArgumentIndex = -1;
continue;
default:
// TODO : implement some more intelligent algorithm that decides which of these fixes (cast args, add target, cast target, add type args)
// is best in this case. Additionally we should not cast all arguments at once, but step-by-step try to add only a minimal number of casts.
if (argumentList.FirstOptionalArgumentIndex >= 0)
{
argumentList.FirstOptionalArgumentIndex = -1;
}
else if (!argumentsCasted)
{
// If we added type arguments beforehand, but that didn't make the code any better,
// undo that decision and add casts first.
if (appliedRequireTypeArgumentsShortcut)
{
requireTypeArguments = false;
typeArguments = Empty<IType>.Array;
appliedRequireTypeArgumentsShortcut = false;
}
argumentsCasted = true;
argumentList.UseImplicitlyTypedOut = false;
CastArguments(argumentList.Arguments, argumentList.ExpectedParameters);
}
else if ((allowedTransforms & CallTransformation.RequireTarget) != 0 && !requireTarget)
{
requireTarget = true;
targetResolveResult = target.ResolveResult;
}
else if ((allowedTransforms & CallTransformation.RequireTarget) != 0 && !targetCasted)
{
if (skipTargetCast && requireTarget != originalRequireTarget)
{
requireTarget = originalRequireTarget;
if (!originalRequireTarget)
targetResolveResult = null;
allowedTransforms &= ~CallTransformation.RequireTarget;
}
else
{
targetCasted = true;
target = target.ConvertTo(method.DeclaringType, expressionBuilder);
targetResolveResult = target.ResolveResult;
}
}
else if ((allowedTransforms & CallTransformation.RequireTypeArguments) != 0 && !requireTypeArguments)
{
requireTypeArguments = true;
typeArguments = method.TypeArguments.ToArray();
}
else
{
break;
}
continue;
}
// We've given up.
foundMethod = method;
break;
}
if ((allowedTransforms & CallTransformation.RequireTarget) != 0 && requireTarget)
transform |= CallTransformation.RequireTarget;
if ((allowedTransforms & CallTransformation.RequireTypeArguments) != 0 && requireTypeArguments)
transform |= CallTransformation.RequireTypeArguments;
if (argumentList.FirstOptionalArgumentIndex < 0)
transform |= CallTransformation.NoOptionalArgumentAllowed;
return transform;
}
private bool IsPossibleExtensionMethodCallOnNull(IMethod method, IList<TranslatedExpression> arguments)
{
return method.IsExtensionMethod && arguments.Count > 0 && arguments[0].Expression is NullReferenceExpression;
}
static bool CanInferTypeArgumentsFromArguments(IMethod method, ArgumentList argumentList, TypeInference typeInference)
{
if (method.TypeParameters.Count == 0)
return true;
// always use unspecialized member, otherwise type inference fails
method = (IMethod)method.MemberDefinition;
IReadOnlyList<IType> paramTypesInArgumentOrder;
if (argumentList.ArgumentToParameterMap == null)
paramTypesInArgumentOrder = method.Parameters.SelectReadOnlyArray(p => p.Type);
else
paramTypesInArgumentOrder = argumentList.ArgumentToParameterMap
.SelectReadOnlyArray(
index => index >= 0 ? method.Parameters[index].Type : SpecialType.UnknownType
);
typeInference.InferTypeArguments(method.TypeParameters,
argumentList.Arguments.SelectReadOnlyArray(a => a.ResolveResult), paramTypesInArgumentOrder,
out bool success);
return success;
}
private void CastArguments(IList<TranslatedExpression> arguments, IList<IParameter> expectedParameters)
{
for (int i = 0; i < arguments.Count; i++)
{
if (settings.AnonymousTypes && expectedParameters[i].Type.ContainsAnonymousType())
{
if (arguments[i].Expression is LambdaExpression lambda)
{
ModifyReturnTypeOfLambda(lambda);
}
}
else
{
IType parameterType;
if (expectedParameters[i].Type.Kind == TypeKind.Dynamic)
{
parameterType = expressionBuilder.compilation.FindType(KnownTypeCode.Object);
}
else
{
parameterType = expectedParameters[i].Type;
}
arguments[i] = arguments[i].ConvertTo(parameterType, expressionBuilder, allowImplicitConversion: false);
}
}
}
static bool IsNullConditional(Expression expr)
{
return expr is UnaryOperatorExpression uoe && uoe.Operator == UnaryOperatorType.NullConditional;
}
private void ModifyReturnTypeOfLambda(LambdaExpression lambda)
{
var resolveResult = (DecompiledLambdaResolveResult)lambda.GetResolveResult();
if (lambda.Body is Expression exprBody)
lambda.Body = new TranslatedExpression(exprBody.Detach()).ConvertTo(resolveResult.ReturnType, expressionBuilder);
else
ModifyReturnStatementInsideLambda(resolveResult.ReturnType, lambda);
resolveResult.InferredReturnType = resolveResult.ReturnType;
}
private void ModifyReturnStatementInsideLambda(IType returnType, AstNode parent)
{
foreach (var child in parent.Children)
{
if (child is LambdaExpression || child is AnonymousMethodExpression)
continue;
if (child is ReturnStatement ret)
{
ret.Expression = new TranslatedExpression(ret.Expression.Detach()).ConvertTo(returnType, expressionBuilder);
continue;
}
ModifyReturnStatementInsideLambda(returnType, child);
}
}
private bool IsDelegateEqualityComparison(IMethod method, IList<TranslatedExpression> arguments)
{
// Comparison on a delegate type is a C# builtin operator
// that compiles down to a Delegate.op_Equality call.
// We handle this as a special case to avoid inserting a cast to System.Delegate.
return method.IsOperator
&& method.DeclaringType.IsKnownType(KnownTypeCode.Delegate)
&& (method.Name == "op_Equality" || method.Name == "op_Inequality")
&& arguments.Count == 2
&& arguments[0].Type.Kind == TypeKind.Delegate
&& arguments[1].Type.Equals(arguments[0].Type);
}
private Expression HandleDelegateEqualityComparison(IMethod method, IList<TranslatedExpression> arguments)
{
return new BinaryOperatorExpression(
arguments[0],
method.Name == "op_Equality" ? BinaryOperatorType.Equality : BinaryOperatorType.InEquality,
arguments[1]
);
}
private ExpressionWithResolveResult HandleImplicitConversion(IMethod method, TranslatedExpression argument)
{
var conversions = CSharpConversions.Get(expressionBuilder.compilation);
IType targetType = method.ReturnType;
var conv = conversions.ImplicitConversion(argument.Type, targetType);
if (!(conv.IsUserDefined && conv.IsValid && conv.Method.Equals(method)))
{
// implicit conversion to targetType isn't directly possible, so first insert a cast to the argument type
argument = argument.ConvertTo(method.Parameters[0].Type, expressionBuilder);
conv = conversions.ImplicitConversion(argument.Type, targetType);
}
if (argument.Expression is DirectionExpression { FieldDirection: FieldDirection.In, Expression: var lvalueExpr })
{
// `(TargetType)(in arg)` is invalid syntax.
// Also, `f(in arg)` is invalid when there's an implicit conversion involved.
argument = argument.UnwrapChild(lvalueExpr);
}
return new CastExpression(expressionBuilder.ConvertType(targetType), argument.Expression)
.WithRR(new ConversionResolveResult(targetType, argument.ResolveResult, conv));
}
OverloadResolutionErrors IsUnambiguousCall(ExpectedTargetDetails expectedTargetDetails, IMethod method,
ResolveResult target, IType[] typeArguments, ResolveResult[] arguments,
string[] argumentNames, int firstOptionalArgumentIndex,
out IParameterizedMember foundMember, out bool bestCandidateIsExpandedForm)
{
foundMember = null;
bestCandidateIsExpandedForm = false;
var currentTypeDefinition = resolver.CurrentTypeDefinition;
var lookup = new MemberLookup(currentTypeDefinition, currentTypeDefinition.ParentModule);
Log.WriteLine("IsUnambiguousCall: Performing overload resolution for " + method);
Log.WriteCollection(" Arguments: ", arguments);
argumentNames = firstOptionalArgumentIndex < 0 || argumentNames == null
? argumentNames
: argumentNames.Take(firstOptionalArgumentIndex).ToArray();
var or = new OverloadResolution(resolver.Compilation,
arguments, argumentNames, typeArguments,
conversions: expressionBuilder.resolver.conversions);
if (expectedTargetDetails.CallOpCode == OpCode.NewObj)
{
foreach (IMethod ctor in method.DeclaringType.GetConstructors())
{
bool allowProtectedAccess =
resolver.CurrentTypeDefinition == method.DeclaringTypeDefinition;
if (lookup.IsAccessible(ctor, allowProtectedAccess))
{
or.AddCandidate(ctor);
}
}
}
else if (method.IsOperator)
{
IEnumerable<IParameterizedMember> operatorCandidates;
if (arguments.Length == 1)
{
IType argType = NullableType.GetUnderlyingType(arguments[0].Type);
operatorCandidates = resolver.GetUserDefinedOperatorCandidates(argType, method.Name);
if (method.Name == "op_Explicit")
{
// For casts, also consider candidates from the target type we are casting to.
var hashSet = new HashSet<IParameterizedMember>(operatorCandidates);
IType targetType = NullableType.GetUnderlyingType(method.ReturnType);
hashSet.UnionWith(
resolver.GetUserDefinedOperatorCandidates(targetType, method.Name)
);
operatorCandidates = hashSet;
}
}
else if (arguments.Length == 2)
{
IType lhsType = NullableType.GetUnderlyingType(arguments[0].Type);
IType rhsType = NullableType.GetUnderlyingType(arguments[1].Type);
var hashSet = new HashSet<IParameterizedMember>();
hashSet.UnionWith(resolver.GetUserDefinedOperatorCandidates(lhsType, method.Name));
hashSet.UnionWith(resolver.GetUserDefinedOperatorCandidates(rhsType, method.Name));
operatorCandidates = hashSet;
}
else
{
operatorCandidates = EmptyList<IParameterizedMember>.Instance;
}
foreach (var m in operatorCandidates)
{
or.AddCandidate(m);
}
}
else if (target == null)
{
var result = resolver.ResolveSimpleName(method.Name, typeArguments, isInvocationTarget: true)
as MethodGroupResolveResult;
if (result == null)
return OverloadResolutionErrors.AmbiguousMatch;
or.AddMethodLists(result.MethodsGroupedByDeclaringType.ToArray());
}
else
{
var result = lookup.Lookup(target, method.Name, typeArguments, isInvocation: true) as MethodGroupResolveResult;
if (result == null)
return OverloadResolutionErrors.AmbiguousMatch;
or.AddMethodLists(result.MethodsGroupedByDeclaringType.ToArray());
}
bestCandidateIsExpandedForm = or.BestCandidateIsExpandedForm;
if (or.BestCandidateErrors != OverloadResolutionErrors.None)
return or.BestCandidateErrors;
if (or.IsAmbiguous)
return OverloadResolutionErrors.AmbiguousMatch;
foundMember = or.GetBestCandidateWithSubstitutedTypeArguments();
if (!IsAppropriateCallTarget(expectedTargetDetails, method, foundMember))
return OverloadResolutionErrors.AmbiguousMatch;
var map = or.GetArgumentToParameterMap();
for (int i = 0; i < arguments.Length; i++)
{
ResolveResult arg = arguments[i];
int parameterIndex = map[i];
if (arg is OutVarResolveResult rr && parameterIndex >= 0)
{
var param = foundMember.Parameters[parameterIndex];
var paramType = param.Type.UnwrapByRef();
if (!paramType.Equals(rr.OriginalVariableType))
return OverloadResolutionErrors.OutVarTypeMismatch;
}
}
return OverloadResolutionErrors.None;
}
bool IsUnambiguousAccess(ExpectedTargetDetails expectedTargetDetails, ResolveResult target, IMethod method,
IList<TranslatedExpression> arguments, string[] argumentNames, out IMember foundMember)
{
Log.WriteLine("IsUnambiguousAccess: Performing overload resolution for " + method);
Log.WriteCollection(" Arguments: ", arguments.Select(a => a.ResolveResult));
foundMember = null;
if (target == null)
{
var result = resolver.ResolveSimpleName(method.AccessorOwner.Name,
EmptyList<IType>.Instance,
isInvocationTarget: false) as MemberResolveResult;
if (result == null || result.IsError)
return false;
foundMember = result.Member;
}
else
{
var lookup = new MemberLookup(resolver.CurrentTypeDefinition, resolver.CurrentTypeDefinition.ParentModule);
if (method.AccessorOwner.SymbolKind == SymbolKind.Indexer)
{
var or = new OverloadResolution(resolver.Compilation,
arguments.SelectArray(a => a.ResolveResult),
argumentNames: argumentNames,
typeArguments: Empty<IType>.Array,
conversions: expressionBuilder.resolver.conversions);
or.AddMethodLists(lookup.LookupIndexers(target));
if (or.BestCandidateErrors != OverloadResolutionErrors.None)
return false;
if (or.IsAmbiguous)
return false;
foundMember = or.GetBestCandidateWithSubstitutedTypeArguments();
}
else
{
var result = lookup.Lookup(target,
method.AccessorOwner.Name,
EmptyList<IType>.Instance,
isInvocation: false) as MemberResolveResult;
if (result == null || result.IsError)
return false;
foundMember = result.Member;
}
}
return foundMember != null && IsAppropriateCallTarget(expectedTargetDetails, method.AccessorOwner, foundMember);
}
ExpressionWithResolveResult HandleAccessorCall(ExpectedTargetDetails expectedTargetDetails, IMethod method,
TranslatedExpression target, List<TranslatedExpression> arguments, string[] argumentNames)
{
bool requireTarget;
if (settings.AlwaysQualifyMemberReferences || method.AccessorOwner.SymbolKind == SymbolKind.Indexer || expressionBuilder.HidesVariableWithName(method.AccessorOwner.Name))
requireTarget = true;
else if (method.IsStatic)
requireTarget = !expressionBuilder.IsCurrentOrContainingType(method.DeclaringTypeDefinition);
else
requireTarget = !(target.Expression is ThisReferenceExpression);
bool targetCasted = false;
bool isSetter = method.ReturnType.IsKnownType(KnownTypeCode.Void);
bool argumentsCasted = (isSetter && method.Parameters.Count == 1) || (!isSetter && method.Parameters.Count == 0);
var targetResolveResult = requireTarget ? target.ResolveResult : null;
TranslatedExpression value = default(TranslatedExpression);
if (isSetter)
{
value = arguments.Last();
arguments.Remove(value);
}
IMember foundMember;
while (!IsUnambiguousAccess(expectedTargetDetails, targetResolveResult, method, arguments, argumentNames, out foundMember))
{
if (!argumentsCasted)
{
argumentsCasted = true;
CastArguments(arguments, method.Parameters.ToList());
}
else if (!requireTarget)
{
requireTarget = true;
targetResolveResult = target.ResolveResult;
}
else if (!targetCasted)
{
targetCasted = true;
target = target.ConvertTo(method.AccessorOwner.DeclaringType, expressionBuilder);
targetResolveResult = target.ResolveResult;
}
else
{
foundMember = method.AccessorOwner;
break;
}
}
var rr = new MemberResolveResult(target.ResolveResult, foundMember);
if (isSetter)
{
TranslatedExpression expr;
if (arguments.Count != 0)
{
expr = new IndexerExpression(target.ResolveResult is InitializedObjectResolveResult ? null : target.Expression, arguments.Select(a => a.Expression))
.WithoutILInstruction().WithRR(rr);
}
else if (requireTarget)
{
expr = new MemberReferenceExpression(target.Expression, method.AccessorOwner.Name)
.WithoutILInstruction().WithRR(rr);
}
else
{
expr = new IdentifierExpression(method.AccessorOwner.Name)
.WithoutILInstruction().WithRR(rr);
}
var op = AssignmentOperatorType.Assign;
if (method.AccessorOwner is IEvent parentEvent)
{
if (method.Equals(parentEvent.AddAccessor))
{
op = AssignmentOperatorType.Add;
}
if (method.Equals(parentEvent.RemoveAccessor))
{
op = AssignmentOperatorType.Subtract;
}
}
return new AssignmentExpression(expr, op, value.Expression).WithRR(new TypeResolveResult(method.AccessorOwner.ReturnType));
}
else
{
if (arguments.Count != 0)
{
return new IndexerExpression(target.Expression, arguments.Select(a => a.Expression))
.WithoutILInstruction().WithRR(rr);
}
else if (requireTarget)
{
return new MemberReferenceExpression(target.Expression, method.AccessorOwner.Name)
.WithoutILInstruction().WithRR(rr);
}
else
{
return new IdentifierExpression(method.AccessorOwner.Name)
.WithoutILInstruction().WithRR(rr);
}
}
}
bool IsAppropriateCallTarget(ExpectedTargetDetails expectedTargetDetails, IMember expectedTarget, IMember actualTarget)
{
if (expectedTarget.Equals(actualTarget, NormalizeTypeVisitor.TypeErasure))
return true;
if (expectedTargetDetails.CallOpCode == OpCode.CallVirt && actualTarget.IsOverride)
{
if (expectedTargetDetails.NeedsBoxingConversion && actualTarget.DeclaringType.IsReferenceType != true)
return false;
foreach (var possibleTarget in InheritanceHelper.GetBaseMembers(actualTarget, false))
{
if (expectedTarget.Equals(possibleTarget, NormalizeTypeVisitor.TypeErasure))
return true;
if (!possibleTarget.IsOverride)
break;
}
}
return false;
}
ExpressionWithResolveResult HandleConstructorCall(ExpectedTargetDetails expectedTargetDetails, ResolveResult target, IMethod method, ArgumentList argumentList)
{
if (settings.AnonymousTypes && method.DeclaringType.IsAnonymousType())
{
Debug.Assert(argumentList.ArgumentToParameterMap == null && argumentList.ArgumentNames == null && argumentList.FirstOptionalArgumentIndex < 0);
var atce = new AnonymousTypeCreateExpression();
if (argumentList.CanInferAnonymousTypePropertyNamesFromArguments())
{
atce.Initializers.AddRange(argumentList.GetArgumentExpressions());
}
else
{
for (int i = 0; i < argumentList.Length; i++)
{
atce.Initializers.Add(
new NamedExpression {
Name = argumentList.ExpectedParameters[i].Name,
Expression = argumentList.Arguments[i].ConvertTo(argumentList.ExpectedParameters[i].Type, expressionBuilder)
});
}
}
return atce.WithRR(new CSharpInvocationResolveResult(
target, method, argumentList.GetArgumentResolveResults(),
isExpandedForm: argumentList.IsExpandedForm, argumentToParameterMap: argumentList.ArgumentToParameterMap
));
}
else
{
while (IsUnambiguousCall(expectedTargetDetails, method, null, Empty<IType>.Array,
argumentList.GetArgumentResolveResults().ToArray(),
argumentList.ArgumentNames, argumentList.FirstOptionalArgumentIndex, out _,
out var bestCandidateIsExpandedForm) != OverloadResolutionErrors.None || bestCandidateIsExpandedForm != argumentList.IsExpandedForm)
{
if (argumentList.FirstOptionalArgumentIndex >= 0)
{
argumentList.FirstOptionalArgumentIndex = -1;
continue;
}
CastArguments(argumentList.Arguments, argumentList.ExpectedParameters);
break; // make sure that we don't not end up in an infinite loop
}
IType returnTypeOverride = null;
if (typeSystem.MainModule.TypeSystemOptions.HasFlag(TypeSystemOptions.NativeIntegersWithoutAttribute))
{
// For DeclaringType, we don't use nint/nuint (so that DeclaringType.GetConstructors etc. works),
// but in NativeIntegersWithoutAttribute mode we must use nint/nuint for expression types,
// so that the appropriate set of conversions is used for further overload resolution.
if (method.DeclaringType.IsKnownType(KnownTypeCode.IntPtr))
returnTypeOverride = SpecialType.NInt;
else if (method.DeclaringType.IsKnownType(KnownTypeCode.UIntPtr))
returnTypeOverride = SpecialType.NUInt;
}
return new ObjectCreateExpression(
expressionBuilder.ConvertType(method.DeclaringType),
argumentList.GetArgumentExpressions()
).WithRR(new CSharpInvocationResolveResult(
target, method, argumentList.GetArgumentResolveResults().ToArray(),
isExpandedForm: argumentList.IsExpandedForm,
argumentToParameterMap: argumentList.ArgumentToParameterMap,
returnTypeOverride: returnTypeOverride
));
}
}
TranslatedExpression HandleDelegateConstruction(CallInstruction inst)
{
ILInstruction thisArg = inst.Arguments[0];
ILInstruction func = inst.Arguments[1];
IMethod method;
ExpectedTargetDetails expectedTargetDetails = default;
switch (func.OpCode)
{
case OpCode.LdFtn:
method = ((LdFtn)func).Method;
expectedTargetDetails.CallOpCode = OpCode.Call;
break;
case OpCode.LdVirtFtn:
method = ((LdVirtFtn)func).Method;
expectedTargetDetails.CallOpCode = OpCode.CallVirt;
break;
default:
throw new ArgumentException($"Unknown instruction type: {func.OpCode}");
}
if (CanUseDelegateConstruction(method, thisArg, inst.Method.DeclaringType.GetDelegateInvokeMethod()))
{
return HandleDelegateConstruction(inst.Method.DeclaringType, method, expectedTargetDetails, thisArg, inst);
}
else
{
var argumentList = BuildArgumentList(expectedTargetDetails, null, inst.Method,
0, inst.Arguments, null);
return HandleConstructorCall(new ExpectedTargetDetails { CallOpCode = OpCode.NewObj }, null, inst.Method, argumentList).WithILInstruction(inst);
}
}
private bool CanUseDelegateConstruction(IMethod targetMethod, ILInstruction thisArg, IMethod invokeMethod)
{
// Accessors cannot be directly referenced as method group in C#
// see https://github.com/icsharpcode/ILSpy/issues/1741#issuecomment-540179101
if (targetMethod.IsAccessor)
return false;
if (targetMethod.IsStatic)
{
// If the invoke method is known, we can compare the parameter counts to figure out whether the
// delegate is static or binds the first argument
if (invokeMethod != null)
{
if (invokeMethod.Parameters.Count == targetMethod.Parameters.Count)
{
return thisArg.MatchLdNull();
}
else if (targetMethod.IsExtensionMethod && invokeMethod.Parameters.Count == targetMethod.Parameters.Count - 1)
{
return true;
}
else
{
return false;
}
}
else
{
// delegate type unknown:
return thisArg.MatchLdNull() || targetMethod.IsExtensionMethod;
}
}
else
{
// targetMethod is instance method
if (invokeMethod != null && invokeMethod.Parameters.Count != targetMethod.Parameters.Count)
return false;
return true;
}
}
internal TranslatedExpression Build(LdVirtDelegate inst)
{
return HandleDelegateConstruction(inst.Type, inst.Method, new ExpectedTargetDetails { CallOpCode = OpCode.CallVirt }, inst.Argument, inst);
}
internal ExpressionWithResolveResult BuildMethodReference(IMethod method, bool isVirtual)
{
var expr = BuildDelegateReference(method, invokeMethod: null, new ExpectedTargetDetails { CallOpCode = isVirtual ? OpCode.CallVirt : OpCode.Call }, thisArg: null);
expr.Expression.RemoveAnnotations<ResolveResult>();
return expr.Expression.WithRR(new MemberResolveResult(null, method));
}
ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod invokeMethod, ExpectedTargetDetails expectedTargetDetails, ILInstruction thisArg)
{
ExpressionBuilder expressionBuilder = this.expressionBuilder;
ExpressionWithResolveResult targetExpression;
(TranslatedExpression target, bool addTypeArguments, string methodName, ResolveResult result) = DisambiguateDelegateReference(method, invokeMethod, expectedTargetDetails, thisArg);
if (target.Expression != null)
{
var mre = new MemberReferenceExpression(target, methodName);
if (addTypeArguments)
{
mre.TypeArguments.AddRange(method.TypeArguments.Select(expressionBuilder.ConvertType));
}
targetExpression = mre.WithRR(result);
}
else
{
var ide = new IdentifierExpression(methodName);
if (addTypeArguments)
{
ide.TypeArguments.AddRange(method.TypeArguments.Select(expressionBuilder.ConvertType));
}
targetExpression = ide.WithRR(result);
}
return targetExpression;
}
(TranslatedExpression target, bool addTypeArguments, string methodName, ResolveResult result) DisambiguateDelegateReference(IMethod method, IMethod invokeMethod, ExpectedTargetDetails expectedTargetDetails, ILInstruction thisArg)
{
if (method.IsLocalFunction)
{
ILFunction localFunction = expressionBuilder.ResolveLocalFunction(method);
Debug.Assert(localFunction != null);
return (default, addTypeArguments: true, localFunction.Name, ToMethodGroup(method, localFunction));
}
if (method.IsExtensionMethod && method.Parameters.Count - 1 == invokeMethod?.Parameters.Count)
{
IType targetType = method.Parameters[0].Type;
if (targetType.Kind == TypeKind.ByReference && thisArg is Box thisArgBox)
{
targetType = ((ByReferenceType)targetType).ElementType;
thisArg = thisArgBox.Argument;
}
TranslatedExpression target = expressionBuilder.Translate(thisArg, targetType);
var currentTarget = target;
bool targetCasted = false;
bool addTypeArguments = false;
// Initial inputs for IsUnambiguousMethodReference:
ResolveResult targetResolveResult = target.ResolveResult;
IReadOnlyList<IType> typeArguments = EmptyList<IType>.Instance;
if (thisArg.MatchLdNull())
{
targetCasted = true;
currentTarget = currentTarget.ConvertTo(targetType, expressionBuilder);
targetResolveResult = currentTarget.ResolveResult;
}
// Find somewhat minimal solution:
ResolveResult result;
while (!IsUnambiguousMethodReference(expectedTargetDetails, method, targetResolveResult, typeArguments, true, out result))
{
if (!targetCasted)
{
// try casting target
targetCasted = true;
currentTarget = currentTarget.ConvertTo(targetType, expressionBuilder);
targetResolveResult = currentTarget.ResolveResult;
continue;
}
if (!addTypeArguments)
{
// try adding type arguments
addTypeArguments = true;
typeArguments = method.TypeArguments;
continue;
}
break;
}
return (currentTarget, addTypeArguments, method.Name, result);
}
else
{
// Prepare call target
IType targetType = method.DeclaringType;
if (targetType.IsReferenceType == false && thisArg is Box thisArgBox)
{
// Normal struct instance method calls (which TranslateTarget is meant for) expect a 'ref T',
// but delegate construction uses a 'box T'.
if (thisArgBox.Argument is LdObj ldobj)
{
thisArg = ldobj.Target;
}
else
{
thisArg = new AddressOf(thisArgBox.Argument, thisArgBox.Type);
}
}
TranslatedExpression target = expressionBuilder.TranslateTarget(thisArg,
nonVirtualInvocation: expectedTargetDetails.CallOpCode == OpCode.Call,
memberStatic: method.IsStatic,
memberDeclaringType: method.DeclaringType);
// check if target is required
bool requireTarget = expressionBuilder.HidesVariableWithName(method.Name)
|| (method.IsStatic ? !expressionBuilder.IsCurrentOrContainingType(method.DeclaringTypeDefinition) : !(target.Expression is ThisReferenceExpression));
// Try to find minimal expression
// If target is required, include it from the start
bool targetAdded = requireTarget;
TranslatedExpression currentTarget = targetAdded ? target : default;
// Remember other decisions:
bool targetCasted = false;
bool addTypeArguments = false;
// Initial inputs for IsUnambiguousMethodReference:
ResolveResult targetResolveResult = targetAdded ? target.ResolveResult : null;
IReadOnlyList<IType> typeArguments = EmptyList<IType>.Instance;
// Find somewhat minimal solution:
ResolveResult result;
while (!IsUnambiguousMethodReference(expectedTargetDetails, method, targetResolveResult, typeArguments, false, out result))
{
if (!addTypeArguments)
{
// try adding type arguments
addTypeArguments = true;
typeArguments = method.TypeArguments;
continue;
}
if (!targetAdded)
{
// try adding target
targetAdded = true;
currentTarget = target;
targetResolveResult = target.ResolveResult;
continue;
}
if (!targetCasted)
{
// try casting target
targetCasted = true;
currentTarget = currentTarget.ConvertTo(targetType, expressionBuilder);
targetResolveResult = currentTarget.ResolveResult;
continue;
}
break;
}
return (currentTarget, addTypeArguments, method.Name, result);
}
}
TranslatedExpression HandleDelegateConstruction(IType delegateType, IMethod method, ExpectedTargetDetails expectedTargetDetails, ILInstruction thisArg, ILInstruction inst)
{
var invokeMethod = delegateType.GetDelegateInvokeMethod();
var targetExpression = BuildDelegateReference(method, invokeMethod, expectedTargetDetails, thisArg);
var oce = new ObjectCreateExpression(expressionBuilder.ConvertType(delegateType), targetExpression)
.WithILInstruction(inst)
.WithRR(new ConversionResolveResult(
delegateType,
targetExpression.ResolveResult,
Conversion.MethodGroupConversion(method, expectedTargetDetails.CallOpCode == OpCode.CallVirt, false)));
return oce;
}
bool IsUnambiguousMethodReference(ExpectedTargetDetails expectedTargetDetails, IMethod method, ResolveResult target, IReadOnlyList<IType> typeArguments, bool isExtensionMethodReference, out ResolveResult result)
{
Log.WriteLine("IsUnambiguousMethodReference: Performing overload resolution for " + method);
var lookup = new MemberLookup(resolver.CurrentTypeDefinition, resolver.CurrentTypeDefinition.ParentModule);
OverloadResolution or;
if (isExtensionMethodReference)
{
var resolver = this.resolver.WithCurrentUsingScope(this.expressionBuilder.statementBuilder.decompileRun.UsingScope.Resolve(this.resolver.Compilation));
result = resolver.ResolveMemberAccess(target, method.Name, typeArguments, NameLookupMode.InvocationTarget) as MethodGroupResolveResult;
if (result == null)
return false;
or = ((MethodGroupResolveResult)result).PerformOverloadResolution(resolver.CurrentTypeResolveContext.Compilation,
method.Parameters.SelectReadOnlyArray(p => new TypeResolveResult(p.Type)),
argumentNames: null, allowExtensionMethods: true);
if (or == null || or.IsAmbiguous)
return false;
}
else
{
or = new OverloadResolution(resolver.Compilation,
arguments: method.Parameters.SelectReadOnlyArray(p => new TypeResolveResult(p.Type)), // there are no arguments, use parameter types
argumentNames: null, // argument names are not possible
typeArguments.ToArray(),
conversions: expressionBuilder.resolver.conversions
);
if (target == null)
{
result = resolver.ResolveSimpleName(method.Name, typeArguments, isInvocationTarget: false);
if (!(result is MethodGroupResolveResult mgrr))
return false;
or.AddMethodLists(mgrr.MethodsGroupedByDeclaringType.ToArray());
}
else
{
result = lookup.Lookup(target, method.Name, typeArguments, isInvocation: false);
if (!(result is MethodGroupResolveResult mgrr))
return false;
or.AddMethodLists(mgrr.MethodsGroupedByDeclaringType.ToArray());
}
}
var foundMethod = or.GetBestCandidateWithSubstitutedTypeArguments();
if (!IsAppropriateCallTarget(expectedTargetDetails, method, foundMethod))
return false;
return result is MethodGroupResolveResult;
}
static MethodGroupResolveResult ToMethodGroup(IMethod method, ILFunction localFunction)
{
return new MethodGroupResolveResult(
null,
localFunction.Name,
new[] {
new MethodListWithDeclaringType(
method.DeclaringType,
new IParameterizedMember[] { method }
)
}, method.TypeArguments
);
}
internal TranslatedExpression CallWithNamedArgs(Block block)
{
Debug.Assert(block.Kind == BlockKind.CallWithNamedArgs);
var call = (CallInstruction)block.FinalInstruction;
var arguments = new ILInstruction[call.Arguments.Count];
var argumentToParameterMap = new int[arguments.Length];
int firstParamIndex = call.IsInstanceCall ? 1 : 0;
// Arguments from temporary variables (VariableKind.NamedArgument):
int pos = 0;
foreach (StLoc stloc in block.Instructions)
{
Debug.Assert(stloc.Variable.LoadInstructions.Single().Parent == call);
arguments[pos] = stloc.Value;
argumentToParameterMap[pos] = stloc.Variable.LoadInstructions.Single().ChildIndex - firstParamIndex;
pos++;
}
// Remaining argument:
foreach (var arg in call.Arguments)
{
if (arg.MatchLdLoc(out var v) && v.Kind == VariableKind.NamedArgument)
{
continue; // already handled in loop above
}
arguments[pos] = arg;
argumentToParameterMap[pos] = arg.ChildIndex - firstParamIndex;
pos++;
}
Debug.Assert(pos == arguments.Length);
return Build(call.OpCode, call.Method, arguments, argumentToParameterMap, call.ConstrainedTo)
.WithILInstruction(call).WithILInstruction(block);
}
private bool HandleRangeConstruction(out ExpressionWithResolveResult result, OpCode callOpCode, IMethod method, TranslatedExpression target, ArgumentList argumentList)
{
result = default;
if (argumentList.ArgumentNames != null)
{
return false; // range syntax doesn't support named arguments
}
if (method.DeclaringType.IsKnownType(KnownTypeCode.Range))
{
if (callOpCode == OpCode.NewObj && argumentList.Length == 2)
{
result = new BinaryOperatorExpression(argumentList.Arguments[0], BinaryOperatorType.Range, argumentList.Arguments[1])
.WithRR(new MemberResolveResult(null, method));
return true;
}
else if (callOpCode == OpCode.Call && method.Name == "get_All" && argumentList.Length == 0)
{
result = new BinaryOperatorExpression(Expression.Null, BinaryOperatorType.Range, Expression.Null)
.WithRR(new MemberResolveResult(null, method.AccessorOwner ?? method));
return true;
}
else if (callOpCode == OpCode.Call && method.Name == "StartAt" && argumentList.Length == 1)
{
result = new BinaryOperatorExpression(argumentList.Arguments[0], BinaryOperatorType.Range, Expression.Null)
.WithRR(new MemberResolveResult(null, method));
return true;
}
else if (callOpCode == OpCode.Call && method.Name == "EndAt" && argumentList.Length == 1)
{
result = new BinaryOperatorExpression(Expression.Null, BinaryOperatorType.Range, argumentList.Arguments[0])
.WithRR(new MemberResolveResult(null, method));
return true;
}
}
else if (callOpCode == OpCode.NewObj && method.DeclaringType.IsKnownType(KnownTypeCode.Index))
{
if (argumentList.Length != 2)
return false;
if (!(argumentList.Arguments[1].Expression is PrimitiveExpression pe && pe.Value is true))
return false;
result = new UnaryOperatorExpression(UnaryOperatorType.IndexFromEnd, argumentList.Arguments[0])
.WithRR(new MemberResolveResult(null, method));
return true;
}
else if (method is SyntheticRangeIndexAccessor rangeIndexAccessor && rangeIndexAccessor.IsSlicing)
{
// For slicing the method is called Slice()/Substring(), but we still need to output indexer notation.
// So special-case range-based slicing here.
result = new IndexerExpression(target, argumentList.Arguments.Select(a => a.Expression))
.WithRR(new MemberResolveResult(target.ResolveResult, method));
return true;
}
return false;
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/CallBuilder.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/CallBuilder.cs",
"repo_id": "ILSpy",
"token_count": 27667
} | 220 |
// 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.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Xml;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler
{
/// <summary>
/// A <see cref="IProjectFileWriter"/> implementation that creates the projects in the SDK style format.
/// </summary>
sealed class ProjectFileWriterSdkStyle : IProjectFileWriter
{
const string AspNetCorePrefix = "Microsoft.AspNetCore";
const string PresentationFrameworkName = "PresentationFramework";
const string WindowsFormsName = "System.Windows.Forms";
const string TrueString = "True";
const string FalseString = "False";
const string AnyCpuString = "AnyCPU";
static readonly HashSet<string> ImplicitReferences = new HashSet<string> {
"mscorlib",
"netstandard",
"PresentationFramework",
"System",
"System.Diagnostics.Debug",
"System.Diagnostics.Tools",
"System.Drawing",
"System.Runtime",
"System.Runtime.Extensions",
"System.Windows.Forms",
"System.Xaml",
};
enum ProjectType { Default, WinForms, Wpf, Web }
/// <summary>
/// Creates a new instance of the <see cref="ProjectFileWriterSdkStyle"/> class.
/// </summary>
/// <returns>A new instance of the <see cref="ProjectFileWriterSdkStyle"/> class.</returns>
public static IProjectFileWriter Create() => new ProjectFileWriterSdkStyle();
/// <inheritdoc />
public void Write(
TextWriter target,
IProjectInfoProvider project,
IEnumerable<ProjectItemInfo> files,
PEFile module)
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(target))
{
xmlWriter.Formatting = Formatting.Indented;
Write(xmlWriter, project, files, module);
}
}
static void Write(XmlTextWriter xml, IProjectInfoProvider project, IEnumerable<ProjectItemInfo> files, PEFile module)
{
xml.WriteStartElement("Project");
var projectType = GetProjectType(module);
xml.WriteAttributeString("Sdk", GetSdkString(projectType));
PlaceIntoTag("PropertyGroup", xml, () => WriteAssemblyInfo(xml, module, project, projectType));
PlaceIntoTag("PropertyGroup", xml, () => WriteProjectInfo(xml, project));
PlaceIntoTag("PropertyGroup", xml, () => WriteMiscellaneousPropertyGroup(xml, files));
PlaceIntoTag("ItemGroup", xml, () => WriteResources(xml, files));
PlaceIntoTag("ItemGroup", xml, () => WriteReferences(xml, module, project, projectType));
xml.WriteEndElement();
}
static void PlaceIntoTag(string tagName, XmlTextWriter xml, Action content)
{
xml.WriteStartElement(tagName);
try
{
content();
}
finally
{
xml.WriteEndElement();
}
}
static void WriteAssemblyInfo(XmlTextWriter xml, PEFile module, IProjectInfoProvider project, ProjectType projectType)
{
xml.WriteElementString("AssemblyName", module.Name);
// Since we create AssemblyInfo.cs manually, we need to disable the auto-generation
xml.WriteElementString("GenerateAssemblyInfo", FalseString);
WriteOutputType(xml, module.Reader.PEHeaders.IsDll, module.Reader.PEHeaders.PEHeader.Subsystem, projectType);
WriteDesktopExtensions(xml, projectType);
string platformName = TargetServices.GetPlatformName(module);
var targetFramework = TargetServices.DetectTargetFramework(module);
if (targetFramework.Identifier == ".NETFramework" && targetFramework.VersionNumber == 200)
targetFramework = TargetServices.DetectTargetFrameworkNET20(module, project.AssemblyResolver, targetFramework);
if (targetFramework.Moniker == null)
{
throw new NotSupportedException($"Cannot decompile this assembly to a SDK style project. Use default project format instead.");
}
xml.WriteElementString("TargetFramework", targetFramework.Moniker);
// 'AnyCPU' is default, so only need to specify platform if it differs
if (platformName != AnyCpuString)
{
xml.WriteElementString("PlatformTarget", platformName);
}
if (platformName == AnyCpuString && (module.Reader.PEHeaders.CorHeader.Flags & CorFlags.Prefers32Bit) != 0)
{
xml.WriteElementString("Prefer32Bit", TrueString);
}
}
static void WriteOutputType(XmlTextWriter xml, bool isDll, Subsystem moduleSubsystem, ProjectType projectType)
{
if (!isDll)
{
switch (moduleSubsystem)
{
case Subsystem.WindowsGui:
xml.WriteElementString("OutputType", "WinExe");
break;
case Subsystem.WindowsCui:
xml.WriteElementString("OutputType", "Exe");
break;
}
}
else
{
// 'Library' is default, so only need to specify output type for executables (excludes ProjectType.Web)
if (projectType == ProjectType.Web)
{
xml.WriteElementString("OutputType", "Library");
}
}
}
static void WriteDesktopExtensions(XmlTextWriter xml, ProjectType projectType)
{
if (projectType == ProjectType.Wpf)
{
xml.WriteElementString("UseWPF", TrueString);
}
else if (projectType == ProjectType.WinForms)
{
xml.WriteElementString("UseWindowsForms", TrueString);
}
}
static void WriteProjectInfo(XmlTextWriter xml, IProjectInfoProvider project)
{
xml.WriteElementString("LangVersion", project.LanguageVersion.ToString().Replace("CSharp", "").Replace('_', '.'));
xml.WriteElementString("AllowUnsafeBlocks", TrueString);
if (project.StrongNameKeyFile != null)
{
xml.WriteElementString("SignAssembly", TrueString);
xml.WriteElementString("AssemblyOriginatorKeyFile", Path.GetFileName(project.StrongNameKeyFile));
}
}
static void WriteMiscellaneousPropertyGroup(XmlTextWriter xml, IEnumerable<ProjectItemInfo> files)
{
var (itemType, fileName) = files.FirstOrDefault(t => t.ItemType == "ApplicationIcon");
if (fileName != null)
xml.WriteElementString("ApplicationIcon", fileName);
(itemType, fileName) = files.FirstOrDefault(t => t.ItemType == "ApplicationManifest");
if (fileName != null)
xml.WriteElementString("ApplicationManifest", fileName);
if (files.Any(t => t.ItemType == "EmbeddedResource"))
xml.WriteElementString("RootNamespace", string.Empty);
// TODO: We should add CustomToolNamespace for resources, otherwise we should add empty RootNamespace
}
static void WriteResources(XmlTextWriter xml, IEnumerable<ProjectItemInfo> files)
{
// remove phase
foreach (var item in files.Where(t => t.ItemType == "EmbeddedResource"))
{
string buildAction = Path.GetExtension(item.FileName).ToUpperInvariant() switch {
".CS" => "Compile",
".RESX" => "EmbeddedResource",
_ => "None"
};
if (buildAction == "EmbeddedResource")
continue;
xml.WriteStartElement(buildAction);
xml.WriteAttributeString("Remove", item.FileName);
xml.WriteEndElement();
}
// include phase
foreach (var item in files.Where(t => t.ItemType == "EmbeddedResource"))
{
if (Path.GetExtension(item.FileName) == ".resx")
continue;
xml.WriteStartElement("EmbeddedResource");
xml.WriteAttributeString("Include", item.FileName);
if (item.AdditionalProperties != null)
{
foreach (var (key, value) in item.AdditionalProperties)
xml.WriteAttributeString(key, value);
}
xml.WriteEndElement();
}
}
static void WriteReferences(XmlTextWriter xml, PEFile module, IProjectInfoProvider project, ProjectType projectType)
{
bool isNetCoreApp = TargetServices.DetectTargetFramework(module).Identifier == ".NETCoreApp";
var targetPacks = new HashSet<string>();
if (isNetCoreApp)
{
targetPacks.Add("Microsoft.NETCore.App");
switch (projectType)
{
case ProjectType.WinForms:
case ProjectType.Wpf:
targetPacks.Add("Microsoft.WindowsDesktop.App");
break;
case ProjectType.Web:
targetPacks.Add("Microsoft.AspNetCore.App");
targetPacks.Add("Microsoft.AspNetCore.All");
break;
}
}
foreach (var reference in module.AssemblyReferences.Where(r => !ImplicitReferences.Contains(r.Name)))
{
if (isNetCoreApp && project.AssemblyReferenceClassifier.IsSharedAssembly(reference, out string runtimePack) && targetPacks.Contains(runtimePack))
{
continue;
}
xml.WriteStartElement("Reference");
xml.WriteAttributeString("Include", reference.Name);
var asembly = project.AssemblyResolver.Resolve(reference);
if (asembly != null && !project.AssemblyReferenceClassifier.IsGacAssembly(reference))
{
xml.WriteElementString("HintPath", FileUtility.GetRelativePath(project.TargetDirectory, asembly.FileName));
}
xml.WriteEndElement();
}
}
static string GetSdkString(ProjectType projectType)
{
switch (projectType)
{
case ProjectType.WinForms:
case ProjectType.Wpf:
return "Microsoft.NET.Sdk.WindowsDesktop";
case ProjectType.Web:
return "Microsoft.NET.Sdk.Web";
default:
return "Microsoft.NET.Sdk";
}
}
static ProjectType GetProjectType(PEFile module)
{
foreach (var referenceName in module.AssemblyReferences.Select(r => r.Name))
{
if (referenceName.StartsWith(AspNetCorePrefix, StringComparison.Ordinal))
{
return ProjectType.Web;
}
if (referenceName == PresentationFrameworkName)
{
return ProjectType.Wpf;
}
if (referenceName == WindowsFormsName)
{
return ProjectType.WinForms;
}
}
return ProjectType.Default;
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs",
"repo_id": "ILSpy",
"token_count": 3676
} | 221 |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ICSharpCode.Decompiler.CSharp.Resolver
{
/// <summary>
/// Resolver logging helper.
/// Wraps System.Diagnostics.Debug so that resolver-specific logging can be enabled/disabled on demand.
/// (it's a huge amount of debug spew and slows down the resolver quite a bit)
/// </summary>
static class Log
{
const bool logEnabled = false;
#if __MonoCS__
[Conditional("MCS_DEBUG")]
#else
[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
#endif
internal static void WriteLine(string text)
{
Debug.WriteLine(text);
}
#if __MonoCS__
[Conditional("MCS_DEBUG")]
#else
[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
#endif
internal static void WriteLine(string format, params object[] args)
{
Debug.WriteLine(format, args);
}
#if __MonoCS__
[Conditional("MCS_DEBUG")]
#else
[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
#endif
internal static void WriteCollection<T>(string text, IEnumerable<T> lines)
{
#if DEBUG
T[] arr = lines.ToArray();
if (arr.Length == 0)
{
Debug.WriteLine(text + "<empty collection>");
}
else
{
Debug.WriteLine(text + (arr[0] != null ? arr[0].ToString() : "<null>"));
for (int i = 1; i < arr.Length; i++)
{
Debug.WriteLine(new string(' ', text.Length) + (arr[i] != null ? arr[i].ToString() : "<null>"));
}
}
#endif
}
#if __MonoCS__
[Conditional("MCS_DEBUG")]
#else
[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
#endif
public static void Indent()
{
Debug.Indent();
}
#if __MonoCS__
[Conditional("MCS_DEBUG")]
#else
[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
#endif
public static void Unindent()
{
Debug.Unindent();
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Resolver/Log.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Resolver/Log.cs",
"repo_id": "ILSpy",
"token_count": 1011
} | 222 |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
/// <summary>
/// Represents a 'cref' reference in XML documentation.
/// </summary>
public class DocumentationReference : AstNode
{
public static readonly Role<AstType> DeclaringTypeRole = new Role<AstType>("DeclaringType", AstType.Null);
public static readonly Role<AstType> ConversionOperatorReturnTypeRole = new Role<AstType>("ConversionOperatorReturnType", AstType.Null);
SymbolKind symbolKind;
OperatorType operatorType;
bool hasParameterList;
/// <summary>
/// Gets/Sets the entity type.
/// Possible values are:
/// <c>SymbolKind.Operator</c> for operators,
/// <c>SymbolKind.Indexer</c> for indexers,
/// <c>SymbolKind.TypeDefinition</c> for references to primitive types,
/// and <c>SymbolKind.None</c> for everything else.
/// </summary>
public SymbolKind SymbolKind {
get { return symbolKind; }
set {
ThrowIfFrozen();
symbolKind = value;
}
}
/// <summary>
/// Gets/Sets the operator type.
/// This property is only used when SymbolKind==Operator.
/// </summary>
public OperatorType OperatorType {
get { return operatorType; }
set {
ThrowIfFrozen();
operatorType = value;
}
}
/// <summary>
/// Gets/Sets whether a parameter list was provided.
/// </summary>
public bool HasParameterList {
get { return hasParameterList; }
set {
ThrowIfFrozen();
hasParameterList = value;
}
}
public override NodeType NodeType {
get { return NodeType.Unknown; }
}
/// <summary>
/// Gets/Sets the declaring type.
/// </summary>
public AstType DeclaringType {
get { return GetChildByRole(DeclaringTypeRole); }
set { SetChildByRole(DeclaringTypeRole, value); }
}
/// <summary>
/// Gets/sets the member name.
/// This property is only used when SymbolKind==None.
/// </summary>
public string MemberName {
get { return GetChildByRole(Roles.Identifier).Name; }
set { SetChildByRole(Roles.Identifier, Identifier.Create(value)); }
}
/// <summary>
/// Gets/Sets the return type of conversion operators.
/// This property is only used when SymbolKind==Operator and OperatorType is explicit or implicit.
/// </summary>
public AstType ConversionOperatorReturnType {
get { return GetChildByRole(ConversionOperatorReturnTypeRole); }
set { SetChildByRole(ConversionOperatorReturnTypeRole, value); }
}
public AstNodeCollection<AstType> TypeArguments {
get { return GetChildrenByRole(Roles.TypeArgument); }
}
public AstNodeCollection<ParameterDeclaration> Parameters {
get { return GetChildrenByRole(Roles.Parameter); }
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
DocumentationReference o = other as DocumentationReference;
if (!(o != null && this.SymbolKind == o.SymbolKind && this.HasParameterList == o.HasParameterList))
return false;
if (this.SymbolKind == SymbolKind.Operator)
{
if (this.OperatorType != o.OperatorType)
return false;
if (this.OperatorType == OperatorType.Implicit || this.OperatorType == OperatorType.Explicit)
{
if (!this.ConversionOperatorReturnType.DoMatch(o.ConversionOperatorReturnType, match))
return false;
}
}
else if (this.SymbolKind == SymbolKind.None)
{
if (!MatchString(this.MemberName, o.MemberName))
return false;
if (!this.TypeArguments.DoMatch(o.TypeArguments, match))
return false;
}
return this.Parameters.DoMatch(o.Parameters, match);
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitDocumentationReference(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitDocumentationReference(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitDocumentationReference(this, data);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs",
"repo_id": "ILSpy",
"token_count": 1684
} | 223 |
// 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;
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
/// <summary>
/// Base class for expressions.
/// </summary>
/// <remarks>
/// This class is useful even though it doesn't provide any additional functionality:
/// It can be used to communicate more information in APIs, e.g. "this subnode will always be an expression"
/// </remarks>
public abstract class Expression : AstNode
{
#region Null
public new static readonly Expression Null = new NullExpression();
sealed class NullExpression : Expression
{
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
#region PatternPlaceholder
public static implicit operator Expression(PatternMatching.Pattern pattern)
{
return pattern != null ? new PatternPlaceholder(pattern) : null;
}
sealed class PatternPlaceholder : Expression, 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 override NodeType NodeType {
get {
return NodeType.Expression;
}
}
public new Expression Clone()
{
return (Expression)base.Clone();
}
public Expression ReplaceWith(Func<Expression, Expression> replaceFunction)
{
if (replaceFunction == null)
throw new ArgumentNullException(nameof(replaceFunction));
return (Expression)base.ReplaceWith(node => replaceFunction((Expression)node));
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs",
"repo_id": "ILSpy",
"token_count": 1277
} | 224 |
// 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.CSharp.Syntax
{
public class QueryExpression : Expression
{
public static readonly Role<QueryClause> ClauseRole = new Role<QueryClause>("Clause", null);
#region Null
public new static readonly QueryExpression Null = new NullQueryExpression();
sealed class NullQueryExpression : QueryExpression
{
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 AstNodeCollection<QueryClause> Clauses {
get { return GetChildrenByRole(ClauseRole); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryExpression(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryExpression(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryExpression o = other as QueryExpression;
return o != null && !o.IsNull && this.Clauses.DoMatch(o.Clauses, match);
}
}
public abstract class QueryClause : AstNode
{
public override NodeType NodeType {
get { return NodeType.QueryClause; }
}
}
/// <summary>
/// Represents a query continuation.
/// "(from .. select ..) into Identifier" or "(from .. group .. by ..) into Identifier"
/// Note that "join .. into .." is not a query continuation!
///
/// This is always the first(!!) clause in a query expression.
/// The tree for "from a in b select c into d select e" looks like this:
/// new QueryExpression {
/// new QueryContinuationClause {
/// PrecedingQuery = new QueryExpression {
/// new QueryFromClause(a in b),
/// new QuerySelectClause(c)
/// },
/// Identifier = d
/// },
/// new QuerySelectClause(e)
/// }
/// </summary>
public class QueryContinuationClause : QueryClause
{
public static readonly Role<QueryExpression> PrecedingQueryRole = new Role<QueryExpression>("PrecedingQuery", QueryExpression.Null);
public static readonly TokenRole IntoKeywordRole = new TokenRole("into");
public QueryExpression PrecedingQuery {
get { return GetChildByRole(PrecedingQueryRole); }
set { SetChildByRole(PrecedingQueryRole, value); }
}
public CSharpTokenNode IntoKeyword {
get { return GetChildByRole(IntoKeywordRole); }
}
public string Identifier {
get {
return GetChildByRole(Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, Decompiler.CSharp.Syntax.Identifier.Create(value));
}
}
public Identifier IdentifierToken {
get { return GetChildByRole(Roles.Identifier); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryContinuationClause(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryContinuationClause(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryContinuationClause(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryContinuationClause o = other as QueryContinuationClause;
return o != null && MatchString(this.Identifier, o.Identifier) && this.PrecedingQuery.DoMatch(o.PrecedingQuery, match);
}
}
public class QueryFromClause : QueryClause
{
public static readonly TokenRole FromKeywordRole = new TokenRole("from");
public static readonly TokenRole InKeywordRole = new TokenRole("in");
public CSharpTokenNode FromKeyword {
get { return GetChildByRole(FromKeywordRole); }
}
public AstType Type {
get { return GetChildByRole(Roles.Type); }
set { SetChildByRole(Roles.Type, value); }
}
public string Identifier {
get {
return GetChildByRole(Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, Decompiler.CSharp.Syntax.Identifier.Create(value));
}
}
public Identifier IdentifierToken {
get { return GetChildByRole(Roles.Identifier); }
}
public CSharpTokenNode InKeyword {
get { return GetChildByRole(InKeywordRole); }
}
public Expression Expression {
get { return GetChildByRole(Roles.Expression); }
set { SetChildByRole(Roles.Expression, value); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryFromClause(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryFromClause(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryFromClause(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryFromClause o = other as QueryFromClause;
return o != null && this.Type.DoMatch(o.Type, match) && MatchString(this.Identifier, o.Identifier)
&& this.Expression.DoMatch(o.Expression, match);
}
}
public class QueryLetClause : QueryClause
{
public readonly static TokenRole LetKeywordRole = new TokenRole("let");
public CSharpTokenNode LetKeyword {
get { return GetChildByRole(LetKeywordRole); }
}
public string Identifier {
get {
return GetChildByRole(Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, Decompiler.CSharp.Syntax.Identifier.Create(value));
}
}
public Identifier IdentifierToken {
get { return GetChildByRole(Roles.Identifier); }
}
public CSharpTokenNode AssignToken {
get { return GetChildByRole(Roles.Assign); }
}
public Expression Expression {
get { return GetChildByRole(Roles.Expression); }
set { SetChildByRole(Roles.Expression, value); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryLetClause(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryLetClause(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryLetClause(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryLetClause o = other as QueryLetClause;
return o != null && MatchString(this.Identifier, o.Identifier) && this.Expression.DoMatch(o.Expression, match);
}
}
public class QueryWhereClause : QueryClause
{
public readonly static TokenRole WhereKeywordRole = new TokenRole("where");
public CSharpTokenNode WhereKeyword {
get { return GetChildByRole(WhereKeywordRole); }
}
public Expression Condition {
get { return GetChildByRole(Roles.Condition); }
set { SetChildByRole(Roles.Condition, value); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryWhereClause(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryWhereClause(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryWhereClause(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryWhereClause o = other as QueryWhereClause;
return o != null && this.Condition.DoMatch(o.Condition, match);
}
}
/// <summary>
/// Represents a join or group join clause.
/// </summary>
public class QueryJoinClause : QueryClause
{
public static readonly TokenRole JoinKeywordRole = new TokenRole("join");
public static readonly Role<AstType> TypeRole = Roles.Type;
public static readonly Role<Identifier> JoinIdentifierRole = Roles.Identifier;
public static readonly TokenRole InKeywordRole = new TokenRole("in");
public static readonly Role<Expression> InExpressionRole = Roles.Expression;
public static readonly TokenRole OnKeywordRole = new TokenRole("on");
public static readonly Role<Expression> OnExpressionRole = new Role<Expression>("OnExpression", Expression.Null);
public static readonly TokenRole EqualsKeywordRole = new TokenRole("equals");
public static readonly Role<Expression> EqualsExpressionRole = new Role<Expression>("EqualsExpression", Expression.Null);
public static readonly TokenRole IntoKeywordRole = new TokenRole("into");
public static readonly Role<Identifier> IntoIdentifierRole = new Role<Identifier>("IntoIdentifier", Identifier.Null);
public bool IsGroupJoin {
get { return !string.IsNullOrEmpty(this.IntoIdentifier); }
}
public CSharpTokenNode JoinKeyword {
get { return GetChildByRole(JoinKeywordRole); }
}
public AstType Type {
get { return GetChildByRole(TypeRole); }
set { SetChildByRole(TypeRole, value); }
}
public string JoinIdentifier {
get {
return GetChildByRole(JoinIdentifierRole).Name;
}
set {
SetChildByRole(JoinIdentifierRole, Identifier.Create(value));
}
}
public Identifier JoinIdentifierToken {
get { return GetChildByRole(JoinIdentifierRole); }
}
public CSharpTokenNode InKeyword {
get { return GetChildByRole(InKeywordRole); }
}
public Expression InExpression {
get { return GetChildByRole(InExpressionRole); }
set { SetChildByRole(InExpressionRole, value); }
}
public CSharpTokenNode OnKeyword {
get { return GetChildByRole(OnKeywordRole); }
}
public Expression OnExpression {
get { return GetChildByRole(OnExpressionRole); }
set { SetChildByRole(OnExpressionRole, value); }
}
public CSharpTokenNode EqualsKeyword {
get { return GetChildByRole(EqualsKeywordRole); }
}
public Expression EqualsExpression {
get { return GetChildByRole(EqualsExpressionRole); }
set { SetChildByRole(EqualsExpressionRole, value); }
}
public CSharpTokenNode IntoKeyword {
get { return GetChildByRole(IntoKeywordRole); }
}
public string IntoIdentifier {
get {
return GetChildByRole(IntoIdentifierRole).Name;
}
set {
SetChildByRole(IntoIdentifierRole, Identifier.Create(value));
}
}
public Identifier IntoIdentifierToken {
get { return GetChildByRole(IntoIdentifierRole); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryJoinClause(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryJoinClause(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryJoinClause(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryJoinClause o = other as QueryJoinClause;
return o != null && this.IsGroupJoin == o.IsGroupJoin
&& this.Type.DoMatch(o.Type, match) && MatchString(this.JoinIdentifier, o.JoinIdentifier)
&& this.InExpression.DoMatch(o.InExpression, match) && this.OnExpression.DoMatch(o.OnExpression, match)
&& this.EqualsExpression.DoMatch(o.EqualsExpression, match)
&& MatchString(this.IntoIdentifier, o.IntoIdentifier);
}
}
public class QueryOrderClause : QueryClause
{
public static readonly TokenRole OrderbyKeywordRole = new TokenRole("orderby");
public static readonly Role<QueryOrdering> OrderingRole = new Role<QueryOrdering>("Ordering", null);
public CSharpTokenNode OrderbyToken {
get { return GetChildByRole(OrderbyKeywordRole); }
}
public AstNodeCollection<QueryOrdering> Orderings {
get { return GetChildrenByRole(OrderingRole); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryOrderClause(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryOrderClause(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryOrderClause(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryOrderClause o = other as QueryOrderClause;
return o != null && this.Orderings.DoMatch(o.Orderings, match);
}
}
public class QueryOrdering : AstNode
{
public readonly static TokenRole AscendingKeywordRole = new TokenRole("ascending");
public readonly static TokenRole DescendingKeywordRole = new TokenRole("descending");
public override NodeType NodeType {
get { return NodeType.Unknown; }
}
public Expression Expression {
get { return GetChildByRole(Roles.Expression); }
set { SetChildByRole(Roles.Expression, value); }
}
public QueryOrderingDirection Direction {
get;
set;
}
public CSharpTokenNode DirectionToken {
get { return Direction == QueryOrderingDirection.Ascending ? GetChildByRole(AscendingKeywordRole) : GetChildByRole(DescendingKeywordRole); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryOrdering(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryOrdering(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryOrdering(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryOrdering o = other as QueryOrdering;
return o != null && this.Direction == o.Direction && this.Expression.DoMatch(o.Expression, match);
}
}
public enum QueryOrderingDirection
{
None,
Ascending,
Descending
}
public class QuerySelectClause : QueryClause
{
public readonly static TokenRole SelectKeywordRole = new TokenRole("select");
public CSharpTokenNode SelectKeyword {
get { return GetChildByRole(SelectKeywordRole); }
}
public Expression Expression {
get { return GetChildByRole(Roles.Expression); }
set { SetChildByRole(Roles.Expression, value); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQuerySelectClause(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQuerySelectClause(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQuerySelectClause(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QuerySelectClause o = other as QuerySelectClause;
return o != null && this.Expression.DoMatch(o.Expression, match);
}
}
public class QueryGroupClause : QueryClause
{
public static readonly TokenRole GroupKeywordRole = new TokenRole("group");
public static readonly Role<Expression> ProjectionRole = new Role<Expression>("Projection", Expression.Null);
public static readonly TokenRole ByKeywordRole = new TokenRole("by");
public static readonly Role<Expression> KeyRole = new Role<Expression>("Key", Expression.Null);
public CSharpTokenNode GroupKeyword {
get { return GetChildByRole(GroupKeywordRole); }
}
public Expression Projection {
get { return GetChildByRole(ProjectionRole); }
set { SetChildByRole(ProjectionRole, value); }
}
public CSharpTokenNode ByKeyword {
get { return GetChildByRole(ByKeywordRole); }
}
public Expression Key {
get { return GetChildByRole(KeyRole); }
set { SetChildByRole(KeyRole, value); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitQueryGroupClause(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitQueryGroupClause(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitQueryGroupClause(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
QueryGroupClause o = other as QueryGroupClause;
return o != null && this.Projection.DoMatch(o.Projection, match) && this.Key.DoMatch(o.Key, match);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs",
"repo_id": "ILSpy",
"token_count": 5958
} | 225 |
//
// AttributeSection.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>
/// [AttributeTarget: Attributes]
/// </summary>
public class AttributeSection : AstNode
{
#region PatternPlaceholder
public static implicit operator AttributeSection(PatternMatching.Pattern pattern)
{
return pattern != null ? new PatternPlaceholder(pattern) : null;
}
sealed class PatternPlaceholder : AttributeSection, 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 override NodeType NodeType {
get {
return NodeType.Unknown;
}
}
public CSharpTokenNode LBracketToken {
get { return GetChildByRole(Roles.LBracket); }
}
public string AttributeTarget {
get {
return GetChildByRole(Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, Identifier.Create(value));
}
}
public Identifier AttributeTargetToken {
get {
return GetChildByRole(Roles.Identifier);
}
set {
SetChildByRole(Roles.Identifier, value);
}
}
public AstNodeCollection<Attribute> Attributes {
get { return base.GetChildrenByRole(Roles.Attribute); }
}
public CSharpTokenNode RBracketToken {
get { return GetChildByRole(Roles.RBracket); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitAttributeSection(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitAttributeSection(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitAttributeSection(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
AttributeSection o = other as AttributeSection;
return o != null && MatchString(this.AttributeTarget, o.AttributeTarget) && this.Attributes.DoMatch(o.Attributes, match);
}
public AttributeSection()
{
}
public AttributeSection(Attribute attr)
{
this.Attributes.Add(attr);
}
// public static string GetAttributeTargetName(AttributeTarget attributeTarget)
// {
// switch (attributeTarget) {
// case AttributeTarget.None:
// return null;
// case AttributeTarget.Assembly:
// return "assembly";
// case AttributeTarget.Module:
// return "module";
// case AttributeTarget.Type:
// return "type";
// case AttributeTarget.Param:
// return "param";
// case AttributeTarget.Field:
// return "field";
// case AttributeTarget.Return:
// return "return";
// case AttributeTarget.Method:
// return "method";
// default:
// throw new NotSupportedException("Invalid value for AttributeTarget");
// }
// }
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs",
"repo_id": "ILSpy",
"token_count": 1704
} | 226 |
//
// FullTypeName.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
using ICSharpCode.Decompiler.CSharp.Resolver;
using ICSharpCode.Decompiler.CSharp.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
public class MemberType : AstType
{
public static readonly Role<AstType> TargetRole = new Role<AstType>("Target", AstType.Null);
bool isDoubleColon;
public bool IsDoubleColon {
get { return isDoubleColon; }
set {
ThrowIfFrozen();
isDoubleColon = value;
}
}
public AstType Target {
get { return GetChildByRole(TargetRole); }
set { SetChildByRole(TargetRole, value); }
}
public string MemberName {
get {
return GetChildByRole(Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, Identifier.Create(value));
}
}
public Identifier MemberNameToken {
get {
return GetChildByRole(Roles.Identifier);
}
set {
SetChildByRole(Roles.Identifier, value);
}
}
public AstNodeCollection<AstType> TypeArguments {
get { return GetChildrenByRole(Roles.TypeArgument); }
}
public MemberType()
{
}
public MemberType(AstType target, string memberName)
{
this.Target = target;
this.MemberName = memberName;
}
public MemberType(AstType target, string memberName, IEnumerable<AstType> typeArguments)
{
this.Target = target;
this.MemberName = memberName;
foreach (var arg in typeArguments)
{
AddChild(arg, Roles.TypeArgument);
}
}
public MemberType(AstType target, string memberName, params AstType[] typeArguments) : this(target, memberName, (IEnumerable<AstType>)typeArguments)
{
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitMemberType(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitMemberType(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitMemberType(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
MemberType o = other as MemberType;
return o != null && this.IsDoubleColon == o.IsDoubleColon
&& MatchString(this.MemberName, o.MemberName) && this.Target.DoMatch(o.Target, match)
&& this.TypeArguments.DoMatch(o.TypeArguments, match);
}
public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null)
{
if (interningProvider == null)
interningProvider = InterningProvider.Dummy;
TypeOrNamespaceReference t;
if (this.IsDoubleColon)
{
SimpleType st = this.Target as SimpleType;
if (st != null)
{
t = interningProvider.Intern(new AliasNamespaceReference(interningProvider.Intern(st.Identifier)));
}
else
{
t = null;
}
}
else
{
t = this.Target.ToTypeReference(lookupMode, interningProvider) as TypeOrNamespaceReference;
}
if (t == null)
return SpecialType.UnknownType;
var typeArguments = new List<ITypeReference>();
foreach (var ta in this.TypeArguments)
{
typeArguments.Add(ta.ToTypeReference(lookupMode, interningProvider));
}
string memberName = interningProvider.Intern(this.MemberName);
return interningProvider.Intern(new MemberTypeOrNamespaceReference(t, memberName, interningProvider.InternList(typeArguments), lookupMode));
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs",
"repo_id": "ILSpy",
"token_count": 1612
} | 227 |
//
// Roles.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin <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.
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
public static class Roles
{
public static readonly Role<AstNode> Root = AstNode.RootRole;
// some pre defined constants for common roles
public static readonly Role<Identifier> Identifier = new Role<Identifier>("Identifier", Syntax.Identifier.Null);
public static readonly Role<BlockStatement> Body = new Role<BlockStatement>("Body", BlockStatement.Null);
public static readonly Role<ParameterDeclaration> Parameter = new Role<ParameterDeclaration>("Parameter", null);
public static readonly Role<Expression> Argument = new Role<Expression>("Argument", Syntax.Expression.Null);
public static readonly Role<AstType> Type = new Role<AstType>("Type", AstType.Null);
public static readonly Role<Expression> Expression = new Role<Expression>("Expression", Syntax.Expression.Null);
public static readonly Role<Expression> TargetExpression = new Role<Expression>("Target", Syntax.Expression.Null);
public readonly static Role<Expression> Condition = new Role<Expression>("Condition", Syntax.Expression.Null);
public static readonly Role<TypeParameterDeclaration> TypeParameter = new Role<TypeParameterDeclaration>("TypeParameter", null);
public static readonly Role<AstType> TypeArgument = new Role<AstType>("TypeArgument", AstType.Null);
public readonly static Role<Constraint> Constraint = new Role<Constraint>("Constraint", null);
public static readonly Role<VariableInitializer> Variable = new Role<VariableInitializer>("Variable", VariableInitializer.Null);
public static readonly Role<Statement> EmbeddedStatement = new Role<Statement>("EmbeddedStatement", Statement.Null);
public readonly static Role<EntityDeclaration> TypeMemberRole = new Role<EntityDeclaration>("TypeMember", null);
public static readonly Role<VariableDesignation> VariableDesignationRole = new Role<VariableDesignation>("VariableDesignation", VariableDesignation.Null);
// public static readonly TokenRole Keyword = new TokenRole ("Keyword", CSharpTokenNode.Null);
// public static readonly TokenRole InKeyword = new TokenRole ("InKeyword", CSharpTokenNode.Null);
// some pre defined constants for most used punctuation
public static readonly TokenRole LPar = new TokenRole("(");
public static readonly TokenRole RPar = new TokenRole(")");
public static readonly TokenRole LBracket = new TokenRole("[");
public static readonly TokenRole RBracket = new TokenRole("]");
public static readonly TokenRole LBrace = new TokenRole("{");
public static readonly TokenRole RBrace = new TokenRole("}");
public static readonly TokenRole LChevron = new TokenRole("<");
public static readonly TokenRole RChevron = new TokenRole(">");
public static readonly TokenRole Comma = new TokenRole(",");
public static readonly TokenRole Dot = new TokenRole(".");
public static readonly TokenRole Semicolon = new TokenRole(";");
public static readonly TokenRole Assign = new TokenRole("=");
public static readonly TokenRole Colon = new TokenRole(":");
public static readonly TokenRole DoubleColon = new TokenRole("::");
public static readonly TokenRole Arrow = new TokenRole("=>");
public static readonly TokenRole DoubleExclamation = new TokenRole("!!");
public static readonly Role<Comment> Comment = new Role<Comment>("Comment", null);
public static readonly Role<PreProcessorDirective> PreProcessorDirective = new Role<PreProcessorDirective>("PreProcessorDirective", null);
public readonly static Role<AstType> BaseType = new Role<AstType>("BaseType", AstType.Null);
public static readonly Role<Attribute> Attribute = new Role<Attribute>("Attribute", null);
public static readonly Role<CSharpTokenNode> AttributeTargetRole = new Role<CSharpTokenNode>("AttributeTarget", CSharpTokenNode.Null);
public readonly static TokenRole WhereKeyword = new TokenRole("where");
public readonly static Role<SimpleType> ConstraintTypeParameter = new Role<SimpleType>("TypeParameter", SimpleType.Null);
public readonly static TokenRole DelegateKeyword = new TokenRole("delegate");
public static readonly TokenRole ExternKeyword = new TokenRole("extern");
public static readonly TokenRole AliasKeyword = new TokenRole("alias");
public static readonly TokenRole NamespaceKeyword = new TokenRole("namespace");
public static readonly TokenRole EnumKeyword = new TokenRole("enum");
public static readonly TokenRole InterfaceKeyword = new TokenRole("interface");
public static readonly TokenRole StructKeyword = new TokenRole("struct");
public static readonly TokenRole ClassKeyword = new TokenRole("class");
public static readonly TokenRole RecordKeyword = new TokenRole("record");
public static readonly TokenRole RecordStructKeyword = new TokenRole("record");
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Roles.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Roles.cs",
"repo_id": "ILSpy",
"token_count": 1646
} | 228 |
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
/// <summary>
/// A specific role only used for C# tokens
/// </summary>
public sealed class TokenRole : Role<CSharpTokenNode>
{
/// <summary>
/// Gets the token as string. Note that the token Name and Token value may differ.
/// </summary>
public string Token { get; }
/// <summary>
/// Gets the char length of the token.
/// </summary>
public int Length { get; }
public TokenRole(string token) : base(token, CSharpTokenNode.Null)
{
this.Token = token;
this.Length = token.Length;
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TokenRole.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TokenRole.cs",
"repo_id": "ILSpy",
"token_count": 198
} | 229 |
//
// VariableInitializer.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
{
public class VariableInitializer : AstNode
{
#region Null
public new static readonly VariableInitializer Null = new NullVariableInitializer();
sealed class NullVariableInitializer : VariableInitializer
{
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
#region PatternPlaceholder
public static implicit operator VariableInitializer(PatternMatching.Pattern pattern)
{
return pattern != null ? new PatternPlaceholder(pattern) : null;
}
sealed class PatternPlaceholder : VariableInitializer, 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 override NodeType NodeType {
get {
return NodeType.Unknown;
}
}
public VariableInitializer()
{
}
public VariableInitializer(string name, Expression initializer = null)
{
this.Name = name;
this.Initializer = initializer;
}
public string Name {
get {
return GetChildByRole(Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, Identifier.Create(value));
}
}
public Identifier NameToken {
get {
return GetChildByRole(Roles.Identifier);
}
set {
SetChildByRole(Roles.Identifier, value);
}
}
public CSharpTokenNode AssignToken {
get { return GetChildByRole(Roles.Assign); }
}
public Expression Initializer {
get { return GetChildByRole(Roles.Expression); }
set { SetChildByRole(Roles.Expression, value); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitVariableInitializer(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitVariableInitializer(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitVariableInitializer(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
VariableInitializer o = other as VariableInitializer;
return o != null && MatchString(this.Name, o.Name) && this.Initializer.DoMatch(o.Initializer, match);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs",
"repo_id": "ILSpy",
"token_count": 1644
} | 230 |
// 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.Linq;
using ICSharpCode.Decompiler.CSharp.Resolver;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.Semantics;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.CSharp.Transforms
{
public class IntroduceUnsafeModifier : DepthFirstAstVisitor<bool>, IAstTransform
{
public void Run(AstNode compilationUnit, TransformContext context)
{
compilationUnit.AcceptVisitor(this);
}
public static bool IsUnsafe(AstNode node)
{
return node.AcceptVisitor(new IntroduceUnsafeModifier());
}
protected override bool VisitChildren(AstNode node)
{
bool result = false;
AstNode next;
for (AstNode child = node.FirstChild; child != null; child = next)
{
// Store next to allow the loop to continue
// if the visitor removes/replaces child.
next = child.NextSibling;
result |= child.AcceptVisitor(this);
}
if (result && node is EntityDeclaration && !(node is Accessor))
{
((EntityDeclaration)node).Modifiers |= Modifiers.Unsafe;
return false;
}
return result;
}
public override bool VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
{
base.VisitPointerReferenceExpression(pointerReferenceExpression);
return true;
}
public override bool VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
{
// C# sizeof(MyStruct) requires unsafe{}
// (not for sizeof(int), but that gets constant-folded and thus decompiled to 4)
base.VisitSizeOfExpression(sizeOfExpression);
return true;
}
public override bool VisitComposedType(ComposedType composedType)
{
if (composedType.PointerRank > 0)
return true;
else
return base.VisitComposedType(composedType);
}
public override bool VisitFunctionPointerType(FunctionPointerAstType functionPointerType)
{
return true;
}
public override bool VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
{
bool result = base.VisitUnaryOperatorExpression(unaryOperatorExpression);
if (unaryOperatorExpression.Operator == UnaryOperatorType.Dereference)
{
var bop = unaryOperatorExpression.Expression as BinaryOperatorExpression;
if (bop != null && bop.Operator == BinaryOperatorType.Add
&& bop.GetResolveResult() is OperatorResolveResult orr
&& orr.Operands.FirstOrDefault()?.Type.Kind == TypeKind.Pointer)
{
// transform "*(ptr + int)" to "ptr[int]"
IndexerExpression indexer = new IndexerExpression();
indexer.Target = bop.Left.Detach();
indexer.Arguments.Add(bop.Right.Detach());
indexer.CopyAnnotationsFrom(unaryOperatorExpression);
indexer.CopyAnnotationsFrom(bop);
unaryOperatorExpression.ReplaceWith(indexer);
}
return true;
}
else if (unaryOperatorExpression.Operator == UnaryOperatorType.AddressOf)
{
return true;
}
else
{
return result;
}
}
public override bool VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
{
bool result = base.VisitMemberReferenceExpression(memberReferenceExpression);
UnaryOperatorExpression uoe = memberReferenceExpression.Target as UnaryOperatorExpression;
if (uoe != null && uoe.Operator == UnaryOperatorType.Dereference)
{
PointerReferenceExpression pre = new PointerReferenceExpression();
pre.Target = uoe.Expression.Detach();
pre.MemberName = memberReferenceExpression.MemberName;
memberReferenceExpression.TypeArguments.MoveTo(pre.TypeArguments);
pre.CopyAnnotationsFrom(uoe);
pre.RemoveAnnotations<ResolveResult>(); // only copy the ResolveResult from the MRE
pre.CopyAnnotationsFrom(memberReferenceExpression);
memberReferenceExpression.ReplaceWith(pre);
}
if (HasUnsafeResolveResult(memberReferenceExpression))
return true;
return result;
}
public override bool VisitIdentifierExpression(IdentifierExpression identifierExpression)
{
bool result = base.VisitIdentifierExpression(identifierExpression);
if (HasUnsafeResolveResult(identifierExpression))
return true;
return result;
}
public override bool VisitStackAllocExpression(StackAllocExpression stackAllocExpression)
{
bool result = base.VisitStackAllocExpression(stackAllocExpression);
if (HasUnsafeResolveResult(stackAllocExpression))
return true;
return result;
}
public override bool VisitInvocationExpression(InvocationExpression invocationExpression)
{
bool result = base.VisitInvocationExpression(invocationExpression);
if (HasUnsafeResolveResult(invocationExpression))
return true;
return result;
}
public override bool VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
{
base.VisitFixedVariableInitializer(fixedVariableInitializer);
return true;
}
private bool HasUnsafeResolveResult(AstNode node)
{
var rr = node.GetResolveResult();
if (rr == null)
return false;
if (IsUnsafeType(rr.Type))
return true;
if ((rr as MemberResolveResult)?.Member is IParameterizedMember pm)
{
if (pm.Parameters.Any(p => IsUnsafeType(p.Type)))
return true;
}
else if (rr is MethodGroupResolveResult)
{
var chosenMethod = node.GetSymbol();
if (chosenMethod is IParameterizedMember pm2)
{
if (IsUnsafeType(pm2.ReturnType))
return true;
if (pm2.Parameters.Any(p => IsUnsafeType(p.Type)))
return true;
}
}
return false;
}
private bool IsUnsafeType(IType type)
{
switch (type?.Kind)
{
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
return true;
case TypeKind.ByReference:
case TypeKind.Array:
return IsUnsafeType(((Decompiler.TypeSystem.Implementation.TypeWithElementType)type).ElementType);
default:
return false;
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs",
"repo_id": "ILSpy",
"token_count": 2403
} | 231 |
// 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 ICSharpCode.Decompiler.CSharp.Resolver;
using ICSharpCode.Decompiler.Semantics;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.CSharp.TypeSystem
{
/// <summary>
/// Represents a simple C# name. (a single non-qualified identifier with an optional list of type arguments)
/// </summary>
[Serializable]
public sealed class SimpleTypeOrNamespaceReference : TypeOrNamespaceReference, ISupportsInterning
{
readonly string identifier;
readonly IList<ITypeReference> typeArguments;
readonly NameLookupMode lookupMode;
public SimpleTypeOrNamespaceReference(string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type)
{
if (identifier == null)
throw new ArgumentNullException(nameof(identifier));
this.identifier = identifier;
this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
this.lookupMode = lookupMode;
}
public string Identifier {
get { return identifier; }
}
public IList<ITypeReference> TypeArguments {
get { return typeArguments; }
}
public NameLookupMode LookupMode {
get { return lookupMode; }
}
/// <summary>
/// Adds a suffix to the identifier.
/// Does not modify the existing type reference, but returns a new one.
/// </summary>
public SimpleTypeOrNamespaceReference AddSuffix(string suffix)
{
return new SimpleTypeOrNamespaceReference(identifier + suffix, typeArguments, lookupMode);
}
public override ResolveResult Resolve(CSharpResolver resolver)
{
var typeArgs = typeArguments.Resolve(resolver.CurrentTypeResolveContext);
return resolver.LookupSimpleNameOrTypeName(identifier, typeArgs, lookupMode);
}
public override IType ResolveType(CSharpResolver resolver)
{
TypeResolveResult trr = Resolve(resolver) as TypeResolveResult;
return trr != null ? trr.Type : new UnknownType(null, identifier, typeArguments.Count);
}
public override string ToString()
{
if (typeArguments.Count == 0)
return identifier;
else
return identifier + "<" + string.Join(",", typeArguments) + ">";
}
int ISupportsInterning.GetHashCodeForInterning()
{
int hashCode = 0;
unchecked
{
hashCode += 1000000021 * identifier.GetHashCode();
hashCode += 1000000033 * typeArguments.GetHashCode();
hashCode += 1000000087 * (int)lookupMode;
}
return hashCode;
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
SimpleTypeOrNamespaceReference o = other as SimpleTypeOrNamespaceReference;
return o != null && this.identifier == o.identifier
&& this.typeArguments == o.typeArguments && this.lookupMode == o.lookupMode;
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs",
"repo_id": "ILSpy",
"token_count": 1243
} | 232 |
// 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.Immutable;
using System.Reflection.Metadata;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.Metadata;
namespace ICSharpCode.Decompiler.Disassembler
{
public class DisassemblerSignatureTypeProvider : ISignatureTypeProvider<Action<ILNameSyntax>, MetadataGenericContext>
{
readonly MetadataFile module;
readonly MetadataReader metadata;
readonly ITextOutput output;
public DisassemblerSignatureTypeProvider(MetadataFile module, ITextOutput output)
{
this.module = module ?? throw new ArgumentNullException(nameof(module));
this.output = output ?? throw new ArgumentNullException(nameof(output));
this.metadata = module.Metadata;
}
public Action<ILNameSyntax> GetArrayType(Action<ILNameSyntax> elementType, ArrayShape shape)
{
return syntax => {
var syntaxForElementTypes = syntax == ILNameSyntax.SignatureNoNamedTypeParameters ? syntax : ILNameSyntax.Signature;
elementType(syntaxForElementTypes);
output.Write('[');
for (int i = 0; i < shape.Rank; i++)
{
if (i > 0)
output.Write(", ");
if (i < shape.LowerBounds.Length || i < shape.Sizes.Length)
{
int lower = 0;
if (i < shape.LowerBounds.Length)
{
lower = shape.LowerBounds[i];
output.Write(lower.ToString());
}
output.Write("...");
if (i < shape.Sizes.Length)
output.Write((lower + shape.Sizes[i] - 1).ToString());
}
}
output.Write(']');
};
}
public Action<ILNameSyntax> GetByReferenceType(Action<ILNameSyntax> elementType)
{
return syntax => {
var syntaxForElementTypes = syntax == ILNameSyntax.SignatureNoNamedTypeParameters ? syntax : ILNameSyntax.Signature;
elementType(syntaxForElementTypes);
output.Write('&');
};
}
public Action<ILNameSyntax> GetFunctionPointerType(MethodSignature<Action<ILNameSyntax>> signature)
{
return syntax => {
output.Write("method ");
signature.Header.WriteTo(output);
signature.ReturnType(syntax);
output.Write(" *(");
for (int i = 0; i < signature.ParameterTypes.Length; i++)
{
if (i > 0)
output.Write(", ");
signature.ParameterTypes[i](syntax);
}
output.Write(')');
};
}
public Action<ILNameSyntax> GetGenericInstantiation(Action<ILNameSyntax> genericType, ImmutableArray<Action<ILNameSyntax>> typeArguments)
{
return syntax => {
var syntaxForElementTypes = syntax == ILNameSyntax.SignatureNoNamedTypeParameters ? syntax : ILNameSyntax.Signature;
genericType(syntaxForElementTypes);
output.Write('<');
for (int i = 0; i < typeArguments.Length; i++)
{
if (i > 0)
output.Write(", ");
typeArguments[i](syntaxForElementTypes);
}
output.Write('>');
};
}
public Action<ILNameSyntax> GetGenericMethodParameter(MetadataGenericContext genericContext, int index)
{
return syntax => {
output.Write("!!");
WriteTypeParameter(genericContext.GetGenericMethodTypeParameterHandleOrNull(index), index, syntax);
};
}
public Action<ILNameSyntax> GetGenericTypeParameter(MetadataGenericContext genericContext, int index)
{
return syntax => {
output.Write("!");
WriteTypeParameter(genericContext.GetGenericTypeParameterHandleOrNull(index), index, syntax);
};
}
void WriteTypeParameter(GenericParameterHandle paramRef, int index, ILNameSyntax syntax)
{
if (paramRef.IsNil || syntax == ILNameSyntax.SignatureNoNamedTypeParameters)
output.Write(index.ToString());
else
{
var param = metadata.GetGenericParameter(paramRef);
if (param.Name.IsNil)
output.Write(param.Index.ToString());
else
output.Write(DisassemblerHelpers.Escape(metadata.GetString(param.Name)));
}
}
public Action<ILNameSyntax> GetModifiedType(Action<ILNameSyntax> modifier, Action<ILNameSyntax> unmodifiedType, bool isRequired)
{
return syntax => {
unmodifiedType(syntax);
if (isRequired)
output.Write(" modreq");
else
output.Write(" modopt");
output.Write('(');
modifier(ILNameSyntax.TypeName);
output.Write(')');
};
}
public Action<ILNameSyntax> GetPinnedType(Action<ILNameSyntax> elementType)
{
return syntax => {
var syntaxForElementTypes = syntax == ILNameSyntax.SignatureNoNamedTypeParameters ? syntax : ILNameSyntax.Signature;
elementType(syntaxForElementTypes);
output.Write(" pinned");
};
}
public Action<ILNameSyntax> GetPointerType(Action<ILNameSyntax> elementType)
{
return syntax => {
var syntaxForElementTypes = syntax == ILNameSyntax.SignatureNoNamedTypeParameters ? syntax : ILNameSyntax.Signature;
elementType(syntaxForElementTypes);
output.Write('*');
};
}
public Action<ILNameSyntax> GetPrimitiveType(PrimitiveTypeCode typeCode)
{
switch (typeCode)
{
case PrimitiveTypeCode.SByte:
return syntax => output.Write("int8");
case PrimitiveTypeCode.Int16:
return syntax => output.Write("int16");
case PrimitiveTypeCode.Int32:
return syntax => output.Write("int32");
case PrimitiveTypeCode.Int64:
return syntax => output.Write("int64");
case PrimitiveTypeCode.Byte:
return syntax => output.Write("uint8");
case PrimitiveTypeCode.UInt16:
return syntax => output.Write("uint16");
case PrimitiveTypeCode.UInt32:
return syntax => output.Write("uint32");
case PrimitiveTypeCode.UInt64:
return syntax => output.Write("uint64");
case PrimitiveTypeCode.Single:
return syntax => output.Write("float32");
case PrimitiveTypeCode.Double:
return syntax => output.Write("float64");
case PrimitiveTypeCode.Void:
return syntax => output.Write("void");
case PrimitiveTypeCode.Boolean:
return syntax => output.Write("bool");
case PrimitiveTypeCode.String:
return syntax => output.Write("string");
case PrimitiveTypeCode.Char:
return syntax => output.Write("char");
case PrimitiveTypeCode.Object:
return syntax => output.Write("object");
case PrimitiveTypeCode.IntPtr:
return syntax => output.Write("native int");
case PrimitiveTypeCode.UIntPtr:
return syntax => output.Write("native uint");
case PrimitiveTypeCode.TypedReference:
return syntax => output.Write("typedref");
default:
throw new ArgumentOutOfRangeException();
}
}
public Action<ILNameSyntax> GetSZArrayType(Action<ILNameSyntax> elementType)
{
return syntax => {
var syntaxForElementTypes = syntax == ILNameSyntax.SignatureNoNamedTypeParameters ? syntax : ILNameSyntax.Signature;
elementType(syntaxForElementTypes);
output.Write('[');
output.Write(']');
};
}
public Action<ILNameSyntax> GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
{
return syntax => {
switch (rawTypeKind)
{
case 0x00:
break;
case 0x11:
output.Write("valuetype ");
break;
case 0x12:
output.Write("class ");
break;
default:
throw new BadImageFormatException($"Unexpected rawTypeKind: {rawTypeKind} (0x{rawTypeKind:x})");
}
((EntityHandle)handle).WriteTo(module, output, default);
};
}
public Action<ILNameSyntax> GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
{
return syntax => {
switch (rawTypeKind)
{
case 0x00:
break;
case 0x11:
output.Write("valuetype ");
break;
case 0x12:
output.Write("class ");
break;
default:
throw new BadImageFormatException($"Unexpected rawTypeKind: {rawTypeKind} (0x{rawTypeKind:x})");
}
((EntityHandle)handle).WriteTo(module, output, default);
};
}
public Action<ILNameSyntax> GetTypeFromSpecification(MetadataReader reader, MetadataGenericContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind)
{
return reader.GetTypeSpecification(handle).DecodeSignature(this, genericContext);
}
}
}
| ILSpy/ICSharpCode.Decompiler/Disassembler/DisassemblerSignatureTypeProvider.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Disassembler/DisassemblerSignatureTypeProvider.cs",
"repo_id": "ILSpy",
"token_count": 3356
} | 233 |
// 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.Generic;
using System.Diagnostics;
using System.Threading;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.FlowAnalysis
{
/// <summary>
/// DataFlowVisitor that performs definite assignment analysis.
/// </summary>
class DefiniteAssignmentVisitor : DataFlowVisitor<DefiniteAssignmentVisitor.State>
{
/// <summary>
/// State for definite assignment analysis.
/// </summary>
[DebuggerDisplay("{bits}")]
public struct State : IDataFlowState<State>
{
/// <summary>
/// bits[i]: There is a code path from the entry point to this state's position
/// that does not write to function.Variables[i].
/// (i.e. the variable is not definitely assigned at the state's position)
///
/// Initial state: all bits set = nothing is definitely assigned
/// Bottom state: all bits clear
/// </summary>
readonly BitSet bits;
/// <summary>
/// Creates the initial state.
/// </summary>
public State(int variableCount)
{
this.bits = new BitSet(variableCount);
this.bits.Set(0, variableCount);
}
private State(BitSet bits)
{
this.bits = bits;
}
public bool LessThanOrEqual(State otherState)
{
return bits.IsSubsetOf(otherState.bits);
}
public State Clone()
{
return new State(bits.Clone());
}
public void ReplaceWith(State newContent)
{
bits.ReplaceWith(newContent.bits);
}
public void JoinWith(State incomingState)
{
bits.UnionWith(incomingState.bits);
}
public void TriggerFinally(State finallyState)
{
// If there is no path to the end of the try-block that leaves a variable v
// uninitialized, then there is no such path to the end of the whole try-finally either.
// (the try-finally cannot complete successfully unless the try block does the same)
// ==> any bits that are false in this.state must be false in the output state.
// Or said otherwise: a variable is definitely assigned after try-finally if it is
// definitely assigned in either the try or the finally block.
// Given that the bits are the opposite of definite assignment, this gives us:
// !outputBits[i] == !bits[i] || !finallyState.bits[i].
// and thus:
// outputBits[i] == bits[i] && finallyState.bits[i].
bits.IntersectWith(finallyState.bits);
}
public void ReplaceWithBottom()
{
bits.ClearAll();
}
public bool IsBottom {
get { return !bits.Any(); }
}
public void MarkVariableInitialized(int variableIndex)
{
bits.Clear(variableIndex);
}
public bool IsPotentiallyUninitialized(int variableIndex)
{
return bits[variableIndex];
}
}
readonly CancellationToken cancellationToken;
readonly ILFunction scope;
readonly BitSet variablesWithUninitializedUsage;
readonly Dictionary<IMethod, State> stateOfLocalFunctionUse = new Dictionary<IMethod, State>();
readonly HashSet<IMethod> localFunctionsNeedingAnalysis = new HashSet<IMethod>();
public DefiniteAssignmentVisitor(ILFunction scope, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
this.cancellationToken = cancellationToken;
this.scope = scope;
this.variablesWithUninitializedUsage = new BitSet(scope.Variables.Count);
base.flagsRequiringManualImpl |= InstructionFlags.MayReadLocals | InstructionFlags.MayWriteLocals;
Initialize(new State(scope.Variables.Count));
}
public bool IsPotentiallyUsedUninitialized(ILVariable v)
{
Debug.Assert(v.Function == scope);
return variablesWithUninitializedUsage[v.IndexInFunction];
}
void HandleStore(ILVariable v)
{
cancellationToken.ThrowIfCancellationRequested();
if (v.Function == scope)
{
// Mark the variable as initialized:
state.MarkVariableInitialized(v.IndexInFunction);
// Note that this gets called even if the store is in unreachable code,
// but that's OK because bottomState.MarkVariableInitialized() has no effect.
// After the state change, we have to call
// PropagateStateOnException() = currentStateOnException.JoinWith(state);
// but because MarkVariableInitialized() only clears a bit,
// this is guaranteed to be a no-op.
}
}
void EnsureInitialized(ILVariable v)
{
if (v.Function == scope && state.IsPotentiallyUninitialized(v.IndexInFunction))
{
variablesWithUninitializedUsage.Set(v.IndexInFunction);
}
}
protected internal override void VisitStLoc(StLoc inst)
{
inst.Value.AcceptVisitor(this);
HandleStore(inst.Variable);
}
protected override void HandleMatchStore(MatchInstruction inst)
{
HandleStore(inst.Variable);
}
protected override void BeginTryCatchHandler(TryCatchHandler inst)
{
HandleStore(inst.Variable);
base.BeginTryCatchHandler(inst);
}
protected internal override void VisitPinnedRegion(PinnedRegion inst)
{
inst.Init.AcceptVisitor(this);
HandleStore(inst.Variable);
inst.Body.AcceptVisitor(this);
}
protected internal override void VisitLdLoc(LdLoc inst)
{
EnsureInitialized(inst.Variable);
}
protected internal override void VisitLdLoca(LdLoca inst)
{
// A variable needs to be initialized before we can take it by reference.
// The exception is if the variable is passed to an out parameter (handled in VisitCall).
EnsureInitialized(inst.Variable);
}
protected internal override void VisitCall(Call inst)
{
HandleCall(inst);
}
protected internal override void VisitCallVirt(CallVirt inst)
{
HandleCall(inst);
}
protected internal override void VisitNewObj(NewObj inst)
{
HandleCall(inst);
}
protected internal override void VisitILFunction(ILFunction inst)
{
DebugStartPoint(inst);
State stateBeforeFunction = state.Clone();
State stateOnExceptionBeforeFunction = currentStateOnException.Clone();
// Note: lambdas are handled at their point of declaration.
// We immediately visit their body, because captured variables need to be definitely initialized at this point.
// We ignore the state after the lambda body (by resetting to the state before), because we don't know
// when the lambda will be invoked.
// This also makes this logic unsuitable for reaching definitions, as we wouldn't see the effect of stores in lambdas.
// Only the simpler case of definite assignment can support lambdas.
inst.Body.AcceptVisitor(this);
// For local functions, the situation is similar to lambdas.
// However, we don't use the state of the declaration site when visiting local functions,
// but instead the state(s) of their point of use.
// Because we might discover additional points of use within the local functions,
// we use a fixed-point iteration.
bool changed;
do
{
changed = false;
foreach (var nestedFunction in inst.LocalFunctions)
{
if (!localFunctionsNeedingAnalysis.Contains(nestedFunction.ReducedMethod))
continue;
localFunctionsNeedingAnalysis.Remove(nestedFunction.ReducedMethod);
State stateOnEntry = stateOfLocalFunctionUse[nestedFunction.ReducedMethod];
this.state.ReplaceWith(stateOnEntry);
this.currentStateOnException.ReplaceWith(stateOnEntry);
nestedFunction.AcceptVisitor(this);
changed = true;
}
} while (changed);
currentStateOnException = stateOnExceptionBeforeFunction;
state = stateBeforeFunction;
DebugEndPoint(inst);
}
void HandleCall(CallInstruction call)
{
DebugStartPoint(call);
bool hasOutArgs = false;
foreach (var arg in call.Arguments)
{
if (arg.MatchLdLoca(out var v) && call.GetParameter(arg.ChildIndex)?.IsOut == true)
{
// Visiting ldloca would require the variable to be initialized,
// but we don't need out arguments to be initialized.
hasOutArgs = true;
}
else
{
arg.AcceptVisitor(this);
}
}
// Mark out arguments as initialized, but only after the whole call:
if (hasOutArgs)
{
foreach (var arg in call.Arguments)
{
if (arg.MatchLdLoca(out var v) && call.GetParameter(arg.ChildIndex)?.IsOut == true)
{
HandleStore(v);
}
}
}
HandleLocalFunctionUse(call.Method);
DebugEndPoint(call);
}
/// <summary>
/// For a use of a local function, remember the current state to use as stateOnEntry when
/// later processing the local function body.
/// </summary>
void HandleLocalFunctionUse(IMethod method)
{
if (method.IsLocalFunction)
{
if (stateOfLocalFunctionUse.TryGetValue(method, out var stateOnEntry))
{
if (!state.LessThanOrEqual(stateOnEntry))
{
stateOnEntry.JoinWith(state);
localFunctionsNeedingAnalysis.Add(method);
}
}
else
{
stateOfLocalFunctionUse.Add(method, state.Clone());
localFunctionsNeedingAnalysis.Add(method);
}
}
}
protected internal override void VisitLdFtn(LdFtn inst)
{
DebugStartPoint(inst);
HandleLocalFunctionUse(inst.Method);
DebugEndPoint(inst);
}
}
}
| ILSpy/ICSharpCode.Decompiler/FlowAnalysis/DefiniteAssignmentVisitor.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/FlowAnalysis/DefiniteAssignmentVisitor.cs",
"repo_id": "ILSpy",
"token_count": 3476
} | 234 |
// 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.IL.Transforms;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.IL.ControlFlow
{
/// <summary>
/// This transform 'optimizes' the control flow logic in the IL code:
/// it replaces constructs that are generated by the C# compiler in debug mode
/// with shorter constructs that are more straightforward to analyze.
/// </summary>
/// <remarks>
/// The transformations performed are:
/// * 'nop' instructions are removed
/// * branches that lead to other branches are replaced with branches that directly jump to the destination
/// * branches that lead to a 'return block' are replaced with a return instruction
/// * basic blocks are combined where possible
/// </remarks>
public class ControlFlowSimplification : IILTransform
{
internal bool aggressivelyDuplicateReturnBlocks;
public void Run(ILFunction function, ILTransformContext context)
{
foreach (var block in function.Descendants.OfType<Block>())
{
context.CancellationToken.ThrowIfCancellationRequested();
RemoveNopInstructions(block);
RemoveDeadStackStores(block, context);
InlineVariableInReturnBlock(block, context);
// 1st pass SimplifySwitchInstruction before SimplifyBranchChains()
// starts duplicating return instructions.
SwitchDetection.SimplifySwitchInstruction(block, context);
}
SimplifyBranchChains(function, context);
CleanUpEmptyBlocks(function, context);
}
private static void RemoveNopInstructions(Block block)
{
// Move ILRanges of special nop instructions to the previous non-nop instruction.
for (int i = block.Instructions.Count - 1; i > 0; i--)
{
if (block.Instructions[i] is Nop nop && nop.Kind == NopKind.Pop)
{
block.Instructions[i - 1].AddILRange(nop);
}
}
// Remove 'nop' instructions
block.Instructions.RemoveAll(inst => inst.OpCode == OpCode.Nop);
}
private static void RemoveDeadStackStores(Block block, ILTransformContext context)
{
bool aggressive = context.Settings.RemoveDeadStores;
// Previously copy propagation did this;
// ideally the ILReader would already do this,
// for now do this here (even though it's not control-flow related).
for (int i = block.Instructions.Count - 1; i >= 0; i--)
{
if (block.Instructions[i] is StLoc stloc && stloc.Variable.IsSingleDefinition && stloc.Variable.LoadCount == 0 && stloc.Variable.Kind == VariableKind.StackSlot)
{
context.Step($"Remove dead stack store {stloc.Variable.Name}", stloc);
if (aggressive ? SemanticHelper.IsPure(stloc.Value.Flags) : IsSimple(stloc.Value))
{
Debug.Assert(SemanticHelper.IsPure(stloc.Value.Flags));
block.Instructions.RemoveAt(i++);
}
else
{
stloc.Value.AddILRange(stloc);
stloc.ReplaceWith(stloc.Value);
}
}
}
bool IsSimple(ILInstruction inst)
{
switch (inst.OpCode)
{
case OpCode.LdLoc:
case OpCode.LdStr: // C# 1.0 compiler sometimes emits redundant ldstr in switch-on-string pattern
return true;
default:
return false;
}
}
}
void InlineVariableInReturnBlock(Block block, ILTransformContext context)
{
// In debug mode, the C#-compiler generates 'return blocks' that
// unnecessarily store the return value to a local and then load it again:
// v = <inst>
// ret(v)
// (where 'v' has no other uses)
// Simplify these to a simple `ret(<inst>)` so that they match the release build version.
//
if (block.Instructions.Count == 2 && block.Instructions[1].MatchReturn(out ILInstruction value))
{
var ret = (Leave)block.Instructions[1];
if (value.MatchLdLoc(out ILVariable v)
&& v.IsSingleDefinition && v.LoadCount == 1 && block.Instructions[0].MatchStLoc(v, out ILInstruction inst))
{
context.Step("Inline variable in return block", block);
inst.AddILRange(ret.Value);
inst.AddILRange(block.Instructions[0]);
ret.Value = inst;
block.Instructions.RemoveAt(0);
}
}
}
void SimplifyBranchChains(ILFunction function, ILTransformContext context)
{
List<(Block Block, BlockContainer TargetContainer)> blocksToMove = new List<(Block, BlockContainer)>();
HashSet<Block> visitedBlocks = new HashSet<Block>();
foreach (var branch in function.Descendants.OfType<Branch>())
{
// Resolve chained branches to the final target:
var targetBlock = branch.TargetBlock;
visitedBlocks.Clear();
while (targetBlock.Instructions.Count == 1 && targetBlock.Instructions[0].OpCode == OpCode.Branch)
{
if (!visitedBlocks.Add(targetBlock))
{
// prevent infinite loop when branch chain is cyclic
break;
}
context.Step("Simplify branch to branch", branch);
var nextBranch = (Branch)targetBlock.Instructions[0];
branch.TargetBlock = nextBranch.TargetBlock;
branch.AddILRange(nextBranch);
if (targetBlock.IncomingEdgeCount == 0)
targetBlock.Instructions.Clear(); // mark the block for deletion
targetBlock = branch.TargetBlock;
}
if (IsBranchToReturnBlock(branch))
{
if (aggressivelyDuplicateReturnBlocks)
{
// Replace branches to 'return blocks' with the return instruction
context.Step("Replace branch to return with return", branch);
branch.ReplaceWith(targetBlock.Instructions[0].Clone());
}
else if (branch.TargetContainer != branch.Ancestors.OfType<BlockContainer>().First() && targetBlock.IncomingEdgeCount == 1)
{
// We don't want to always inline the return directly, because this
// might force us to place the return within a loop, when it's better
// placed outside.
// But we do want to move the return block into the correct try-finally scope,
// so that loop detection at least has the option to put it inside
// the loop body.
context.Step("Move return block into try block", branch);
BlockContainer localContainer = branch.Ancestors.OfType<BlockContainer>().First();
blocksToMove.Add((targetBlock, localContainer));
}
}
else if (targetBlock.Instructions.Count == 1 && targetBlock.Instructions[0] is Leave leave && leave.Value.MatchNop())
{
context.Step("Replace branch to leave with leave", branch);
// Replace branches to 'leave' instruction with the leave instruction
var leave2 = leave.Clone();
if (!branch.ILRangeIsEmpty) // use the ILRange of the branch if possible
leave2.AddILRange(branch);
branch.ReplaceWith(leave2);
}
if (targetBlock.IncomingEdgeCount == 0)
targetBlock.Instructions.Clear(); // mark the block for deletion
}
foreach ((Block block, BlockContainer targetContainer) in blocksToMove)
{
block.Remove();
targetContainer.Blocks.Add(block);
}
}
void CleanUpEmptyBlocks(ILFunction function, ILTransformContext context)
{
foreach (var container in function.Descendants.OfType<BlockContainer>())
{
foreach (var block in container.Blocks)
{
if (block.Instructions.Count == 0)
continue; // block is already marked for deletion
while (CombineBlockWithNextBlock(container, block, context))
{
// repeat combining blocks until it is no longer possible
// (this loop terminates because a block is deleted in every iteration)
}
}
// Remove return blocks that are no longer reachable:
container.Blocks.RemoveAll(b => b.IncomingEdgeCount == 0 && b.Instructions.Count == 0);
}
}
bool IsBranchToReturnBlock(Branch branch)
{
var targetBlock = branch.TargetBlock;
if (targetBlock.Instructions.Count != 1)
return false;
if (!targetBlock.Instructions[0].MatchReturn(out var value))
return false;
if (!value.MatchLdLoc(out var returnVar))
return false;
var container = branch.TargetContainer;
for (ILInstruction inst = branch; inst != container; inst = inst.Parent)
{
if (inst.Parent is TryFinally tryFinally && inst.SlotInfo == TryFinally.TryBlockSlot)
{
// The branch will trigger the finally block.
// Moving the return block into the try is only possible if the finally block doesn't touch the return variable.
if (returnVar.IsUsedWithin(tryFinally.FinallyBlock))
return false;
}
}
return true;
}
static bool CombineBlockWithNextBlock(BlockContainer container, Block block, ILTransformContext context)
{
Debug.Assert(container == block.Parent);
// Ensure the block will stay a basic block -- we don't want extended basic blocks prior to LoopDetection.
if (block.Instructions.Count > 1 && block.Instructions[block.Instructions.Count - 2].HasFlag(InstructionFlags.MayBranch))
return false;
Branch br = block.Instructions.Last() as Branch;
// Check whether we can combine the target block with this block
if (br == null || br.TargetBlock.Parent != container || br.TargetBlock.IncomingEdgeCount != 1)
return false;
if (br.TargetBlock == block)
return false; // don't inline block into itself
context.Step("CombineBlockWithNextBlock", br);
var targetBlock = br.TargetBlock;
if (targetBlock.StartILOffset < block.StartILOffset && IsDeadTrueStore(block))
{
// The C# compiler generates a dead store for the condition of while (true) loops.
block.Instructions.RemoveAt(block.Instructions.Count - 2);
}
if (block.ILRangeIsEmpty)
block.AddILRange(targetBlock);
block.Instructions.Remove(br);
block.Instructions.AddRange(targetBlock.Instructions);
targetBlock.Instructions.Clear(); // mark targetBlock for deletion
return true;
}
/// <summary>
/// Returns true if the last two instructions before the branch are storing the value 'true' into an unused variable.
/// </summary>
private static bool IsDeadTrueStore(Block block)
{
if (block.Instructions.Count < 2)
return false;
if (!(block.Instructions.SecondToLastOrDefault() is StLoc deadStore))
return false;
if (!(deadStore.Variable.LoadCount == 0 && deadStore.Variable.AddressCount == 0))
return false;
return deadStore.Value.MatchLdcI4(1) && deadStore.Variable.Type.IsKnownType(KnownTypeCode.Boolean);
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs",
"repo_id": "ILSpy",
"token_count": 3879
} | 235 |
#nullable enable
// Copyright (c) 2014 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler.Disassembler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL
{
public static partial class InstructionOutputExtensions
{
public static void Write(this ITextOutput output, OpCode opCode)
{
output.Write(originalOpCodeNames[(int)opCode]);
}
public static void Write(this ITextOutput output, StackType stackType)
{
output.Write(stackType.ToString().ToLowerInvariant());
}
public static void Write(this ITextOutput output, PrimitiveType primitiveType)
{
output.Write(primitiveType.ToString().ToLowerInvariant());
}
public static void WriteTo(this IType type, ITextOutput output)
{
output.WriteReference(type, type.ReflectionName);
}
public static void WriteTo(this IMember member, ITextOutput output)
{
if (member is IMethod method && method.IsConstructor)
output.WriteReference(member, method.DeclaringType?.Name + "." + method.Name);
else
output.WriteReference(member, member.Name);
}
public static void WriteTo(this Interval interval, ITextOutput output, ILAstWritingOptions options)
{
if (!options.ShowILRanges)
return;
if (interval.IsEmpty)
output.Write("[empty] ");
else
output.Write($"[{interval.Start:x4}..{interval.InclusiveEnd:x4}] ");
}
public static void WriteTo(this EntityHandle entity, MetadataFile module, ITextOutput output, Metadata.MetadataGenericContext genericContext, ILNameSyntax syntax = ILNameSyntax.Signature)
{
if (entity.IsNil)
{
output.Write("<nil>");
return;
}
if (module == null)
throw new ArgumentNullException(nameof(module));
var metadata = module.Metadata;
Action<ILNameSyntax> signature;
MethodSignature<Action<ILNameSyntax>> methodSignature;
string memberName;
switch (entity.Kind)
{
case HandleKind.TypeDefinition:
{
var td = metadata.GetTypeDefinition((TypeDefinitionHandle)entity);
output.WriteReference(module, entity, td.GetFullTypeName(metadata).ToILNameString());
break;
}
case HandleKind.TypeReference:
{
var tr = metadata.GetTypeReference((TypeReferenceHandle)entity);
EntityHandle resolutionScope;
try
{
resolutionScope = tr.ResolutionScope;
}
catch (BadImageFormatException)
{
resolutionScope = default;
}
if (!resolutionScope.IsNil)
{
output.Write("[");
var currentTypeRef = tr;
while (currentTypeRef.ResolutionScope.Kind == HandleKind.TypeReference)
{
currentTypeRef = metadata.GetTypeReference((TypeReferenceHandle)currentTypeRef.ResolutionScope);
}
switch (currentTypeRef.ResolutionScope.Kind)
{
case HandleKind.ModuleDefinition:
var modDef = metadata.GetModuleDefinition();
output.Write(DisassemblerHelpers.Escape(metadata.GetString(modDef.Name)));
break;
case HandleKind.ModuleReference:
break;
case HandleKind.AssemblyReference:
var asmRef = metadata.GetAssemblyReference((AssemblyReferenceHandle)currentTypeRef.ResolutionScope);
output.Write(DisassemblerHelpers.Escape(metadata.GetString(asmRef.Name)));
break;
}
output.Write("]");
}
output.WriteReference(module, entity, entity.GetFullTypeName(metadata).ToILNameString());
break;
}
case HandleKind.TypeSpecification:
{
var ts = metadata.GetTypeSpecification((TypeSpecificationHandle)entity);
signature = ts.DecodeSignature(new DisassemblerSignatureTypeProvider(module, output), genericContext);
signature(syntax);
break;
}
case HandleKind.FieldDefinition:
{
var fd = metadata.GetFieldDefinition((FieldDefinitionHandle)entity);
signature = fd.DecodeSignature(new DisassemblerSignatureTypeProvider(module, output), new Metadata.MetadataGenericContext(fd.GetDeclaringType(), metadata));
signature(ILNameSyntax.SignatureNoNamedTypeParameters);
output.Write(' ');
((EntityHandle)fd.GetDeclaringType()).WriteTo(module, output, default, ILNameSyntax.TypeName);
output.Write("::");
output.WriteReference(module, entity, DisassemblerHelpers.Escape(metadata.GetString(fd.Name)));
break;
}
case HandleKind.MethodDefinition:
{
var md = metadata.GetMethodDefinition((MethodDefinitionHandle)entity);
methodSignature = md.DecodeSignature(new DisassemblerSignatureTypeProvider(module, output), new Metadata.MetadataGenericContext((MethodDefinitionHandle)entity, metadata));
methodSignature.Header.WriteTo(output);
methodSignature.ReturnType(ILNameSyntax.SignatureNoNamedTypeParameters);
output.Write(' ');
var declaringType = md.GetDeclaringType();
if (!declaringType.IsNil)
{
((EntityHandle)declaringType).WriteTo(module, output, genericContext, ILNameSyntax.TypeName);
output.Write("::");
}
bool isCompilerControlled = (md.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.PrivateScope;
if (isCompilerControlled)
{
output.WriteReference(module, entity, DisassemblerHelpers.Escape(metadata.GetString(md.Name) + "$PST" + MetadataTokens.GetToken(entity).ToString("X8")));
}
else
{
output.WriteReference(module, entity, DisassemblerHelpers.Escape(metadata.GetString(md.Name)));
}
var genericParameters = md.GetGenericParameters();
if (genericParameters.Count > 0)
{
output.Write('<');
for (int i = 0; i < genericParameters.Count; i++)
{
if (i > 0)
output.Write(", ");
var gp = metadata.GetGenericParameter(genericParameters[i]);
if ((gp.Attributes & GenericParameterAttributes.ReferenceTypeConstraint) == GenericParameterAttributes.ReferenceTypeConstraint)
{
output.Write("class ");
}
else if ((gp.Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) == GenericParameterAttributes.NotNullableValueTypeConstraint)
{
output.Write("valuetype ");
}
if ((gp.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) == GenericParameterAttributes.DefaultConstructorConstraint)
{
output.Write(".ctor ");
}
var constraints = gp.GetConstraints();
if (constraints.Count > 0)
{
output.Write('(');
for (int j = 0; j < constraints.Count; j++)
{
if (j > 0)
output.Write(", ");
var constraint = metadata.GetGenericParameterConstraint(constraints[j]);
constraint.Type.WriteTo(module, output, new Metadata.MetadataGenericContext((MethodDefinitionHandle)entity, metadata), ILNameSyntax.TypeName);
}
output.Write(") ");
}
if ((gp.Attributes & GenericParameterAttributes.Contravariant) == GenericParameterAttributes.Contravariant)
{
output.Write('-');
}
else if ((gp.Attributes & GenericParameterAttributes.Covariant) == GenericParameterAttributes.Covariant)
{
output.Write('+');
}
output.Write(DisassemblerHelpers.Escape(metadata.GetString(gp.Name)));
}
output.Write('>');
}
WriteParameterList(output, methodSignature);
break;
}
case HandleKind.MemberReference:
var mr = metadata.GetMemberReference((MemberReferenceHandle)entity);
memberName = metadata.GetString(mr.Name);
switch (mr.GetKind())
{
case MemberReferenceKind.Method:
methodSignature = mr.DecodeMethodSignature(new DisassemblerSignatureTypeProvider(module, output), genericContext);
methodSignature.Header.WriteTo(output);
methodSignature.ReturnType(ILNameSyntax.SignatureNoNamedTypeParameters);
output.Write(' ');
WriteParent(output, module, mr.Parent, genericContext, syntax);
output.Write("::");
output.WriteReference(module, entity, DisassemblerHelpers.Escape(memberName));
WriteParameterList(output, methodSignature);
break;
case MemberReferenceKind.Field:
var fieldSignature = mr.DecodeFieldSignature(new DisassemblerSignatureTypeProvider(module, output), genericContext);
fieldSignature(ILNameSyntax.SignatureNoNamedTypeParameters);
output.Write(' ');
WriteParent(output, module, mr.Parent, genericContext, syntax);
output.Write("::");
output.WriteReference(module, entity, DisassemblerHelpers.Escape(memberName));
break;
}
break;
case HandleKind.MethodSpecification:
var ms = metadata.GetMethodSpecification((MethodSpecificationHandle)entity);
var substitution = ms.DecodeSignature(new DisassemblerSignatureTypeProvider(module, output), genericContext);
switch (ms.Method.Kind)
{
case HandleKind.MethodDefinition:
var methodDefinition = metadata.GetMethodDefinition((MethodDefinitionHandle)ms.Method);
var methodName = metadata.GetString(methodDefinition.Name);
methodSignature = methodDefinition.DecodeSignature(new DisassemblerSignatureTypeProvider(module, output), genericContext);
methodSignature.Header.WriteTo(output);
methodSignature.ReturnType(ILNameSyntax.SignatureNoNamedTypeParameters);
output.Write(' ');
var declaringType = methodDefinition.GetDeclaringType();
if (!declaringType.IsNil)
{
((EntityHandle)declaringType).WriteTo(module, output, genericContext, ILNameSyntax.TypeName);
output.Write("::");
}
bool isCompilerControlled = (methodDefinition.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.PrivateScope;
if (isCompilerControlled)
{
output.Write(DisassemblerHelpers.Escape(methodName + "$PST" + MetadataTokens.GetToken(ms.Method).ToString("X8")));
}
else
{
output.Write(DisassemblerHelpers.Escape(methodName));
}
WriteTypeParameterList(output, syntax, substitution);
WriteParameterList(output, methodSignature);
break;
case HandleKind.MemberReference:
var memberReference = metadata.GetMemberReference((MemberReferenceHandle)ms.Method);
memberName = metadata.GetString(memberReference.Name);
methodSignature = memberReference.DecodeMethodSignature(new DisassemblerSignatureTypeProvider(module, output), genericContext);
methodSignature.Header.WriteTo(output);
methodSignature.ReturnType(ILNameSyntax.SignatureNoNamedTypeParameters);
output.Write(' ');
WriteParent(output, module, memberReference.Parent, genericContext, syntax);
output.Write("::");
output.Write(DisassemblerHelpers.Escape(memberName));
WriteTypeParameterList(output, syntax, substitution);
WriteParameterList(output, methodSignature);
break;
}
break;
case HandleKind.StandaloneSignature:
var standaloneSig = metadata.GetStandaloneSignature((StandaloneSignatureHandle)entity);
var header = metadata.GetBlobReader(standaloneSig.Signature).ReadSignatureHeader();
switch (header.Kind)
{
case SignatureKind.Method:
methodSignature = standaloneSig.DecodeMethodSignature(new DisassemblerSignatureTypeProvider(module, output), genericContext);
methodSignature.Header.WriteTo(output);
methodSignature.ReturnType(ILNameSyntax.SignatureNoNamedTypeParameters);
WriteParameterList(output, methodSignature);
break;
default:
output.Write($"@{MetadataTokens.GetToken(entity):X8} /* signature {header.Kind} */");
break;
}
break;
default:
output.Write($"@{MetadataTokens.GetToken(entity):X8}");
break;
}
}
static void WriteTypeParameterList(ITextOutput output, ILNameSyntax syntax, System.Collections.Immutable.ImmutableArray<Action<ILNameSyntax>> substitution)
{
output.Write('<');
for (int i = 0; i < substitution.Length; i++)
{
if (i > 0)
output.Write(", ");
substitution[i](syntax);
}
output.Write('>');
}
internal static void WriteParameterList(ITextOutput output, MethodSignature<Action<ILNameSyntax>> methodSignature)
{
output.Write("(");
for (int i = 0; i < methodSignature.ParameterTypes.Length; ++i)
{
if (i > 0)
output.Write(", ");
if (i == methodSignature.RequiredParameterCount)
output.Write("..., ");
methodSignature.ParameterTypes[i](ILNameSyntax.SignatureNoNamedTypeParameters);
}
output.Write(")");
}
internal static void WriteTo(this in SignatureHeader header, ITextOutput output)
{
if (header.HasExplicitThis)
{
output.Write("instance explicit ");
}
else if (header.IsInstance)
{
output.Write("instance ");
}
if (header.CallingConvention != SignatureCallingConvention.Default)
{
output.Write(header.CallingConvention.ToILSyntax());
output.Write(' ');
}
}
static void WriteParent(ITextOutput output, MetadataFile metadataFile, EntityHandle parentHandle, Metadata.MetadataGenericContext genericContext, ILNameSyntax syntax)
{
switch (parentHandle.Kind)
{
case HandleKind.MethodDefinition:
var methodDef = metadataFile.Metadata.GetMethodDefinition((MethodDefinitionHandle)parentHandle);
((EntityHandle)methodDef.GetDeclaringType()).WriteTo(metadataFile, output, genericContext, syntax);
break;
case HandleKind.ModuleReference:
output.Write('[');
var moduleRef = metadataFile.Metadata.GetModuleReference((ModuleReferenceHandle)parentHandle);
output.Write(metadataFile.Metadata.GetString(moduleRef.Name));
output.Write(']');
break;
case HandleKind.TypeDefinition:
case HandleKind.TypeReference:
case HandleKind.TypeSpecification:
parentHandle.WriteTo(metadataFile, output, genericContext, syntax);
break;
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/InstructionOutputExtensions.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/InstructionOutputExtensions.cs",
"repo_id": "ILSpy",
"token_count": 5601
} | 236 |
#nullable enable
// Copyright (c) 2018 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using ICSharpCode.Decompiler.IL.Patterns;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL
{
[Flags]
public enum CSharpArgumentInfoFlags
{
None = 0,
UseCompileTimeType = 1,
Constant = 2,
NamedArgument = 4,
IsRef = 8,
IsOut = 0x10,
IsStaticType = 0x20
}
[Flags]
public enum CSharpBinderFlags
{
None = 0,
CheckedContext = 1,
InvokeSimpleName = 2,
InvokeSpecialName = 4,
BinaryOperationLogical = 8,
ConvertExplicit = 0x10,
ConvertArrayIndex = 0x20,
ResultIndexed = 0x40,
ValueFromCompoundAssignment = 0x80,
ResultDiscarded = 0x100
}
public struct CSharpArgumentInfo
{
public string? Name { get; set; }
public CSharpArgumentInfoFlags Flags { get; set; }
public IType CompileTimeType { get; set; }
public bool HasFlag(CSharpArgumentInfoFlags flag) => (Flags & flag) != 0;
}
partial class DynamicInstruction
{
public CSharpBinderFlags BinderFlags { get; }
public IType? CallingContext { get; }
protected DynamicInstruction(OpCode opCode, CSharpBinderFlags binderFlags, IType? context)
: base(opCode)
{
BinderFlags = binderFlags;
CallingContext = context;
}
protected void WriteBinderFlags(ITextOutput output, ILAstWritingOptions options)
{
WriteBinderFlags(BinderFlags, output, options);
}
internal static void WriteBinderFlags(CSharpBinderFlags flags, ITextOutput output, ILAstWritingOptions options)
{
if ((flags & CSharpBinderFlags.BinaryOperationLogical) != 0)
output.Write(".logic");
if ((flags & CSharpBinderFlags.CheckedContext) != 0)
output.Write(".checked");
if ((flags & CSharpBinderFlags.ConvertArrayIndex) != 0)
output.Write(".arrayindex");
if ((flags & CSharpBinderFlags.ConvertExplicit) != 0)
output.Write(".explicit");
if ((flags & CSharpBinderFlags.InvokeSimpleName) != 0)
output.Write(".invokesimple");
if ((flags & CSharpBinderFlags.InvokeSpecialName) != 0)
output.Write(".invokespecial");
if ((flags & CSharpBinderFlags.ResultDiscarded) != 0)
output.Write(".discard");
if ((flags & CSharpBinderFlags.ResultIndexed) != 0)
output.Write(".resultindexed");
if ((flags & CSharpBinderFlags.ValueFromCompoundAssignment) != 0)
output.Write(".compound");
}
public abstract CSharpArgumentInfo GetArgumentInfoOfChild(int index);
internal static void WriteArgumentList(ITextOutput output, ILAstWritingOptions options, params (ILInstruction, CSharpArgumentInfo)[] arguments)
{
WriteArgumentList(output, options, (IEnumerable<(ILInstruction, CSharpArgumentInfo)>)arguments);
}
internal static void WriteArgumentList(ITextOutput output, ILAstWritingOptions options, IEnumerable<(ILInstruction, CSharpArgumentInfo)> arguments)
{
output.Write('(');
int j = 0;
foreach (var (arg, info) in arguments)
{
if (j > 0)
output.Write(", ");
output.Write("[flags: ");
output.Write(info.Flags.ToString());
output.Write(", name: " + info.Name + "] ");
arg.WriteTo(output, options);
j++;
}
output.Write(')');
}
}
partial class DynamicConvertInstruction
{
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
type.WriteTo(output);
output.Write('(');
argument.WriteTo(output, options);
output.Write(')');
}
public DynamicConvertInstruction(CSharpBinderFlags binderFlags, IType type, IType? context, ILInstruction argument)
: base(OpCode.DynamicConvertInstruction, binderFlags, context)
{
this.type = type;
Argument = argument;
}
protected internal override bool PerformMatch(ref ListMatch listMatch, ref Match match)
{
return base.PerformMatch(ref listMatch, ref match);
}
public override StackType ResultType => type.GetStackType();
public bool IsChecked => (BinderFlags & CSharpBinderFlags.CheckedContext) != 0;
public bool IsExplicit => (BinderFlags & CSharpBinderFlags.ConvertExplicit) != 0;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
return default(CSharpArgumentInfo);
}
}
partial class DynamicInvokeMemberInstruction
{
public string Name { get; }
public IReadOnlyList<IType> TypeArguments { get; }
public IReadOnlyList<CSharpArgumentInfo> ArgumentInfo { get; }
public DynamicInvokeMemberInstruction(CSharpBinderFlags binderFlags, string name, IType[]? typeArguments, IType? context, CSharpArgumentInfo[] argumentInfo, ILInstruction[] arguments)
: base(OpCode.DynamicInvokeMemberInstruction, binderFlags, context)
{
Name = name;
TypeArguments = typeArguments ?? Empty<IType>.Array;
ArgumentInfo = argumentInfo;
Arguments = new InstructionCollection<ILInstruction>(this, 0);
Arguments.AddRange(arguments);
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write(Name);
if (TypeArguments.Count > 0)
{
output.Write('<');
int i = 0;
foreach (var typeArg in TypeArguments)
{
if (i > 0)
output.Write(", ");
typeArg.WriteTo(output);
i++;
}
output.Write('>');
}
WriteArgumentList(output, options, Arguments.Zip(ArgumentInfo));
}
public override StackType ResultType => StackType.O;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
if (index < 0 || index >= ArgumentInfo.Count)
throw new ArgumentOutOfRangeException(nameof(index));
return ArgumentInfo[index];
}
}
partial class DynamicGetMemberInstruction
{
public string? Name { get; }
public CSharpArgumentInfo TargetArgumentInfo { get; }
public DynamicGetMemberInstruction(CSharpBinderFlags binderFlags, string? name, IType? context, CSharpArgumentInfo targetArgumentInfo, ILInstruction target)
: base(OpCode.DynamicGetMemberInstruction, binderFlags, context)
{
Name = name;
TargetArgumentInfo = targetArgumentInfo;
Target = target;
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write(Name);
WriteArgumentList(output, options, (Target, TargetArgumentInfo));
}
public override StackType ResultType => StackType.O;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
if (index != 0)
throw new ArgumentOutOfRangeException(nameof(index));
return TargetArgumentInfo;
}
}
partial class DynamicSetMemberInstruction
{
public string? Name { get; }
public CSharpArgumentInfo TargetArgumentInfo { get; }
public CSharpArgumentInfo ValueArgumentInfo { get; }
public DynamicSetMemberInstruction(CSharpBinderFlags binderFlags, string? name, IType? context, CSharpArgumentInfo targetArgumentInfo, ILInstruction target, CSharpArgumentInfo valueArgumentInfo, ILInstruction value)
: base(OpCode.DynamicSetMemberInstruction, binderFlags, context)
{
Name = name;
TargetArgumentInfo = targetArgumentInfo;
Target = target;
ValueArgumentInfo = valueArgumentInfo;
Value = value;
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write(Name);
WriteArgumentList(output, options, (Target, TargetArgumentInfo), (Value, ValueArgumentInfo));
}
public override StackType ResultType => StackType.O;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
switch (index)
{
case 0:
return TargetArgumentInfo;
case 1:
return ValueArgumentInfo;
default:
throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
partial class DynamicGetIndexInstruction
{
public IReadOnlyList<CSharpArgumentInfo> ArgumentInfo { get; }
public DynamicGetIndexInstruction(CSharpBinderFlags binderFlags, IType? context, CSharpArgumentInfo[] argumentInfo, ILInstruction[] arguments)
: base(OpCode.DynamicGetIndexInstruction, binderFlags, context)
{
ArgumentInfo = argumentInfo;
Arguments = new InstructionCollection<ILInstruction>(this, 0);
Arguments.AddRange(arguments);
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write("get_Item");
WriteArgumentList(output, options, Arguments.Zip(ArgumentInfo));
}
public override StackType ResultType => StackType.O;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
if (index < 0 || index >= ArgumentInfo.Count)
throw new ArgumentOutOfRangeException(nameof(index));
return ArgumentInfo[index];
}
}
partial class DynamicSetIndexInstruction
{
public IReadOnlyList<CSharpArgumentInfo> ArgumentInfo { get; }
public DynamicSetIndexInstruction(CSharpBinderFlags binderFlags, IType? context, CSharpArgumentInfo[] argumentInfo, ILInstruction[] arguments)
: base(OpCode.DynamicSetIndexInstruction, binderFlags, context)
{
ArgumentInfo = argumentInfo;
Arguments = new InstructionCollection<ILInstruction>(this, 0);
Arguments.AddRange(arguments);
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write("set_Item");
WriteArgumentList(output, options, Arguments.Zip(ArgumentInfo));
}
public override StackType ResultType => StackType.O;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
if (index < 0 || index >= ArgumentInfo.Count)
throw new ArgumentOutOfRangeException(nameof(index));
return ArgumentInfo[index];
}
}
partial class DynamicInvokeConstructorInstruction
{
readonly IType? resultType;
public IReadOnlyList<CSharpArgumentInfo> ArgumentInfo { get; }
public DynamicInvokeConstructorInstruction(CSharpBinderFlags binderFlags, IType? type, IType? context, CSharpArgumentInfo[] argumentInfo, ILInstruction[] arguments)
: base(OpCode.DynamicInvokeConstructorInstruction, binderFlags, context)
{
ArgumentInfo = argumentInfo;
Arguments = new InstructionCollection<ILInstruction>(this, 0);
Arguments.AddRange(arguments);
this.resultType = type;
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
resultType?.WriteTo(output);
output.Write(".ctor");
WriteArgumentList(output, options, Arguments.Zip(ArgumentInfo));
}
public override StackType ResultType => resultType?.GetStackType() ?? StackType.Unknown;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
if (index < 0 || index >= ArgumentInfo.Count)
throw new ArgumentOutOfRangeException(nameof(index));
return ArgumentInfo[index];
}
}
partial class DynamicBinaryOperatorInstruction
{
public CSharpArgumentInfo LeftArgumentInfo { get; }
public CSharpArgumentInfo RightArgumentInfo { get; }
public ExpressionType Operation { get; }
public DynamicBinaryOperatorInstruction(CSharpBinderFlags binderFlags, ExpressionType operation, IType? context, CSharpArgumentInfo leftArgumentInfo, ILInstruction left, CSharpArgumentInfo rightArgumentInfo, ILInstruction right)
: base(OpCode.DynamicBinaryOperatorInstruction, binderFlags, context)
{
Operation = operation;
LeftArgumentInfo = leftArgumentInfo;
Left = left;
RightArgumentInfo = rightArgumentInfo;
Right = right;
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write(Operation.ToString());
WriteArgumentList(output, options, (Left, LeftArgumentInfo), (Right, RightArgumentInfo));
}
public override StackType ResultType => StackType.O;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
switch (index)
{
case 0:
return LeftArgumentInfo;
case 1:
return RightArgumentInfo;
default:
throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
partial class DynamicLogicOperatorInstruction
{
public CSharpArgumentInfo LeftArgumentInfo { get; }
public CSharpArgumentInfo RightArgumentInfo { get; }
public ExpressionType Operation { get; }
public DynamicLogicOperatorInstruction(CSharpBinderFlags binderFlags, ExpressionType operation, IType? context, CSharpArgumentInfo leftArgumentInfo, ILInstruction left, CSharpArgumentInfo rightArgumentInfo, ILInstruction right)
: base(OpCode.DynamicLogicOperatorInstruction, binderFlags, context)
{
Operation = operation;
LeftArgumentInfo = leftArgumentInfo;
Left = left;
RightArgumentInfo = rightArgumentInfo;
Right = right;
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write(Operation.ToString());
WriteArgumentList(output, options, (Left, LeftArgumentInfo), (Right, RightArgumentInfo));
}
public override StackType ResultType => StackType.O;
protected override InstructionFlags ComputeFlags()
{
return DirectFlags | Left.Flags
| SemanticHelper.CombineBranches(Right.Flags, InstructionFlags.None);
}
public override InstructionFlags DirectFlags => InstructionFlags.MayThrow | InstructionFlags.SideEffect | InstructionFlags.ControlFlow;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
switch (index)
{
case 0:
return LeftArgumentInfo;
case 1:
return RightArgumentInfo;
default:
throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
partial class DynamicUnaryOperatorInstruction
{
public CSharpArgumentInfo OperandArgumentInfo { get; }
public ExpressionType Operation { get; }
public DynamicUnaryOperatorInstruction(CSharpBinderFlags binderFlags, ExpressionType operation, IType? context, CSharpArgumentInfo operandArgumentInfo, ILInstruction operand)
: base(OpCode.DynamicUnaryOperatorInstruction, binderFlags, context)
{
Operation = operation;
OperandArgumentInfo = operandArgumentInfo;
Operand = operand;
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write(Operation.ToString());
WriteArgumentList(output, options, (Operand, OperandArgumentInfo));
}
public override StackType ResultType {
get {
switch (Operation)
{
case ExpressionType.IsFalse:
case ExpressionType.IsTrue:
return StackType.I4; // bool
default:
return StackType.O;
}
}
}
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
switch (index)
{
case 0:
return OperandArgumentInfo;
default:
throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
partial class DynamicInvokeInstruction
{
public IReadOnlyList<CSharpArgumentInfo> ArgumentInfo { get; }
public DynamicInvokeInstruction(CSharpBinderFlags binderFlags, IType? context, CSharpArgumentInfo[] argumentInfo, ILInstruction[] arguments)
: base(OpCode.DynamicInvokeInstruction, binderFlags, context)
{
ArgumentInfo = argumentInfo;
Arguments = new InstructionCollection<ILInstruction>(this, 0);
Arguments.AddRange(arguments);
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
WriteArgumentList(output, options, Arguments.Zip(ArgumentInfo));
}
public override StackType ResultType => StackType.O;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
if (index < 0 || index >= ArgumentInfo.Count)
throw new ArgumentOutOfRangeException(nameof(index));
return ArgumentInfo[index];
}
}
partial class DynamicIsEventInstruction
{
public string? Name { get; }
public DynamicIsEventInstruction(CSharpBinderFlags binderFlags, string? name, IType? context, ILInstruction argument)
: base(OpCode.DynamicIsEventInstruction, binderFlags, context)
{
Name = name;
Argument = argument;
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
WriteBinderFlags(output, options);
output.Write(' ');
output.Write('(');
Argument.WriteTo(output, options);
output.Write(')');
}
public override StackType ResultType => StackType.I4;
public override CSharpArgumentInfo GetArgumentInfoOfChild(int index)
{
return default(CSharpArgumentInfo);
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Instructions/DynamicInstructions.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/DynamicInstructions.cs",
"repo_id": "ILSpy",
"token_count": 6330
} | 237 |
#nullable enable
// Copyright (c) 2014 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Diagnostics.CodeAnalysis;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.IL
{
partial class ILInstruction
{
public bool MatchLdcI4(int val)
{
return OpCode == OpCode.LdcI4 && ((LdcI4)this).Value == val;
}
public bool MatchLdcF4(float value)
{
return MatchLdcF4(out var v) && v == value;
}
public bool MatchLdcF8(double value)
{
return MatchLdcF8(out var v) && v == value;
}
/// <summary>
/// Matches ldc.i4, ldc.i8, and extending conversions.
/// </summary>
public bool MatchLdcI(out long val)
{
if (MatchLdcI8(out val))
return true;
if (MatchLdcI4(out int intVal))
{
val = intVal;
return true;
}
if (this is Conv conv)
{
if (conv.Kind == ConversionKind.SignExtend)
{
return conv.Argument.MatchLdcI(out val);
}
else if (conv.Kind == ConversionKind.ZeroExtend && conv.InputType == StackType.I4)
{
if (conv.Argument.MatchLdcI(out val))
{
// clear top 32 bits
val &= uint.MaxValue;
return true;
}
}
}
return false;
}
public bool MatchLdcI(long val)
{
return MatchLdcI(out long v) && v == val;
}
public bool MatchLdLoc(ILVariable? variable)
{
var inst = this as LdLoc;
return inst != null && inst.Variable == variable;
}
public bool MatchLdLoca(ILVariable? variable)
{
var inst = this as LdLoca;
return inst != null && inst.Variable == variable;
}
/// <summary>
/// Matches either ldloc (if the variable is a reference type), or ldloca (otherwise).
/// </summary>
public bool MatchLdLocRef(ILVariable? variable)
{
return MatchLdLocRef(out var v) && v == variable;
}
/// <summary>
/// Matches either ldloc (if the variable is a reference type), or ldloca (otherwise).
/// </summary>
public bool MatchLdLocRef([NotNullWhen(true)] out ILVariable? variable)
{
switch (this)
{
case LdLoc ldloc:
variable = ldloc.Variable;
return variable.Type.IsReferenceType == true;
case LdLoca ldloca:
variable = ldloca.Variable;
return variable.Type.IsReferenceType != true || variable.Type.Kind == TypeKind.TypeParameter;
default:
variable = null;
return false;
}
}
public bool MatchLdThis()
{
var inst = this as LdLoc;
return inst != null && inst.Variable.Kind == VariableKind.Parameter && inst.Variable.Index < 0;
}
public bool MatchStLoc([NotNullWhen(true)] out ILVariable? variable)
{
var inst = this as StLoc;
if (inst != null)
{
variable = inst.Variable;
return true;
}
variable = null;
return false;
}
public bool MatchStLoc(ILVariable? variable, [NotNullWhen(true)] out ILInstruction? value)
{
var inst = this as StLoc;
if (inst != null && inst.Variable == variable)
{
value = inst.Value;
return true;
}
value = null;
return false;
}
public bool MatchLdLen(StackType type, [NotNullWhen(true)] out ILInstruction? array)
{
var inst = this as LdLen;
if (inst != null && inst.ResultType == type)
{
array = inst.Array;
return true;
}
array = null;
return false;
}
public bool MatchReturn([NotNullWhen(true)] out ILInstruction? value)
{
var inst = this as Leave;
if (inst != null && inst.IsLeavingFunction)
{
value = inst.Value;
return true;
}
value = default(ILInstruction);
return false;
}
public bool MatchBranch([NotNullWhen(true)] out Block? targetBlock)
{
var inst = this as Branch;
if (inst != null)
{
targetBlock = inst.TargetBlock;
return true;
}
targetBlock = null;
return false;
}
public bool MatchBranch(Block? targetBlock)
{
var inst = this as Branch;
return inst != null && inst.TargetBlock == targetBlock;
}
public bool MatchLeave([NotNullWhen(true)] out BlockContainer? targetContainer, [NotNullWhen(true)] out ILInstruction? value)
{
var inst = this as Leave;
if (inst != null)
{
targetContainer = inst.TargetContainer;
value = inst.Value;
return true;
}
targetContainer = null;
value = null;
return false;
}
public bool MatchLeave(BlockContainer? targetContainer, [NotNullWhen(true)] out ILInstruction? value)
{
var inst = this as Leave;
if (inst != null && targetContainer == inst.TargetContainer)
{
value = inst.Value;
return true;
}
value = null;
return false;
}
public bool MatchLeave([NotNullWhen(true)] out BlockContainer? targetContainer)
{
var inst = this as Leave;
if (inst != null && inst.Value.MatchNop())
{
targetContainer = inst.TargetContainer;
return true;
}
targetContainer = null;
return false;
}
public bool MatchLeave(BlockContainer? targetContainer)
{
var inst = this as Leave;
return inst != null && inst.TargetContainer == targetContainer && inst.Value.MatchNop();
}
public bool MatchIfInstruction([NotNullWhen(true)] out ILInstruction? condition, [NotNullWhen(true)] out ILInstruction? trueInst, [NotNullWhen(true)] out ILInstruction? falseInst)
{
if (this is IfInstruction inst)
{
condition = inst.Condition;
trueInst = inst.TrueInst;
falseInst = inst.FalseInst;
return true;
}
condition = null;
trueInst = null;
falseInst = null;
return false;
}
public bool MatchIfInstructionPositiveCondition([NotNullWhen(true)] out ILInstruction? condition, [NotNullWhen(true)] out ILInstruction? trueInst, [NotNullWhen(true)] out ILInstruction? falseInst)
{
if (MatchIfInstruction(out condition, out trueInst, out falseInst))
{
// Swap trueInst<>falseInst for every logic.not in the condition.
while (condition.MatchLogicNot(out var arg))
{
condition = arg;
ILInstruction? tmp = trueInst;
trueInst = falseInst;
falseInst = tmp;
}
return true;
}
return false;
}
/// <summary>
/// Matches an if instruction where the false instruction is a nop.
/// </summary>
public bool MatchIfInstruction([NotNullWhen(true)] out ILInstruction? condition, [NotNullWhen(true)] out ILInstruction? trueInst)
{
var inst = this as IfInstruction;
if (inst != null && inst.FalseInst.MatchNop())
{
condition = inst.Condition;
trueInst = inst.TrueInst;
return true;
}
condition = null;
trueInst = null;
return false;
}
/// <summary>
/// Matches a 'logic and' instruction ("if (a) b else ldc.i4 0").
/// Note: unlike C# '&&', this instruction is not limited to booleans,
/// but allows passing through arbitrary I4 values on the rhs (but not on the lhs).
/// </summary>
public bool MatchLogicAnd([NotNullWhen(true)] out ILInstruction? lhs, [NotNullWhen(true)] out ILInstruction? rhs)
{
var inst = this as IfInstruction;
if (inst != null && inst.FalseInst.MatchLdcI4(0))
{
lhs = inst.Condition;
rhs = inst.TrueInst;
return true;
}
lhs = null;
rhs = null;
return false;
}
/// <summary>
/// Matches a 'logic or' instruction ("if (a) ldc.i4 1 else b").
/// Note: unlike C# '||', this instruction is not limited to booleans,
/// but allows passing through arbitrary I4 values on the rhs (but not on the lhs).
/// </summary>
public bool MatchLogicOr([NotNullWhen(true)] out ILInstruction? lhs, [NotNullWhen(true)] out ILInstruction? rhs)
{
var inst = this as IfInstruction;
if (inst != null && inst.TrueInst.MatchLdcI4(1))
{
lhs = inst.Condition;
rhs = inst.FalseInst;
return true;
}
lhs = null;
rhs = null;
return false;
}
/// <summary>
/// Matches an logical negation.
/// </summary>
public bool MatchLogicNot([NotNullWhen(true)] out ILInstruction? arg)
{
if (this is Comp comp && comp.Kind == ComparisonKind.Equality
&& comp.LiftingKind == ComparisonLiftingKind.None
&& comp.Right.MatchLdcI4(0))
{
arg = comp.Left;
return true;
}
arg = null;
return false;
}
public bool MatchTryCatchHandler([NotNullWhen(true)] out ILVariable? variable)
{
var inst = this as TryCatchHandler;
if (inst != null)
{
variable = inst.Variable;
return true;
}
variable = null;
return false;
}
/// <summary>
/// Matches comp(left == right) or logic.not(comp(left != right)).
/// </summary>
public bool MatchCompEquals([NotNullWhen(true)] out ILInstruction? left, [NotNullWhen(true)] out ILInstruction? right)
{
ILInstruction thisInst = this;
var compKind = ComparisonKind.Equality;
while (thisInst.MatchLogicNot(out var arg) && arg is Comp)
{
thisInst = arg;
if (compKind == ComparisonKind.Equality)
compKind = ComparisonKind.Inequality;
else
compKind = ComparisonKind.Equality;
}
if (thisInst is Comp comp && comp.Kind == compKind && !comp.IsLifted)
{
left = comp.Left;
right = comp.Right;
return true;
}
else
{
left = null;
right = null;
return false;
}
}
/// <summary>
/// Matches 'comp(arg == ldnull)'
/// </summary>
public bool MatchCompEqualsNull([NotNullWhen(true)] out ILInstruction? arg)
{
if (!MatchCompEquals(out var left, out var right))
{
arg = null;
return false;
}
if (right.MatchLdNull())
{
arg = left;
return true;
}
else if (left.MatchLdNull())
{
arg = right;
return true;
}
else
{
arg = null;
return false;
}
}
/// <summary>
/// Matches 'comp(arg != ldnull)'
/// </summary>
public bool MatchCompNotEqualsNull([NotNullWhen(true)] out ILInstruction? arg)
{
if (!MatchCompNotEquals(out var left, out var right))
{
arg = null;
return false;
}
if (right.MatchLdNull())
{
arg = left;
return true;
}
else if (left.MatchLdNull())
{
arg = right;
return true;
}
else
{
arg = null;
return false;
}
}
/// <summary>
/// Matches comp(left != right) or logic.not(comp(left == right)).
/// </summary>
public bool MatchCompNotEquals([NotNullWhen(true)] out ILInstruction? left, [NotNullWhen(true)] out ILInstruction? right)
{
ILInstruction thisInst = this;
var compKind = ComparisonKind.Inequality;
while (thisInst.MatchLogicNot(out var arg) && arg is Comp)
{
thisInst = arg;
if (compKind == ComparisonKind.Equality)
compKind = ComparisonKind.Inequality;
else
compKind = ComparisonKind.Equality;
}
if (thisInst is Comp comp && comp.Kind == compKind && !comp.IsLifted)
{
left = comp.Left;
right = comp.Right;
return true;
}
else
{
left = null;
right = null;
return false;
}
}
public bool MatchLdFld([NotNullWhen(true)] out ILInstruction? target, [NotNullWhen(true)] out IField? field)
{
if (this is LdObj ldobj && ldobj.Target is LdFlda ldflda && ldobj.UnalignedPrefix == 0 && !ldobj.IsVolatile)
{
field = ldflda.Field;
if (field.DeclaringType.IsReferenceType == true || !ldflda.Target.MatchAddressOf(out target, out _))
{
target = ldflda.Target;
}
return true;
}
target = null;
field = null;
return false;
}
public bool MatchLdsFld([NotNullWhen(true)] out IField? field)
{
if (this is LdObj ldobj && ldobj.Target is LdsFlda ldsflda && ldobj.UnalignedPrefix == 0 && !ldobj.IsVolatile)
{
field = ldsflda.Field;
return true;
}
field = null;
return false;
}
public bool MatchLdsFld(IField? field)
{
return MatchLdsFld(out var f) && f.Equals(field);
}
public bool MatchStsFld([NotNullWhen(true)] out IField? field, [NotNullWhen(true)] out ILInstruction? value)
{
if (this is StObj stobj && stobj.Target is LdsFlda ldsflda && stobj.UnalignedPrefix == 0 && !stobj.IsVolatile)
{
field = ldsflda.Field;
value = stobj.Value;
return true;
}
field = null;
value = null;
return false;
}
public bool MatchStFld([NotNullWhen(true)] out ILInstruction? target, [NotNullWhen(true)] out IField? field, [NotNullWhen(true)] out ILInstruction? value)
{
if (this is StObj stobj && stobj.Target is LdFlda ldflda && stobj.UnalignedPrefix == 0 && !stobj.IsVolatile)
{
target = ldflda.Target;
field = ldflda.Field;
value = stobj.Value;
return true;
}
target = null;
field = null;
value = null;
return false;
}
public bool MatchBinaryNumericInstruction(BinaryNumericOperator @operator)
{
var op = this as BinaryNumericInstruction;
return op != null && op.Operator == @operator;
}
public bool MatchBinaryNumericInstruction(BinaryNumericOperator @operator, [NotNullWhen(true)] out ILInstruction? left, [NotNullWhen(true)] out ILInstruction? right)
{
var op = this as BinaryNumericInstruction;
if (op != null && op.Operator == @operator)
{
left = op.Left;
right = op.Right;
return true;
}
left = null;
right = null;
return false;
}
public bool MatchBinaryNumericInstruction(out BinaryNumericOperator @operator, [NotNullWhen(true)] out ILInstruction? left, [NotNullWhen(true)] out ILInstruction? right)
{
var op = this as BinaryNumericInstruction;
if (op != null)
{
@operator = op.Operator;
left = op.Left;
right = op.Right;
return true;
}
@operator = BinaryNumericOperator.None;
left = null;
right = null;
return false;
}
public bool MatchDefaultOrNullOrZero()
{
switch (this)
{
case LdNull _:
case LdcF4 { Value: 0 }:
case LdcF8 { Value: 0 }:
case LdcI4 { Value: 0 }:
case LdcI8 { Value: 0 }:
case DefaultValue _:
return true;
default:
return false;
}
}
/// <summary>
/// If this instruction is a conversion of the specified kind, return its argument.
/// Otherwise, return the instruction itself.
/// </summary>
/// <remarks>
/// Does not unwrap lifted conversions.
/// </remarks>
public virtual ILInstruction UnwrapConv(ConversionKind kind)
{
return this;
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Instructions/PatternMatching.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/PatternMatching.cs",
"repo_id": "ILSpy",
"token_count": 5989
} | 238 |
// 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.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using Humanizer.Inflections;
using ICSharpCode.Decompiler.CSharp.OutputVisitor;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL.Transforms
{
public class AssignVariableNames : IILTransform
{
static readonly Dictionary<string, string> typeNameToVariableNameDict = new Dictionary<string, string> {
{ "System.Boolean", "flag" },
{ "System.Byte", "b" },
{ "System.SByte", "b" },
{ "System.Int16", "num" },
{ "System.Int32", "num" },
{ "System.Int64", "num" },
{ "System.UInt16", "num" },
{ "System.UInt32", "num" },
{ "System.UInt64", "num" },
{ "System.Single", "num" },
{ "System.Double", "num" },
{ "System.Decimal", "num" },
{ "System.String", "text" },
{ "System.Object", "obj" },
{ "System.Char", "c" }
};
ILTransformContext context;
List<string> currentLowerCaseTypeOrMemberNames;
Dictionary<string, int> reservedVariableNames;
Dictionary<MethodDefinitionHandle, string> localFunctionMapping;
HashSet<ILVariable> loopCounters;
const char maxLoopVariableName = 'n';
int numDisplayClassLocals;
public void Run(ILFunction function, ILTransformContext context)
{
this.context = context;
reservedVariableNames = new Dictionary<string, int>();
currentLowerCaseTypeOrMemberNames = new List<string>();
var currentLowerCaseMemberNames = CollectAllLowerCaseMemberNames(function.Method.DeclaringTypeDefinition);
foreach (var name in currentLowerCaseMemberNames)
currentLowerCaseTypeOrMemberNames.Add(name);
var currentLowerCaseTypeNames = CollectAllLowerCaseTypeNames(function.Method.DeclaringTypeDefinition);
foreach (var name in currentLowerCaseTypeNames)
{
currentLowerCaseTypeOrMemberNames.Add(name);
AddExistingName(reservedVariableNames, name);
}
localFunctionMapping = new Dictionary<MethodDefinitionHandle, string>();
loopCounters = CollectLoopCounters(function);
foreach (var f in function.Descendants.OfType<ILFunction>())
{
if (f.Method != null)
{
if (IsSetOrEventAccessor(f.Method) && f.Method.Parameters.Count > 0)
{
for (int i = 0; i < f.Method.Parameters.Count - 1; i++)
{
AddExistingName(reservedVariableNames, f.Method.Parameters[i].Name);
}
var lastParameter = f.Method.Parameters.Last();
switch (f.Method.AccessorOwner)
{
case IProperty prop:
if (f.Method.AccessorKind == MethodSemanticsAttributes.Setter)
{
if (prop.Parameters.Any(p => p.Name == "value"))
{
f.Warnings.Add("Parameter named \"value\" already present in property signature!");
break;
}
var variableForLastParameter = f.Variables.FirstOrDefault(v => v.Function == f
&& v.Kind == VariableKind.Parameter
&& v.Index == f.Method.Parameters.Count - 1);
if (variableForLastParameter == null)
{
AddExistingName(reservedVariableNames, lastParameter.Name);
}
else
{
if (variableForLastParameter.Name != "value")
{
variableForLastParameter.Name = "value";
}
AddExistingName(reservedVariableNames, variableForLastParameter.Name);
}
}
break;
case IEvent ev:
if (f.Method.AccessorKind != MethodSemanticsAttributes.Raiser)
{
var variableForLastParameter = f.Variables.FirstOrDefault(v => v.Function == f
&& v.Kind == VariableKind.Parameter
&& v.Index == f.Method.Parameters.Count - 1);
if (variableForLastParameter == null)
{
AddExistingName(reservedVariableNames, lastParameter.Name);
}
else
{
if (variableForLastParameter.Name != "value")
{
variableForLastParameter.Name = "value";
}
AddExistingName(reservedVariableNames, variableForLastParameter.Name);
}
}
break;
default:
AddExistingName(reservedVariableNames, lastParameter.Name);
break;
}
}
else
{
foreach (var p in f.Method.Parameters)
AddExistingName(reservedVariableNames, p.Name);
}
}
else
{
foreach (var p in f.Variables.Where(v => v.Kind == VariableKind.Parameter))
AddExistingName(reservedVariableNames, p.Name);
}
}
numDisplayClassLocals = 0;
foreach (ILFunction f in function.Descendants.OfType<ILFunction>().Reverse())
{
PerformAssignment(f);
}
}
static IEnumerable<string> CollectAllLowerCaseMemberNames(ITypeDefinition type)
{
foreach (var item in type.GetMembers(m => IsLowerCase(m.Name)))
yield return item.Name;
}
static IEnumerable<string> CollectAllLowerCaseTypeNames(ITypeDefinition type)
{
var ns = type.ParentModule.Compilation.GetNamespaceByFullName(type.Namespace);
foreach (var item in ns.Types)
{
if (IsLowerCase(item.Name))
yield return item.Name;
}
}
static bool IsLowerCase(string name)
{
return name.Length > 0 && char.ToLower(name[0]) == name[0];
}
bool IsSetOrEventAccessor(IMethod method)
{
switch (method.AccessorKind)
{
case MethodSemanticsAttributes.Setter:
case MethodSemanticsAttributes.Adder:
case MethodSemanticsAttributes.Remover:
return true;
default:
return false;
}
}
void PerformAssignment(ILFunction function)
{
// remove unused variables before assigning names
function.Variables.RemoveDead();
Dictionary<int, string> assignedLocalSignatureIndices = new Dictionary<int, string>();
foreach (var v in function.Variables.OrderBy(v => v.Name))
{
switch (v.Kind)
{
case VariableKind.Parameter:
// Parameter names are handled in ILReader.CreateILVariable
// and CSharpDecompiler.FixParameterNames
break;
case VariableKind.InitializerTarget: // keep generated names
AddExistingName(reservedVariableNames, v.Name);
break;
case VariableKind.DisplayClassLocal:
v.Name = "CS$<>8__locals" + (numDisplayClassLocals++);
break;
case VariableKind.Local when v.Index != null:
if (assignedLocalSignatureIndices.TryGetValue(v.Index.Value, out string name))
{
// make sure all local ILVariables that refer to the same slot in the locals signature
// are assigned the same name.
v.Name = name;
}
else
{
AssignName();
// Remember the newly assigned name:
assignedLocalSignatureIndices.Add(v.Index.Value, v.Name);
}
break;
default:
AssignName();
break;
}
void AssignName()
{
if (v.HasGeneratedName || !IsValidName(v.Name) || ConflictWithLocal(v))
{
// don't use the name from the debug symbols if it looks like a generated name
v.Name = null;
}
else
{
// use the name from the debug symbols and update index appended to duplicates
string nameWithoutNumber = SplitName(v.Name, out int newIndex);
if (!reservedVariableNames.TryGetValue(nameWithoutNumber, out int currentIndex))
{
currentIndex = 1;
}
reservedVariableNames[nameWithoutNumber] = Math.Max(newIndex, currentIndex);
}
}
}
foreach (var localFunction in function.LocalFunctions)
{
if (!LocalFunctionDecompiler.ParseLocalFunctionName(localFunction.Name, out _, out var newName) || !IsValidName(newName))
newName = null;
localFunction.Name = newName;
localFunction.ReducedMethod.Name = newName;
}
// Now generate names:
var mapping = new Dictionary<ILVariable, string>(ILVariableEqualityComparer.Instance);
foreach (var inst in function.Descendants.OfType<IInstructionWithVariableOperand>())
{
var v = inst.Variable;
if (!mapping.TryGetValue(v, out string name))
{
if (string.IsNullOrEmpty(v.Name))
v.Name = GenerateNameForVariable(v);
mapping.Add(v, v.Name);
}
else
{
v.Name = name;
}
}
foreach (var localFunction in function.LocalFunctions)
{
var newName = localFunction.Name;
if (newName == null)
{
string nameWithoutNumber = "f";
if (!reservedVariableNames.TryGetValue(nameWithoutNumber, out int currentIndex))
{
currentIndex = 1;
}
int count = Math.Max(1, currentIndex) + 1;
reservedVariableNames[nameWithoutNumber] = count;
if (count > 1)
{
newName = nameWithoutNumber + count.ToString();
}
else
{
newName = nameWithoutNumber;
}
}
localFunction.Name = newName;
localFunction.ReducedMethod.Name = newName;
localFunctionMapping[(MethodDefinitionHandle)localFunction.ReducedMethod.MetadataToken] = newName;
}
foreach (var inst in function.Descendants)
{
LocalFunctionMethod localFunction;
switch (inst)
{
case Call call:
localFunction = call.Method as LocalFunctionMethod;
break;
case LdFtn ldftn:
localFunction = ldftn.Method as LocalFunctionMethod;
break;
default:
localFunction = null;
break;
}
if (localFunction == null || !localFunctionMapping.TryGetValue((MethodDefinitionHandle)localFunction.MetadataToken, out var name))
continue;
localFunction.Name = name;
}
}
/// <remarks>
/// Must be in sync with <see cref="GetNameFromInstruction" />.
/// </remarks>
internal static bool IsSupportedInstruction(object arg)
{
switch (arg)
{
case LdObj _:
case LdFlda _:
case LdsFlda _:
case CallInstruction _:
return true;
default:
return false;
}
}
bool ConflictWithLocal(ILVariable v)
{
if (v.Kind == VariableKind.UsingLocal || v.Kind == VariableKind.ForeachLocal)
{
if (reservedVariableNames.ContainsKey(v.Name))
return true;
}
return false;
}
internal static bool IsValidName(string varName)
{
if (string.IsNullOrWhiteSpace(varName))
return false;
if (!(char.IsLetter(varName[0]) || varName[0] == '_'))
return false;
for (int i = 1; i < varName.Length; i++)
{
if (!(char.IsLetterOrDigit(varName[i]) || varName[i] == '_'))
return false;
}
return true;
}
HashSet<ILVariable> CollectLoopCounters(ILFunction function)
{
var loopCounters = new HashSet<ILVariable>();
foreach (BlockContainer possibleLoop in function.Descendants.OfType<BlockContainer>())
{
if (possibleLoop.Kind != ContainerKind.For)
continue;
foreach (var inst in possibleLoop.Blocks.Last().Instructions)
{
if (HighLevelLoopTransform.MatchIncrement(inst, out var variable))
loopCounters.Add(variable);
}
}
return loopCounters;
}
string GenerateNameForVariable(ILVariable variable)
{
string proposedName = null;
if (variable.Type.IsKnownType(KnownTypeCode.Int32))
{
// test whether the variable might be a loop counter
if (loopCounters.Contains(variable))
{
// For loop variables, use i,j,k,l,m,n
for (char c = 'i'; c <= maxLoopVariableName; c++)
{
if (!reservedVariableNames.ContainsKey(c.ToString()))
{
proposedName = c.ToString();
break;
}
}
}
}
// The ComponentResourceManager inside InitializeComponent must be named "resources",
// otherwise the WinForms designer won't load the Form.
if (CSharp.CSharpDecompiler.IsWindowsFormsInitializeComponentMethod(context.Function.Method) && variable.Type.FullName == "System.ComponentModel.ComponentResourceManager")
{
proposedName = "resources";
}
if (string.IsNullOrEmpty(proposedName))
{
var proposedNameForAddress = variable.AddressInstructions.OfType<LdLoca>()
.Select(arg => arg.Parent is CallInstruction c ? c.GetParameter(arg.ChildIndex)?.Name : null)
.Where(arg => !string.IsNullOrWhiteSpace(arg))
.Except(currentLowerCaseTypeOrMemberNames).ToList();
if (proposedNameForAddress.Count > 0)
{
proposedName = proposedNameForAddress[0];
}
}
if (string.IsNullOrEmpty(proposedName))
{
var proposedNameForStores = new HashSet<string>();
foreach (var store in variable.StoreInstructions)
{
if (store is StLoc stloc)
{
var name = GetNameFromInstruction(stloc.Value);
if (!currentLowerCaseTypeOrMemberNames.Contains(name))
proposedNameForStores.Add(name);
}
else if (store is MatchInstruction match && match.SlotInfo == MatchInstruction.SubPatternsSlot)
{
var name = GetNameFromInstruction(match.TestedOperand);
if (!currentLowerCaseTypeOrMemberNames.Contains(name))
proposedNameForStores.Add(name);
}
}
if (proposedNameForStores.Count == 1)
{
proposedName = proposedNameForStores.Single();
}
}
if (string.IsNullOrEmpty(proposedName))
{
var proposedNameForLoads = variable.LoadInstructions
.Select(arg => GetNameForArgument(arg.Parent, arg.ChildIndex))
.Except(currentLowerCaseTypeOrMemberNames).ToList();
if (proposedNameForLoads.Count == 1)
{
proposedName = proposedNameForLoads[0];
}
}
if (string.IsNullOrEmpty(proposedName) && variable.Kind == VariableKind.StackSlot)
{
var proposedNameForStoresFromNewObj = variable.StoreInstructions.OfType<StLoc>()
.Select(expr => GetNameByType(GuessType(variable.Type, expr.Value, context)))
.Except(currentLowerCaseTypeOrMemberNames).ToList();
if (proposedNameForStoresFromNewObj.Count == 1)
{
proposedName = proposedNameForStoresFromNewObj[0];
}
}
if (string.IsNullOrEmpty(proposedName))
{
proposedName = GetNameByType(variable.Type);
}
// remove any numbers from the proposed name
proposedName = SplitName(proposedName, out int number);
if (!reservedVariableNames.ContainsKey(proposedName))
{
reservedVariableNames.Add(proposedName, 0);
}
int count = ++reservedVariableNames[proposedName];
Debug.Assert(!string.IsNullOrWhiteSpace(proposedName));
if (count > 1)
{
return proposedName + count.ToString();
}
else
{
return proposedName;
}
}
static string GetNameFromInstruction(ILInstruction inst)
{
switch (inst)
{
case LdObj ldobj:
return GetNameFromInstruction(ldobj.Target);
case LdFlda ldflda:
return CleanUpVariableName(ldflda.Field.Name);
case LdsFlda ldsflda:
return CleanUpVariableName(ldsflda.Field.Name);
case CallInstruction call:
if (call is NewObj)
break;
IMethod m = call.Method;
if (ExcludeMethodFromCandidates(m))
break;
if (m.Name.StartsWith("get_", StringComparison.OrdinalIgnoreCase) && m.Parameters.Count == 0)
{
// use name from properties, but not from indexers
return CleanUpVariableName(m.Name.Substring(4));
}
else if (m.Name.StartsWith("Get", StringComparison.OrdinalIgnoreCase) && m.Name.Length >= 4 && char.IsUpper(m.Name[3]))
{
// use name from Get-methods
return CleanUpVariableName(m.Name.Substring(3));
}
break;
case DynamicInvokeMemberInstruction dynInvokeMember:
if (dynInvokeMember.Name.StartsWith("Get", StringComparison.OrdinalIgnoreCase)
&& dynInvokeMember.Name.Length >= 4 && char.IsUpper(dynInvokeMember.Name[3]))
{
// use name from Get-methods
return CleanUpVariableName(dynInvokeMember.Name.Substring(3));
}
break;
}
return null;
}
static string GetNameForArgument(ILInstruction parent, int i)
{
switch (parent)
{
case StObj stobj:
IField field;
if (stobj.Target is LdFlda ldflda)
field = ldflda.Field;
else if (stobj.Target is LdsFlda ldsflda)
field = ldsflda.Field;
else
break;
return CleanUpVariableName(field.Name);
case CallInstruction call:
IMethod m = call.Method;
if (ExcludeMethodFromCandidates(m))
return null;
if (m.Parameters.Count == 1 && i == call.Arguments.Count - 1)
{
// argument might be value of a setter
if (m.Name.StartsWith("set_", StringComparison.OrdinalIgnoreCase))
{
return CleanUpVariableName(m.Name.Substring(4));
}
else if (m.Name.StartsWith("Set", StringComparison.OrdinalIgnoreCase) && m.Name.Length >= 4 && char.IsUpper(m.Name[3]))
{
return CleanUpVariableName(m.Name.Substring(3));
}
}
var p = call.GetParameter(i);
if (p != null && !string.IsNullOrEmpty(p.Name))
return CleanUpVariableName(p.Name);
break;
case Leave _:
return "result";
}
return null;
}
static bool ExcludeMethodFromCandidates(IMethod m)
{
if (m.SymbolKind == SymbolKind.Operator)
return true;
if (m.Name == "ToString")
return true;
if (m.Name == "Concat" && m.DeclaringType.IsKnownType(KnownTypeCode.String))
return true;
return false;
}
static string GetNameByType(IType type)
{
type = NullableType.GetUnderlyingType(type);
while (type is ModifiedType || type is PinnedType)
{
type = NullableType.GetUnderlyingType(((TypeWithElementType)type).ElementType);
}
string name = type.Kind switch {
TypeKind.Array => "array",
TypeKind.Pointer => "ptr",
TypeKind.TypeParameter => "val",
TypeKind.Unknown => "val",
TypeKind.Dynamic => "val",
TypeKind.ByReference => "reference",
TypeKind.Tuple => "tuple",
TypeKind.NInt => "num",
TypeKind.NUInt => "num",
_ => null
};
if (name != null)
{
return name;
}
if (type.IsAnonymousType())
{
name = "anon";
}
else if (type.Name.EndsWith("Exception", StringComparison.Ordinal))
{
name = "ex";
}
else if (type.IsCSharpNativeIntegerType())
{
name = "num";
}
else if (!typeNameToVariableNameDict.TryGetValue(type.FullName, out name))
{
name = type.Name;
// remove the 'I' for interfaces
if (name.Length >= 3 && name[0] == 'I' && char.IsUpper(name[1]) && char.IsLower(name[2]))
name = name.Substring(1);
name = CleanUpVariableName(name) ?? "obj";
}
return name;
}
static void AddExistingName(Dictionary<string, int> reservedVariableNames, string name)
{
if (string.IsNullOrEmpty(name))
return;
string nameWithoutDigits = SplitName(name, out int number);
if (reservedVariableNames.TryGetValue(nameWithoutDigits, out int existingNumber))
{
reservedVariableNames[nameWithoutDigits] = Math.Max(number, existingNumber);
}
else
{
reservedVariableNames.Add(nameWithoutDigits, number);
}
}
static string SplitName(string name, out int number)
{
// First, identify whether the name already ends with a number:
int pos = name.Length;
while (pos > 0 && name[pos - 1] >= '0' && name[pos - 1] <= '9')
pos--;
if (pos < name.Length)
{
if (int.TryParse(name.Substring(pos), out number))
{
return name.Substring(0, pos);
}
}
number = 1;
return name;
}
static string CleanUpVariableName(string name)
{
// remove the backtick (generics)
int pos = name.IndexOf('`');
if (pos >= 0)
name = name.Substring(0, pos);
// remove field prefix:
if (name.Length > 2 && name.StartsWith("m_", StringComparison.Ordinal))
name = name.Substring(2);
else if (name.Length > 1 && name[0] == '_' && (char.IsLetter(name[1]) || name[1] == '_'))
name = name.Substring(1);
if (TextWriterTokenWriter.ContainsNonPrintableIdentifierChar(name))
{
return null;
}
if (name.Length == 0)
return "obj";
else
return char.ToLower(name[0]) + name.Substring(1);
}
internal static IType GuessType(IType variableType, ILInstruction inst, ILTransformContext context)
{
if (!variableType.IsKnownType(KnownTypeCode.Object))
return variableType;
IType inferredType = inst.InferType(context.TypeSystem);
if (inferredType.Kind != TypeKind.Unknown)
return inferredType;
else
return variableType;
}
static Dictionary<string, int> CollectReservedVariableNames(ILFunction function,
ILVariable existingVariable, bool mustResolveConflicts)
{
var reservedVariableNames = new Dictionary<string, int>();
var rootFunction = function.Ancestors.OfType<ILFunction>().Single(f => f.Parent == null);
foreach (var f in rootFunction.Descendants.OfType<ILFunction>())
{
foreach (var p in rootFunction.Parameters)
{
AddExistingName(reservedVariableNames, p.Name);
}
foreach (var v in f.Variables.Where(v => v.Kind != VariableKind.Parameter))
{
if (v != existingVariable)
AddExistingName(reservedVariableNames, v.Name);
}
}
if (mustResolveConflicts)
{
var memberNames = CollectAllLowerCaseMemberNames(function.Method.DeclaringTypeDefinition)
.Concat(CollectAllLowerCaseTypeNames(function.Method.DeclaringTypeDefinition));
foreach (var name in memberNames)
AddExistingName(reservedVariableNames, name);
}
return reservedVariableNames;
}
internal static string GenerateForeachVariableName(ILFunction function, ILInstruction valueContext,
ILVariable existingVariable = null, bool mustResolveConflicts = false)
{
if (function == null)
throw new ArgumentNullException(nameof(function));
if (existingVariable != null && !existingVariable.HasGeneratedName)
{
return existingVariable.Name;
}
var reservedVariableNames = CollectReservedVariableNames(function, existingVariable, mustResolveConflicts);
string baseName = GetNameFromInstruction(valueContext);
if (string.IsNullOrEmpty(baseName))
{
if (valueContext is LdLoc ldloc && ldloc.Variable.Kind == VariableKind.Parameter)
{
baseName = ldloc.Variable.Name;
}
}
string proposedName = "item";
if (!string.IsNullOrEmpty(baseName))
{
if (!IsPlural(baseName, ref proposedName))
{
if (baseName.Length > 4 && baseName.EndsWith("List", StringComparison.Ordinal))
{
proposedName = baseName.Substring(0, baseName.Length - 4);
}
else if (baseName.Equals("list", StringComparison.OrdinalIgnoreCase))
{
proposedName = "item";
}
else if (baseName.EndsWith("children", StringComparison.OrdinalIgnoreCase))
{
proposedName = baseName.Remove(baseName.Length - 3);
}
}
}
// remove any numbers from the proposed name
proposedName = SplitName(proposedName, out int number);
if (!reservedVariableNames.ContainsKey(proposedName))
{
reservedVariableNames.Add(proposedName, 0);
}
int count = ++reservedVariableNames[proposedName];
Debug.Assert(!string.IsNullOrWhiteSpace(proposedName));
if (count > 1)
{
return proposedName + count.ToString();
}
else
{
return proposedName;
}
}
internal static string GenerateVariableName(ILFunction function, IType type,
ILInstruction valueContext = null, ILVariable existingVariable = null,
bool mustResolveConflicts = false)
{
if (function == null)
throw new ArgumentNullException(nameof(function));
var reservedVariableNames = CollectReservedVariableNames(function, existingVariable, mustResolveConflicts);
string baseName = valueContext != null ? GetNameFromInstruction(valueContext) ?? GetNameByType(type) : GetNameByType(type);
string proposedName = "obj";
if (!string.IsNullOrEmpty(baseName))
{
if (!IsPlural(baseName, ref proposedName))
{
if (baseName.Length > 4 && baseName.EndsWith("List", StringComparison.Ordinal))
{
proposedName = baseName.Substring(0, baseName.Length - 4);
}
else if (baseName.Equals("list", StringComparison.OrdinalIgnoreCase))
{
proposedName = "item";
}
else if (baseName.EndsWith("children", StringComparison.OrdinalIgnoreCase))
{
proposedName = baseName.Remove(baseName.Length - 3);
}
else
{
proposedName = baseName;
}
}
}
// remove any numbers from the proposed name
proposedName = SplitName(proposedName, out int number);
if (!reservedVariableNames.ContainsKey(proposedName))
{
reservedVariableNames.Add(proposedName, 0);
}
int count = ++reservedVariableNames[proposedName];
Debug.Assert(!string.IsNullOrWhiteSpace(proposedName));
if (count > 1)
{
return proposedName + count.ToString();
}
else
{
return proposedName;
}
}
private static bool IsPlural(string baseName, ref string proposedName)
{
var newName = Vocabularies.Default.Singularize(baseName, inputIsKnownToBePlural: false);
if (string.IsNullOrWhiteSpace(newName) || newName == baseName)
return false;
proposedName = newName;
return true;
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs",
"repo_id": "ILSpy",
"token_count": 10440
} | 239 |
// Copyright (c) 2019 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.TypeSystem;
namespace ICSharpCode.Decompiler.IL.Transforms
{
/// <summary>
/// Context object for the ILInstruction.Extract() operation.
/// </summary>
class ExtractionContext
{
/// <summary>
/// Nearest function, used for registering the new locals that are created by extraction.
/// </summary>
readonly ILFunction Function;
readonly ILTransformContext context;
/// <summary>
/// Combined flags of all instructions being moved.
/// </summary>
internal InstructionFlags FlagsBeingMoved;
/// <summary>
/// List of actions to be executed when performing the extraction.
///
/// Each function in this list has the side-effect of replacing the instruction-to-be-moved
/// with a load of a fresh temporary variable; and returns the the store to the temporary variable,
/// which will be inserted at block-level.
/// </summary>
readonly List<Func<ILInstruction>> MoveActions = new List<Func<ILInstruction>>();
ExtractionContext(ILFunction function, ILTransformContext context)
{
Debug.Assert(function != null);
this.Function = function;
this.context = context;
}
internal void RegisterMove(ILInstruction predecessor)
{
FlagsBeingMoved |= predecessor.Flags;
MoveActions.Add(delegate {
var type = context.TypeSystem.FindType(predecessor.ResultType);
var v = Function.RegisterVariable(VariableKind.StackSlot, type);
predecessor.ReplaceWith(new LdLoc(v));
return new StLoc(v, predecessor);
});
}
internal void RegisterMoveIfNecessary(ILInstruction predecessor)
{
if (!CanReorderWithInstructionsBeingMoved(predecessor))
{
RegisterMove(predecessor);
}
}
/// <summary>
/// Currently, <c>predecessor</c> is evaluated before the instructions being moved.
/// If this function returns true, <c>predecessor</c> can stay as-is, despite the move changing the evaluation order.
/// If this function returns false, <c>predecessor</c> will need to also move, to ensure the evaluation order stays unchanged.
/// </summary>
public bool CanReorderWithInstructionsBeingMoved(ILInstruction predecessor)
{
// We could track the instructions being moved and be smarter about unnecessary moves,
// but given the limited scenarios where extraction is used so far,
// this seems unnecessary.
return predecessor.Flags == InstructionFlags.None;
}
/// <summary>
/// Extracts the specified 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.
///
/// May return null if extraction is not possible.
/// </summary>
public static ILVariable Extract(ILInstruction instToExtract, ILTransformContext context)
{
var function = instToExtract.Ancestors.OfType<ILFunction>().First();
ExtractionContext ctx = new ExtractionContext(function, context);
ctx.FlagsBeingMoved = instToExtract.Flags;
ILInstruction inst = instToExtract;
while (inst != null)
{
if (inst.Parent is IfInstruction ifInst && inst.SlotInfo != IfInstruction.ConditionSlot)
{
// this context doesn't support extraction, but maybe we can create a block here?
if (ifInst.ResultType == StackType.Void)
{
Block newBlock = new Block();
inst.ReplaceWith(newBlock);
newBlock.Instructions.Add(inst);
}
}
if (inst.Parent is Block { Kind: BlockKind.ControlFlow } block)
{
// We've reached a target block, and extraction is possible all the way.
// Check if the parent BlockContainer allows extraction:
if (block.Parent is BlockContainer container)
{
switch (container.Kind)
{
case ContainerKind.Normal:
case ContainerKind.Loop:
// extraction is always possible
break;
case ContainerKind.Switch:
// extraction is possible, unless in the entry-point (i.e., the switch head)
if (block == container.EntryPoint && inst.ChildIndex == 0)
{
// try to extract to the container's parent block, if it's a valid location
inst = container;
continue;
}
break;
case ContainerKind.While:
// extraction is possible, unless in the entry-point (i.e., the condition block)
if (block == container.EntryPoint)
{
return null;
}
break;
case ContainerKind.DoWhile:
// extraction is possible, unless in the last block (i.e., the condition block)
if (block == container.Blocks.Last())
{
return null;
}
break;
case ContainerKind.For:
// extraction is possible, unless in the first or last block
// (i.e., the condition block or increment block)
if (block == container.EntryPoint
|| block == container.Blocks.Last())
{
return null;
}
break;
}
}
int insertIndex = inst.ChildIndex;
var type = context.TypeSystem.FindType(instToExtract.ResultType);
// Move instToExtract itself:
var v = function.RegisterVariable(VariableKind.StackSlot, type);
instToExtract.ReplaceWith(new LdLoc(v));
block.Instructions.Insert(insertIndex, new StLoc(v, instToExtract));
// Apply the other move actions:
foreach (var moveAction in ctx.MoveActions)
{
block.Instructions.Insert(insertIndex, moveAction());
}
return v;
}
if (!inst.Parent.PrepareExtract(inst.ChildIndex, ctx))
return null;
inst = inst.Parent;
}
return null;
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs",
"repo_id": "ILSpy",
"token_count": 2339
} | 240 |
// Copyright (c) 2021 Daniel Grunwald, 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using ICSharpCode.Decompiler.IL.ControlFlow;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL.Transforms
{
class PatternMatchingTransform : IILTransform
{
void IILTransform.Run(ILFunction function, ILTransformContext context)
{
if (!context.Settings.PatternMatching)
return;
foreach (var container in function.Descendants.OfType<BlockContainer>())
{
ControlFlowGraph? cfg = null;
foreach (var block in container.Blocks.Reverse())
{
if (PatternMatchValueTypes(block, container, context, ref cfg))
{
continue;
}
if (PatternMatchRefTypes(block, container, context, ref cfg))
{
continue;
}
}
container.Blocks.RemoveAll(b => b.Instructions.Count == 0);
}
}
/// Block {
/// ...
/// stloc V(isinst T(testedOperand))
/// if (comp.o(ldloc V == ldnull)) br falseBlock
/// br trueBlock
/// }
///
/// All other uses of V are in blocks dominated by trueBlock.
/// =>
/// Block {
/// ...
/// if (match.type[T].notnull(V = testedOperand)) br trueBlock
/// br falseBlock
/// }
///
/// - or -
///
/// Block {
/// stloc s(isinst T(testedOperand))
/// stloc v(ldloc s)
/// if (logic.not(comp.o(ldloc s != ldnull))) br falseBlock
/// br trueBlock
/// }
/// =>
/// Block {
/// ...
/// if (match.type[T].notnull(V = testedOperand)) br trueBlock
/// br falseBlock
/// }
///
/// All other uses of V are in blocks dominated by trueBlock.
private bool PatternMatchRefTypes(Block block, BlockContainer container, ILTransformContext context, ref ControlFlowGraph? cfg)
{
if (!block.MatchIfAtEndOfBlock(out var condition, out var trueInst, out var falseInst))
return false;
int pos = block.Instructions.Count - 3;
if (condition.MatchLdLoc(out var conditionVar))
{
// stloc conditionVar(comp.o(ldloc s == ldnull))
// if (logic.not(ldloc conditionVar)) br trueBlock
if (pos < 0)
return false;
if (!(conditionVar.IsSingleDefinition && conditionVar.LoadCount == 1
&& conditionVar.Kind == VariableKind.StackSlot))
{
return false;
}
if (!block.Instructions[pos].MatchStLoc(conditionVar, out condition))
return false;
pos--;
}
if (condition.MatchCompEqualsNull(out var loadInNullCheck))
{
ExtensionMethods.Swap(ref trueInst, ref falseInst);
}
else if (condition.MatchCompNotEqualsNull(out loadInNullCheck))
{
// do nothing
}
else
{
return false;
}
if (!loadInNullCheck.MatchLdLoc(out var s))
return false;
if (!s.IsSingleDefinition)
return false;
if (s.Kind is not (VariableKind.Local or VariableKind.StackSlot))
return false;
if (pos < 0)
return false;
// stloc V(isinst T(testedOperand))
ILInstruction storeToV = block.Instructions[pos];
if (!storeToV.MatchStLoc(out var v, out var value))
return false;
if (value.MatchLdLoc(s))
{
// stloc v(ldloc s)
pos--;
if (pos < 0 || !block.Instructions[pos].MatchStLoc(s, out value))
return false;
if (v.Kind is not (VariableKind.Local or VariableKind.StackSlot))
return false;
if (s.LoadCount != 2)
return false;
}
else
{
if (v != s)
return false;
}
IType? unboxType;
if (value is UnboxAny unboxAny)
{
// stloc S(unbox.any T(isinst T(testedOperand)))
unboxType = unboxAny.Type;
value = unboxAny.Argument;
}
else
{
unboxType = null;
}
if (value is not IsInst { Argument: var testedOperand, Type: var type })
return false;
if (type.IsReferenceType != true)
return false;
if (!(unboxType == null || type.Equals(unboxType)))
return false;
if (!v.Type.Equals(type))
return false;
if (!CheckAllUsesDominatedBy(v, container, trueInst, storeToV, loadInNullCheck, context, ref cfg))
return false;
context.Step($"Type pattern matching {v.Name}", block);
// if (match.type[T].notnull(V = testedOperand)) br trueBlock
var ifInst = (IfInstruction)block.Instructions.SecondToLastOrDefault()!;
ifInst.Condition = new MatchInstruction(v, testedOperand) {
CheckNotNull = true,
CheckType = true
}.WithILRange(ifInst.Condition);
ifInst.TrueInst = trueInst;
block.Instructions[block.Instructions.Count - 1] = falseInst;
block.Instructions.RemoveRange(pos, ifInst.ChildIndex - pos);
v.Kind = VariableKind.PatternLocal;
DetectPropertySubPatterns((MatchInstruction)ifInst.Condition, trueInst, falseInst, container, context, ref cfg);
return true;
}
private static ILInstruction DetectPropertySubPatterns(MatchInstruction parentPattern, ILInstruction trueInst,
ILInstruction parentFalseInst, BlockContainer container, ILTransformContext context, ref ControlFlowGraph? cfg)
{
if (!context.Settings.RecursivePatternMatching)
{
return trueInst;
}
while (true)
{
Block? trueBlock = trueInst as Block;
if (!(trueBlock != null || trueInst.MatchBranch(out trueBlock)))
{
break;
}
if (!(trueBlock.IncomingEdgeCount == 1 && trueBlock.Parent == container))
{
break;
}
var nextTrueInst = DetectPropertySubPattern(parentPattern, trueBlock, parentFalseInst, context, ref cfg);
if (nextTrueInst != null)
{
trueInst = nextTrueInst;
}
else
{
break;
}
}
return trueInst;
}
private static ILInstruction? DetectPropertySubPattern(MatchInstruction parentPattern, Block block,
ILInstruction parentFalseInst, ILTransformContext context, ref ControlFlowGraph? cfg)
{
// if (match.notnull.type[System.String] (V_0 = callvirt get_C(ldloc V_2))) br IL_0022
// br IL_0037
if (MatchBlockContainingOneCondition(block, out var condition, out var trueInst, out var falseInst))
{
bool negate = false;
if (!DetectExitPoints.CompatibleExitInstruction(parentFalseInst, falseInst))
{
if (!DetectExitPoints.CompatibleExitInstruction(parentFalseInst, trueInst))
{
return null;
}
ExtensionMethods.Swap(ref trueInst, ref falseInst);
negate = true;
}
if (MatchInstruction.IsPatternMatch(condition, out var operand, context.Settings))
{
if (!PropertyOrFieldAccess(operand, out var target, out _))
{
return null;
}
if (!target.MatchLdLocRef(parentPattern.Variable))
{
return null;
}
if (negate && !context.Settings.PatternCombinators)
{
return null;
}
context.Step("Move property sub pattern", condition);
if (negate)
{
condition = Comp.LogicNot(condition);
}
parentPattern.SubPatterns.Add(condition);
}
else if (PropertyOrFieldAccess(condition, out var target, out _))
{
if (!target.MatchLdLocRef(parentPattern.Variable))
{
return null;
}
if (!negate && !context.Settings.PatternCombinators)
{
return null;
}
context.Step("Sub pattern: implicit != 0", condition);
parentPattern.SubPatterns.Add(new Comp(negate ? ComparisonKind.Equality : ComparisonKind.Inequality,
Sign.None, condition, new LdcI4(0)));
}
else
{
return null;
}
block.Instructions.Clear();
block.Instructions.Add(trueInst);
return trueInst;
}
else if (block.Instructions[0].MatchStLoc(out var targetVariable, out var operand))
{
if (!PropertyOrFieldAccess(operand, out var target, out var member))
{
return null;
}
if (!target.MatchLdLocRef(parentPattern.Variable))
{
return null;
}
if (!targetVariable.Type.Equals(member.ReturnType))
{
return null;
}
if (!CheckAllUsesDominatedBy(targetVariable, (BlockContainer)block.Parent!, block, block.Instructions[0], null, context, ref cfg))
{
return null;
}
context.Step("Property var pattern", block);
var varPattern = new MatchInstruction(targetVariable, operand)
.WithILRange(block.Instructions[0]);
parentPattern.SubPatterns.Add(varPattern);
block.Instructions.RemoveAt(0);
targetVariable.Kind = VariableKind.PatternLocal;
if (targetVariable.Type.IsKnownType(KnownTypeCode.NullableOfT))
{
return MatchNullableHasValueCheckPattern(block, varPattern, parentFalseInst, context, ref cfg)
?? block;
}
var instructionAfterNullCheck = MatchNullCheckPattern(block, varPattern, parentFalseInst, context);
if (instructionAfterNullCheck != null)
{
return DetectPropertySubPatterns(varPattern, instructionAfterNullCheck, parentFalseInst, (BlockContainer)block.Parent!, context, ref cfg);
}
else if (targetVariable.Type.IsReferenceType == false)
{
return DetectPropertySubPatterns(varPattern, block, parentFalseInst, (BlockContainer)block.Parent!, context, ref cfg);
}
else
{
return block;
}
}
else
{
return null;
}
}
private static ILInstruction? MatchNullCheckPattern(Block block, MatchInstruction varPattern,
ILInstruction parentFalseInst, ILTransformContext context)
{
if (!MatchBlockContainingOneCondition(block, out var condition, out var trueInst, out var falseInst))
{
return null;
}
if (condition.MatchCompEqualsNull(out var arg) && arg.MatchLdLoc(varPattern.Variable))
{
ExtensionMethods.Swap(ref trueInst, ref falseInst);
}
else if (condition.MatchCompNotEqualsNull(out arg) && arg.MatchLdLoc(varPattern.Variable))
{
}
else
{
return null;
}
if (!DetectExitPoints.CompatibleExitInstruction(falseInst, parentFalseInst))
{
return null;
}
context.Step("Null check pattern", block);
varPattern.CheckNotNull = true;
block.Instructions.Clear();
block.Instructions.Add(trueInst);
return trueInst;
}
private static ILInstruction? MatchNullableHasValueCheckPattern(Block block, MatchInstruction varPattern,
ILInstruction parentFalseInst, ILTransformContext context, ref ControlFlowGraph? cfg)
{
if (!(varPattern.Variable.StoreCount == 1 && varPattern.Variable.LoadCount == 0))
{
return null;
}
if (!MatchBlockContainingOneCondition(block, out var condition, out var trueInst, out var falseInst))
{
return null;
}
if (!NullableLiftingTransform.MatchHasValueCall(condition, varPattern.Variable))
{
return null;
}
if (!DetectExitPoints.CompatibleExitInstruction(falseInst, parentFalseInst))
{
if (DetectExitPoints.CompatibleExitInstruction(trueInst, parentFalseInst))
{
if (!(varPattern.Variable.AddressCount == 1))
{
return null;
}
context.Step("Nullable.HasValue check -> null pattern", block);
varPattern.ReplaceWith(new Comp(ComparisonKind.Equality, ComparisonLiftingKind.CSharp, StackType.O, Sign.None, varPattern.TestedOperand, new LdNull()));
block.Instructions.Clear();
block.Instructions.Add(falseInst);
return falseInst;
}
return null;
}
if (varPattern.Variable.AddressCount == 1 && context.Settings.PatternCombinators)
{
context.Step("Nullable.HasValue check -> not null pattern", block);
varPattern.ReplaceWith(new Comp(ComparisonKind.Inequality, ComparisonLiftingKind.CSharp, StackType.O, Sign.None, varPattern.TestedOperand, new LdNull()));
block.Instructions.Clear();
block.Instructions.Add(trueInst);
return trueInst;
}
else if (varPattern.Variable.AddressCount != 2)
{
return null;
}
if (!(trueInst.MatchBranch(out var trueBlock) && trueBlock.Parent == block.Parent && trueBlock.IncomingEdgeCount == 1))
{
return null;
}
if (trueBlock.Instructions[0].MatchStLoc(out var newTargetVariable, out var getValueOrDefaultCall)
&& NullableLiftingTransform.MatchGetValueOrDefault(getValueOrDefaultCall, varPattern.Variable))
{
context.Step("Nullable.HasValue check + Nullable.GetValueOrDefault pattern", block);
varPattern.CheckNotNull = true;
varPattern.Variable = newTargetVariable;
newTargetVariable.Kind = VariableKind.PatternLocal;
block.Instructions.Clear();
block.Instructions.Add(trueInst);
trueBlock.Instructions.RemoveAt(0);
return DetectPropertySubPatterns(varPattern, trueBlock, parentFalseInst, (BlockContainer)block.Parent!, context, ref cfg);
}
else if (MatchBlockContainingOneCondition(trueBlock, out condition, out trueInst, out falseInst))
{
if (!(condition is Comp comp
&& MatchInstruction.IsConstant(comp.Right)
&& NullableLiftingTransform.MatchGetValueOrDefault(comp.Left, varPattern.Variable)))
{
return null;
}
if (!(context.Settings.RelationalPatterns || comp.Kind is ComparisonKind.Equality or ComparisonKind.Inequality))
{
return null;
}
bool negated = false;
if (!DetectExitPoints.CompatibleExitInstruction(falseInst, parentFalseInst))
{
if (!DetectExitPoints.CompatibleExitInstruction(trueInst, parentFalseInst))
{
return null;
}
ExtensionMethods.Swap(ref trueInst, ref falseInst);
negated = true;
}
if (comp.Kind == (negated ? ComparisonKind.Equality : ComparisonKind.Inequality))
{
return null;
}
if (negated && !context.Settings.PatternCombinators)
{
return null;
}
context.Step("Nullable.HasValue check + Nullable.GetValueOrDefault pattern", block);
// varPattern: match (v = testedOperand)
// comp: comp.i4(call GetValueOrDefault(ldloca v) != ldc.i4 42)
// =>
// comp.i4.lifted(testedOperand != ldc.i4 42)
block.Instructions.Clear();
block.Instructions.Add(trueInst);
trueBlock.Instructions.Clear();
comp.Left = varPattern.TestedOperand;
comp.LiftingKind = ComparisonLiftingKind.CSharp;
if (negated)
{
comp = Comp.LogicNot(comp);
}
varPattern.ReplaceWith(comp);
return trueInst;
}
else
{
return null;
}
}
private static bool PropertyOrFieldAccess(ILInstruction operand, [NotNullWhen(true)] out ILInstruction? target, [NotNullWhen(true)] out IMember? member)
{
if (operand is CallInstruction {
Method: {
SymbolKind: SymbolKind.Accessor,
AccessorKind: MethodSemanticsAttributes.Getter,
AccessorOwner: { } _member
},
Arguments: [var _target]
})
{
target = _target;
member = _member;
return true;
}
else if (operand.MatchLdFld(out target, out var field))
{
member = field;
return true;
}
else
{
member = null;
return false;
}
}
private static bool MatchBlockContainingOneCondition(Block block, [NotNullWhen(true)] out ILInstruction? condition, [NotNullWhen(true)] out ILInstruction? trueInst, [NotNullWhen(true)] out ILInstruction? falseInst)
{
switch (block.Instructions.Count)
{
case 2:
return block.MatchIfAtEndOfBlock(out condition, out trueInst, out falseInst);
case 3:
condition = null;
if (!block.MatchIfAtEndOfBlock(out var loadTemp, out trueInst, out falseInst))
return false;
if (!(loadTemp.MatchLdLoc(out var tempVar) && tempVar.IsSingleDefinition && tempVar.LoadCount == 1))
return false;
if (!block.Instructions[0].MatchStLoc(tempVar, out condition))
return false;
while (condition.MatchLogicNot(out var arg))
{
condition = arg;
ExtensionMethods.Swap(ref trueInst, ref falseInst);
}
return true;
default:
condition = null;
trueInst = null;
falseInst = null;
return false;
}
}
private static bool CheckAllUsesDominatedBy(ILVariable v, BlockContainer container, ILInstruction trueInst,
ILInstruction storeToV, ILInstruction? loadInNullCheck, ILTransformContext context, ref ControlFlowGraph? cfg)
{
var targetBlock = trueInst as Block;
if (targetBlock == null && !trueInst.MatchBranch(out targetBlock))
{
return false;
}
if (targetBlock.Parent != container)
return false;
if (targetBlock.IncomingEdgeCount != 1)
return false;
cfg ??= new ControlFlowGraph(container, context.CancellationToken);
var targetBlockNode = cfg.GetNode(targetBlock);
var uses = v.LoadInstructions.Concat<ILInstruction>(v.AddressInstructions)
.Concat(v.StoreInstructions.Cast<ILInstruction>());
foreach (var use in uses)
{
if (use == storeToV || use == loadInNullCheck)
continue;
Block? found = null;
for (ILInstruction? current = use; current != null; current = current.Parent)
{
if (current.Parent == container)
{
found = (Block)current;
break;
}
}
if (found == null)
return false;
var node = cfg.GetNode(found);
if (!targetBlockNode.Dominates(node))
return false;
}
return true;
}
/// Block {
/// ...
/// [stloc temp(ldloc testedOperand)]
/// if (comp.o(isinst T(ldloc testedOperand) == ldnull)) br falseBlock
/// br unboxBlock
/// }
///
/// Block unboxBlock (incoming: 1) {
/// stloc V(unbox.any T(ldloc temp))
/// ...
/// }
/// =>
/// Block {
/// ...
/// if (match.type[T].notnull(V = testedOperand)) br unboxBlock
/// br falseBlock
/// }
private bool PatternMatchValueTypes(Block block, BlockContainer container, ILTransformContext context, ref ControlFlowGraph? cfg)
{
if (!MatchIsInstBlock(block, out var type, out var testedOperand, out var testedVariable,
out var boxType1, out var unboxBlock, out var falseInst))
{
return false;
}
StLoc? tempStore = block.Instructions.ElementAtOrDefault(block.Instructions.Count - 3) as StLoc;
if (tempStore == null || !tempStore.Value.MatchLdLoc(testedVariable))
{
tempStore = null;
}
if (!MatchUnboxBlock(unboxBlock, type, out var unboxOperand, out var boxType2, out var storeToV))
{
return false;
}
if (!object.Equals(boxType1, boxType2))
{
return false;
}
if (unboxOperand == testedVariable)
{
// do nothing
}
else if (unboxOperand == tempStore?.Variable)
{
if (!(tempStore.Variable.IsSingleDefinition && tempStore.Variable.LoadCount == 1))
return false;
}
else
{
return false;
}
if (!CheckAllUsesDominatedBy(storeToV.Variable, container, unboxBlock, storeToV, null, context, ref cfg))
return false;
context.Step($"PatternMatching with {storeToV.Variable.Name}", block);
var ifInst = (IfInstruction)block.Instructions.SecondToLastOrDefault()!;
ifInst.Condition = new MatchInstruction(storeToV.Variable, testedOperand) {
CheckNotNull = true,
CheckType = true
};
ifInst.TrueInst = new Branch(unboxBlock);
block.Instructions[^1] = falseInst;
unboxBlock.Instructions.RemoveAt(0);
if (unboxOperand == tempStore?.Variable)
{
block.Instructions.Remove(tempStore);
}
// HACK: condition detection uses StartILOffset of blocks to decide which branch of if-else
// should become the then-branch. Change the unboxBlock StartILOffset from an offset inside
// the pattern matching machinery to an offset belonging to an instruction in the then-block.
unboxBlock.SetILRange(unboxBlock.Instructions[0]);
storeToV.Variable.Kind = VariableKind.PatternLocal;
DetectPropertySubPatterns((MatchInstruction)ifInst.Condition, unboxBlock, falseInst, container, context, ref cfg);
return true;
}
/// ...
/// if (comp.o(isinst T(ldloc testedOperand) == ldnull)) br falseBlock
/// br unboxBlock
/// - or -
/// ...
/// if (comp.o(isinst T(box ``0(ldloc testedOperand)) == ldnull)) br falseBlock
/// br unboxBlock
private bool MatchIsInstBlock(Block block,
[NotNullWhen(true)] out IType? type,
[NotNullWhen(true)] out ILInstruction? testedOperand,
[NotNullWhen(true)] out ILVariable? testedVariable,
out IType? boxType,
[NotNullWhen(true)] out Block? unboxBlock,
[NotNullWhen(true)] out ILInstruction? falseInst)
{
type = null;
testedOperand = null;
testedVariable = null;
boxType = null;
unboxBlock = null;
if (!block.MatchIfAtEndOfBlock(out var condition, out var trueInst, out falseInst))
{
return false;
}
if (condition.MatchCompEqualsNull(out var arg))
{
ExtensionMethods.Swap(ref trueInst, ref falseInst);
}
else if (condition.MatchCompNotEqualsNull(out arg))
{
// do nothing
}
else
{
return false;
}
if (!arg.MatchIsInst(out testedOperand, out type))
{
return false;
}
if (!(testedOperand.MatchBox(out var boxArg, out boxType) && boxType.Kind == TypeKind.TypeParameter))
{
boxArg = testedOperand;
}
if (!boxArg.MatchLdLoc(out testedVariable))
{
return false;
}
return trueInst.MatchBranch(out unboxBlock) && unboxBlock.Parent == block.Parent;
}
/// Block unboxBlock (incoming: 1) {
/// stloc V(unbox.any T(ldloc testedOperand))
/// ...
/// - or -
/// stloc V(unbox.any T(isinst T(box ``0(ldloc testedOperand))))
/// ...
/// }
private bool MatchUnboxBlock(Block unboxBlock, IType type, [NotNullWhen(true)] out ILVariable? testedVariable,
out IType? boxType, [NotNullWhen(true)] out StLoc? storeToV)
{
boxType = null;
storeToV = null;
testedVariable = null;
if (unboxBlock.IncomingEdgeCount != 1)
return false;
storeToV = unboxBlock.Instructions[0] as StLoc;
if (storeToV == null)
return false;
var value = storeToV.Value;
if (!(value.MatchUnboxAny(out var arg, out var t) && t.Equals(type)))
return false;
if (arg.MatchIsInst(out var isinstArg, out var isinstType) && isinstType.Equals(type))
{
arg = isinstArg;
}
if (arg.MatchBox(out var boxArg, out boxType) && boxType.Kind == TypeKind.TypeParameter)
{
arg = boxArg;
}
if (!arg.MatchLdLoc(out testedVariable))
{
return false;
}
if (boxType != null && !boxType.Equals(testedVariable.Type))
{
return false;
}
return true;
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Transforms/PatternMatchingTransform.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/PatternMatchingTransform.cs",
"repo_id": "ILSpy",
"token_count": 8967
} | 241 |
// Copyright (c) 2018 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL.Transforms
{
public class UserDefinedLogicTransform : IStatementTransform
{
void IStatementTransform.Run(Block block, int pos, StatementTransformContext context)
{
if (LegacyPattern(block, pos, context))
return;
if (RoslynOptimized(block, pos, context))
return;
}
bool RoslynOptimized(Block block, int pos, StatementTransformContext context)
{
// Roslyn, optimized pattern in combination with return statement:
// if (logic.not(call op_False(ldloc lhsVar))) leave IL_0000 (call op_BitwiseAnd(ldloc lhsVar, rhsInst))
// leave IL_0000(ldloc lhsVar)
// ->
// user.logic op_BitwiseAnd(ldloc lhsVar, rhsInst)
if (!block.Instructions[pos].MatchIfInstructionPositiveCondition(out var condition, out var trueInst, out var falseInst))
return false;
if (trueInst.OpCode == OpCode.Nop)
{
trueInst = block.Instructions[pos + 1];
}
else if (falseInst.OpCode == OpCode.Nop)
{
falseInst = block.Instructions[pos + 1];
}
else
{
return false;
}
if (trueInst.MatchReturn(out var trueValue) && falseInst.MatchReturn(out var falseValue))
{
var transformed = Transform(condition, trueValue, falseValue);
if (transformed == null)
{
transformed = TransformDynamic(condition, trueValue, falseValue);
}
if (transformed != null)
{
context.Step("User-defined short-circuiting logic operator (optimized return)", condition);
((Leave)block.Instructions[pos + 1]).Value = transformed;
block.Instructions.RemoveAt(pos);
return true;
}
}
return false;
}
bool LegacyPattern(Block block, int pos, StatementTransformContext context)
{
// Legacy csc pattern:
// stloc s(lhsInst)
// if (logic.not(call op_False(ldloc s))) Block {
// stloc s(call op_BitwiseAnd(ldloc s, rhsInst))
// }
// ->
// stloc s(user.logic op_BitwiseAnd(lhsInst, rhsInst))
if (!block.Instructions[pos].MatchStLoc(out var s, out var lhsInst))
return false;
if (!(s.Kind == VariableKind.StackSlot))
return false;
if (!(block.Instructions[pos + 1] is IfInstruction ifInst))
return false;
if (!ifInst.Condition.MatchLogicNot(out var condition))
return false;
if (!(MatchCondition(condition, out var s2, out string conditionMethodName) && s2 == s))
return false;
if (ifInst.FalseInst.OpCode != OpCode.Nop)
return false;
var trueInst = Block.Unwrap(ifInst.TrueInst);
if (!trueInst.MatchStLoc(s, out var storeValue))
return false;
if (storeValue is Call call)
{
if (!MatchBitwiseCall(call, s, conditionMethodName))
return false;
if (s.IsUsedWithin(call.Arguments[1]))
return false;
context.Step("User-defined short-circuiting logic operator (legacy pattern)", condition);
((StLoc)block.Instructions[pos]).Value = new UserDefinedLogicOperator(call.Method, lhsInst, call.Arguments[1])
.WithILRange(call);
block.Instructions.RemoveAt(pos + 1);
context.RequestRerun(); // the 'stloc s' may now be eligible for inlining
return true;
}
return false;
}
static bool MatchCondition(ILInstruction condition, out ILVariable v, out string name)
{
v = null;
name = null;
if (!(condition is Call call && call.Method.IsOperator && call.Arguments.Count == 1 && !call.IsLifted))
return false;
name = call.Method.Name;
if (!(name == "op_True" || name == "op_False"))
return false;
return call.Arguments[0].MatchLdLoc(out v);
}
static bool MatchBitwiseCall(Call call, ILVariable v, string conditionMethodName)
{
if (!(call != null && call.Method.IsOperator && call.Arguments.Count == 2 && !call.IsLifted))
return false;
if (!call.Arguments[0].MatchLdLoc(v))
return false;
return conditionMethodName == "op_False" && call.Method.Name == "op_BitwiseAnd"
|| conditionMethodName == "op_True" && call.Method.Name == "op_BitwiseOr";
}
/// <summary>
/// if (call op_False(ldloc lhsVar)) ldloc lhsVar else call op_BitwiseAnd(ldloc lhsVar, rhsInst)
/// -> user.logic op_BitwiseAnd(ldloc lhsVar, rhsInst)
/// or
/// if (call op_True(ldloc lhsVar)) ldloc lhsVar else call op_BitwiseOr(ldloc lhsVar, rhsInst)
/// -> user.logic op_BitwiseOr(ldloc lhsVar, rhsInst)
/// </summary>
public static ILInstruction Transform(ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst)
{
if (!MatchCondition(condition, out var lhsVar, out var conditionMethodName))
return null;
if (!trueInst.MatchLdLoc(lhsVar))
return null;
var call = falseInst as Call;
if (!MatchBitwiseCall(call, lhsVar, conditionMethodName))
return null;
var result = new UserDefinedLogicOperator(call.Method, call.Arguments[0], call.Arguments[1]);
result.AddILRange(condition);
result.AddILRange(trueInst);
result.AddILRange(call);
return result;
}
public static ILInstruction TransformDynamic(ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst)
{
// Check condition:
System.Linq.Expressions.ExpressionType unaryOp;
if (condition.MatchLdLoc(out var lhsVar))
{
// if (ldloc lhsVar) box bool(ldloc lhsVar) else dynamic.binary.operator.logic Or(ldloc lhsVar, rhsInst)
// -> dynamic.logic.operator OrElse(ldloc lhsVar, rhsInst)
if (trueInst is Box box && box.Type.IsKnownType(KnownTypeCode.Boolean))
{
unaryOp = System.Linq.Expressions.ExpressionType.IsTrue;
trueInst = box.Argument;
}
else if (falseInst is Box box2 && box2.Type.IsKnownType(KnownTypeCode.Boolean))
{
// negate condition and swap true/false
unaryOp = System.Linq.Expressions.ExpressionType.IsFalse;
falseInst = trueInst;
trueInst = box2.Argument;
}
else
{
return null;
}
}
else if (condition is DynamicUnaryOperatorInstruction unary)
{
// if (dynamic.unary.operator IsFalse(ldloc lhsVar)) ldloc lhsVar else dynamic.binary.operator.logic And(ldloc lhsVar, rhsInst)
// -> dynamic.logic.operator AndAlso(ldloc lhsVar, rhsInst)
unaryOp = unary.Operation;
if (!unary.Operand.MatchLdLoc(out lhsVar))
return null;
}
else if (MatchCondition(condition, out lhsVar, out string operatorMethodName))
{
// if (call op_False(ldloc s)) box S(ldloc s) else dynamic.binary.operator.logic And(ldloc s, rhsInst))
if (operatorMethodName == "op_True")
{
unaryOp = System.Linq.Expressions.ExpressionType.IsTrue;
}
else
{
Debug.Assert(operatorMethodName == "op_False");
unaryOp = System.Linq.Expressions.ExpressionType.IsFalse;
}
var callParamType = ((Call)condition).Method.Parameters.Single().Type.SkipModifiers();
if (callParamType.IsReferenceType == false)
{
// If lhs is a value type, eliminate the boxing instruction.
if (trueInst is Box box && NormalizeTypeVisitor.TypeErasure.EquivalentTypes(box.Type, callParamType))
{
trueInst = box.Argument;
}
else if (trueInst.OpCode == OpCode.LdcI4)
{
// special case, handled below in 'check trueInst'
}
else
{
return null;
}
}
}
else
{
return null;
}
// Check trueInst:
DynamicUnaryOperatorInstruction rhsUnary;
if (trueInst.MatchLdLoc(lhsVar))
{
// OK, typical pattern where the expression evaluates to 'dynamic'
rhsUnary = null;
}
else if (trueInst.MatchLdcI4(1) && unaryOp == System.Linq.Expressions.ExpressionType.IsTrue)
{
// logic.or(IsTrue(lhsVar), IsTrue(lhsVar | rhsInst))
// => IsTrue(lhsVar || rhsInst)
rhsUnary = falseInst as DynamicUnaryOperatorInstruction;
if (rhsUnary != null)
{
if (rhsUnary.Operation != System.Linq.Expressions.ExpressionType.IsTrue)
return null;
falseInst = rhsUnary.Operand;
}
else
{
return null;
}
}
else
{
return null;
}
System.Linq.Expressions.ExpressionType expectedBitop;
System.Linq.Expressions.ExpressionType logicOp;
if (unaryOp == System.Linq.Expressions.ExpressionType.IsFalse)
{
expectedBitop = System.Linq.Expressions.ExpressionType.And;
logicOp = System.Linq.Expressions.ExpressionType.AndAlso;
}
else if (unaryOp == System.Linq.Expressions.ExpressionType.IsTrue)
{
expectedBitop = System.Linq.Expressions.ExpressionType.Or;
logicOp = System.Linq.Expressions.ExpressionType.OrElse;
}
else
{
return null;
}
// Check falseInst:
if (!(falseInst is DynamicBinaryOperatorInstruction binary))
return null;
if (binary.Operation != expectedBitop)
return null;
if (!binary.Left.MatchLdLoc(lhsVar))
return null;
var logicInst = new DynamicLogicOperatorInstruction(binary.BinderFlags, logicOp, binary.CallingContext,
binary.LeftArgumentInfo, binary.Left, binary.RightArgumentInfo, binary.Right)
.WithILRange(binary);
if (rhsUnary != null)
{
rhsUnary.Operand = logicInst;
return rhsUnary;
}
else
{
return logicInst;
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs",
"repo_id": "ILSpy",
"token_count": 4023
} | 242 |
// 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
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using LightJson.Serialization;
/// <summary>
/// A wrapper object that contains a valid JSON value.
/// </summary>
[DebuggerDisplay("{ToString(),nq}", Type = "JsonValue({Type})")]
[DebuggerTypeProxy(typeof(JsonValueDebugView))]
internal struct JsonValue
{
/// <summary>
/// Represents a null JsonValue.
/// </summary>
public static readonly JsonValue Null = new JsonValue(JsonValueType.Null, default(double), null);
private readonly JsonValueType type;
private readonly object reference;
private readonly double value;
/// <summary>
/// Initializes a new instance of the <see cref="JsonValue"/> struct, representing a Boolean value.
/// </summary>
/// <param name="value">The value to be wrapped.</param>
public JsonValue(bool? value)
{
if (value.HasValue)
{
this.reference = null;
this.type = JsonValueType.Boolean;
this.value = value.Value ? 1 : 0;
}
else
{
this = JsonValue.Null;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonValue"/> struct, representing a Number value.
/// </summary>
/// <param name="value">The value to be wrapped.</param>
public JsonValue(double? value)
{
if (value.HasValue)
{
this.reference = null;
this.type = JsonValueType.Number;
this.value = value.Value;
}
else
{
this = JsonValue.Null;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonValue"/> struct, representing a String value.
/// </summary>
/// <param name="value">The value to be wrapped.</param>
public JsonValue(string value)
{
if (value != null)
{
this.value = default(double);
this.type = JsonValueType.String;
this.reference = value;
}
else
{
this = JsonValue.Null;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonValue"/> struct, representing a JsonObject.
/// </summary>
/// <param name="value">The value to be wrapped.</param>
public JsonValue(JsonObject value)
{
if (value != null)
{
this.value = default(double);
this.type = JsonValueType.Object;
this.reference = value;
}
else
{
this = JsonValue.Null;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonValue"/> struct, representing a Array reference value.
/// </summary>
/// <param name="value">The value to be wrapped.</param>
public JsonValue(JsonArray value)
{
if (value != null)
{
this.value = default(double);
this.type = JsonValueType.Array;
this.reference = value;
}
else
{
this = JsonValue.Null;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonValue"/> struct.
/// </summary>
/// <param name="type">The Json type of the JsonValue.</param>
/// <param name="value">
/// The internal value of the JsonValue.
/// This is used when the Json type is Number or Boolean.
/// </param>
/// <param name="reference">
/// The internal value reference of the JsonValue.
/// This value is used when the Json type is String, JsonObject, or JsonArray.
/// </param>
private JsonValue(JsonValueType type, double value, object reference)
{
this.type = type;
this.value = value;
this.reference = reference;
}
/// <summary>
/// Gets the type of this JsonValue.
/// </summary>
/// <value>The type of this JsonValue.</value>
public JsonValueType Type {
get {
return this.type;
}
}
/// <summary>
/// Gets a value indicating whether this JsonValue is Null.
/// </summary>
/// <value>A value indicating whether this JsonValue is Null.</value>
public bool IsNull {
get {
return this.Type == JsonValueType.Null;
}
}
/// <summary>
/// Gets a value indicating whether this JsonValue is a Boolean.
/// </summary>
/// <value>A value indicating whether this JsonValue is a Boolean.</value>
public bool IsBoolean {
get {
return this.Type == JsonValueType.Boolean;
}
}
/// <summary>
/// Gets a value indicating whether this JsonValue is an Integer.
/// </summary>
/// <value>A value indicating whether this JsonValue is an Integer.</value>
public bool IsInteger {
get {
if (!this.IsNumber)
{
return false;
}
var value = this.value;
return unchecked((int)value) == value;
}
}
/// <summary>
/// Gets a value indicating whether this JsonValue is a Number.
/// </summary>
/// <value>A value indicating whether this JsonValue is a Number.</value>
public bool IsNumber {
get {
return this.Type == JsonValueType.Number;
}
}
/// <summary>
/// Gets a value indicating whether this JsonValue is a String.
/// </summary>
/// <value>A value indicating whether this JsonValue is a String.</value>
public bool IsString {
get {
return this.Type == JsonValueType.String;
}
}
/// <summary>
/// Gets a value indicating whether this JsonValue is a JsonObject.
/// </summary>
/// <value>A value indicating whether this JsonValue is a JsonObject.</value>
public bool IsJsonObject {
get {
return this.Type == JsonValueType.Object;
}
}
/// <summary>
/// Gets a value indicating whether this JsonValue is a JsonArray.
/// </summary>
/// <value>A value indicating whether this JsonValue is a JsonArray.</value>
public bool IsJsonArray {
get {
return this.Type == JsonValueType.Array;
}
}
/// <summary>
/// Gets a value indicating whether this JsonValue represents a DateTime.
/// </summary>
/// <value>A value indicating whether this JsonValue represents a DateTime.</value>
public bool IsDateTime {
get {
return this.AsDateTime != null;
}
}
/// <summary>
/// Gets a value indicating whether this value is true or false.
/// </summary>
/// <value>This value as a Boolean type.</value>
public bool AsBoolean {
get {
switch (this.Type)
{
case JsonValueType.Boolean:
return this.value == 1;
case JsonValueType.Number:
return this.value != 0;
case JsonValueType.String:
return (string)this.reference != string.Empty;
case JsonValueType.Object:
case JsonValueType.Array:
return true;
default:
return false;
}
}
}
/// <summary>
/// Gets this value as an Integer type.
/// </summary>
/// <value>This value as an Integer type.</value>
public int AsInteger {
get {
var value = this.AsNumber;
// Prevent overflow if the value doesn't fit.
if (value >= int.MaxValue)
{
return int.MaxValue;
}
if (value <= int.MinValue)
{
return int.MinValue;
}
return (int)value;
}
}
/// <summary>
/// Gets this value as a Number type.
/// </summary>
/// <value>This value as a Number type.</value>
public double AsNumber {
get {
switch (this.Type)
{
case JsonValueType.Boolean:
return (this.value == 1)
? 1
: 0;
case JsonValueType.Number:
return this.value;
case JsonValueType.String:
double number;
if (double.TryParse((string)this.reference, NumberStyles.Float, CultureInfo.InvariantCulture, out number))
{
return number;
}
else
{
goto default;
}
default:
return 0;
}
}
}
/// <summary>
/// Gets this value as a String type.
/// </summary>
/// <value>This value as a String type.</value>
public string AsString {
get {
switch (this.Type)
{
case JsonValueType.Boolean:
return (this.value == 1)
? "true"
: "false";
case JsonValueType.Number:
return this.value.ToString(CultureInfo.InvariantCulture);
case JsonValueType.String:
return (string)this.reference;
default:
return null;
}
}
}
/// <summary>
/// Gets this value as an JsonObject.
/// </summary>
/// <value>This value as an JsonObject.</value>
public JsonObject AsJsonObject {
get {
return this.IsJsonObject
? (JsonObject)this.reference
: null;
}
}
/// <summary>
/// Gets this value as an JsonArray.
/// </summary>
/// <value>This value as an JsonArray.</value>
public JsonArray AsJsonArray {
get {
return this.IsJsonArray
? (JsonArray)this.reference
: null;
}
}
/// <summary>
/// Gets this value as a system.DateTime.
/// </summary>
/// <value>This value as a system.DateTime.</value>
public DateTime? AsDateTime {
get {
DateTime value;
if (this.IsString && DateTime.TryParse((string)this.reference, out value))
{
return value;
}
else
{
return null;
}
}
}
/// <summary>
/// Gets this (inner) value as a System.object.
/// </summary>
/// <value>This (inner) value as a System.object.</value>
public object AsObject {
get {
switch (this.Type)
{
case JsonValueType.Boolean:
case JsonValueType.Number:
return this.value;
case JsonValueType.String:
case JsonValueType.Object:
case JsonValueType.Array:
return this.reference;
default:
return null;
}
}
}
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get or set.</param>
/// <exception cref="System.InvalidOperationException">
/// Thrown when this JsonValue is not a JsonObject.
/// </exception>
public JsonValue this[string key] {
get {
if (this.IsJsonObject)
{
return ((JsonObject)this.reference)[key];
}
else
{
throw new InvalidOperationException("This value does not represent a JsonObject.");
}
}
set {
if (this.IsJsonObject)
{
((JsonObject)this.reference)[key] = value;
}
else
{
throw new InvalidOperationException("This value does not represent a JsonObject.");
}
}
}
/// <summary>
/// Gets or sets the value at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the value to get or set.</param>
/// <exception cref="System.InvalidOperationException">
/// Thrown when this JsonValue is not a JsonArray
/// </exception>
public JsonValue this[int index] {
get {
if (this.IsJsonArray)
{
return ((JsonArray)this.reference)[index];
}
else
{
throw new InvalidOperationException("This value does not represent a JsonArray.");
}
}
set {
if (this.IsJsonArray)
{
((JsonArray)this.reference)[index] = value;
}
else
{
throw new InvalidOperationException("This value does not represent a JsonArray.");
}
}
}
/// <summary>
/// Converts the given nullable boolean into a JsonValue.
/// </summary>
/// <param name="value">The value to be converted.</param>
public static implicit operator JsonValue(bool? value)
{
return new JsonValue(value);
}
/// <summary>
/// Converts the given nullable double into a JsonValue.
/// </summary>
/// <param name="value">The value to be converted.</param>
public static implicit operator JsonValue(double? value)
{
return new JsonValue(value);
}
/// <summary>
/// Converts the given string into a JsonValue.
/// </summary>
/// <param name="value">The value to be converted.</param>
public static implicit operator JsonValue(string value)
{
return new JsonValue(value);
}
/// <summary>
/// Converts the given JsonObject into a JsonValue.
/// </summary>
/// <param name="value">The value to be converted.</param>
public static implicit operator JsonValue(JsonObject value)
{
return new JsonValue(value);
}
/// <summary>
/// Converts the given JsonArray into a JsonValue.
/// </summary>
/// <param name="value">The value to be converted.</param>
public static implicit operator JsonValue(JsonArray value)
{
return new JsonValue(value);
}
/// <summary>
/// Converts the given DateTime? into a JsonValue.
/// </summary>
/// <remarks>
/// The DateTime value will be stored as a string using ISO 8601 format,
/// since JSON does not define a DateTime type.
/// </remarks>
/// <param name="value">The value to be converted.</param>
public static implicit operator JsonValue(DateTime? value)
{
if (value == null)
{
return JsonValue.Null;
}
return new JsonValue(value.Value.ToString("o"));
}
/// <summary>
/// Converts the given JsonValue into an Int.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
public static explicit operator int(JsonValue jsonValue)
{
if (jsonValue.IsInteger)
{
return jsonValue.AsInteger;
}
else
{
return 0;
}
}
/// <summary>
/// Converts the given JsonValue into a nullable Int.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
/// <exception cref="System.InvalidCastException">
/// Throws System.InvalidCastException when the inner value type of the
/// JsonValue is not the desired type of the conversion.
/// </exception>
public static explicit operator int?(JsonValue jsonValue)
{
if (jsonValue.IsNull)
{
return null;
}
else
{
return (int)jsonValue;
}
}
/// <summary>
/// Converts the given JsonValue into a Bool.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
public static explicit operator bool(JsonValue jsonValue)
{
if (jsonValue.IsBoolean)
{
return jsonValue.value == 1;
}
else
{
return false;
}
}
/// <summary>
/// Converts the given JsonValue into a nullable Bool.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
/// <exception cref="System.InvalidCastException">
/// Throws System.InvalidCastException when the inner value type of the
/// JsonValue is not the desired type of the conversion.
/// </exception>
public static explicit operator bool?(JsonValue jsonValue)
{
if (jsonValue.IsNull)
{
return null;
}
else
{
return (bool)jsonValue;
}
}
/// <summary>
/// Converts the given JsonValue into a Double.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
public static explicit operator double(JsonValue jsonValue)
{
if (jsonValue.IsNumber)
{
return jsonValue.value;
}
else
{
return double.NaN;
}
}
/// <summary>
/// Converts the given JsonValue into a nullable Double.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
/// <exception cref="System.InvalidCastException">
/// Throws System.InvalidCastException when the inner value type of the
/// JsonValue is not the desired type of the conversion.
/// </exception>
public static explicit operator double?(JsonValue jsonValue)
{
if (jsonValue.IsNull)
{
return null;
}
else
{
return (double)jsonValue;
}
}
/// <summary>
/// Converts the given JsonValue into a String.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
public static explicit operator string(JsonValue jsonValue)
{
if (jsonValue.IsString || jsonValue.IsNull)
{
return jsonValue.reference as string;
}
else
{
return null;
}
}
/// <summary>
/// Converts the given JsonValue into a JsonObject.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
public static explicit operator JsonObject(JsonValue jsonValue)
{
if (jsonValue.IsJsonObject || jsonValue.IsNull)
{
return jsonValue.reference as JsonObject;
}
else
{
return null;
}
}
/// <summary>
/// Converts the given JsonValue into a JsonArray.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
public static explicit operator JsonArray(JsonValue jsonValue)
{
if (jsonValue.IsJsonArray || jsonValue.IsNull)
{
return jsonValue.reference as JsonArray;
}
else
{
return null;
}
}
/// <summary>
/// Converts the given JsonValue into a DateTime.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
public static explicit operator DateTime(JsonValue jsonValue)
{
var dateTime = jsonValue.AsDateTime;
if (dateTime.HasValue)
{
return dateTime.Value;
}
else
{
return DateTime.MinValue;
}
}
/// <summary>
/// Converts the given JsonValue into a nullable DateTime.
/// </summary>
/// <param name="jsonValue">The JsonValue to be converted.</param>
public static explicit operator DateTime?(JsonValue jsonValue)
{
if (jsonValue.IsDateTime || jsonValue.IsNull)
{
return jsonValue.AsDateTime;
}
else
{
return null;
}
}
/// <summary>
/// Returns a value indicating whether the two given JsonValues are equal.
/// </summary>
/// <param name="a">First JsonValue to compare.</param>
/// <param name="b">Second JsonValue to compare.</param>
public static bool operator ==(JsonValue a, JsonValue b)
{
return (a.Type == b.Type)
&& (a.value == b.value)
&& Equals(a.reference, b.reference);
}
/// <summary>
/// Returns a value indicating whether the two given JsonValues are unequal.
/// </summary>
/// <param name="a">First JsonValue to compare.</param>
/// <param name="b">Second JsonValue to compare.</param>
public static bool operator !=(JsonValue a, JsonValue b)
{
return !(a == b);
}
/// <summary>
/// Returns a JsonValue by parsing the given string.
/// </summary>
/// <param name="text">The JSON-formatted string to be parsed.</param>
/// <returns>The <see cref="JsonValue"/> representing the parsed text.</returns>
public static JsonValue Parse(string text)
{
return JsonReader.Parse(text);
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (obj == null)
{
return this.IsNull;
}
var jsonValue = obj as JsonValue?;
if (jsonValue == null)
{
return false;
}
else
{
return this == jsonValue.Value;
}
}
/// <inheritdoc/>
public override int GetHashCode()
{
if (this.IsNull)
{
return this.Type.GetHashCode();
}
else
{
return this.Type.GetHashCode()
^ this.value.GetHashCode()
^ EqualityComparer<object>.Default.GetHashCode(this.reference);
}
}
[ExcludeFromCodeCoverage]
private class JsonValueDebugView
{
private JsonValue jsonValue;
public JsonValueDebugView(JsonValue jsonValue)
{
this.jsonValue = jsonValue;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public JsonObject ObjectView {
get {
if (this.jsonValue.IsJsonObject)
{
return (JsonObject)this.jsonValue.reference;
}
else
{
return null;
}
}
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public JsonArray ArrayView {
get {
if (this.jsonValue.IsJsonArray)
{
return (JsonArray)this.jsonValue.reference;
}
else
{
return null;
}
}
}
public JsonValueType Type {
get {
return this.jsonValue.Type;
}
}
public object Value {
get {
if (this.jsonValue.IsJsonObject)
{
return (JsonObject)this.jsonValue.reference;
}
else if (this.jsonValue.IsJsonArray)
{
return (JsonArray)this.jsonValue.reference;
}
else
{
return this.jsonValue;
}
}
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs",
"repo_id": "ILSpy",
"token_count": 7819
} | 243 |
// 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.Reflection.Metadata;
namespace ICSharpCode.Decompiler.Metadata
{
public static class SignatureBlobComparer
{
public static bool EqualsMethodSignature(BlobReader a, BlobReader b, MetadataReader contextForA, MetadataReader contextForB)
{
return EqualsMethodSignature(ref a, ref b, contextForA, contextForB);
}
static bool EqualsMethodSignature(ref BlobReader a, ref BlobReader b, MetadataReader contextForA, MetadataReader contextForB)
{
SignatureHeader header;
// compare signature headers
if (a.RemainingBytes == 0 || b.RemainingBytes == 0 || (header = a.ReadSignatureHeader()) != b.ReadSignatureHeader())
return false;
if (header.IsGeneric)
{
// read & compare generic parameter count
if (!IsSameCompressedInteger(ref a, ref b, out _))
return false;
}
// read & compare parameter count
if (!IsSameCompressedInteger(ref a, ref b, out int totalParameterCount))
return false;
if (!IsSameCompressedInteger(ref a, ref b, out int typeCode))
return false;
if (!TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode))
return false;
int i = 0;
for (; i < totalParameterCount; i++)
{
if (!IsSameCompressedInteger(ref a, ref b, out typeCode))
return false;
// varargs sentinel
if (typeCode == 65)
break;
if (!TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode))
return false;
}
for (; i < totalParameterCount; i++)
{
if (!IsSameCompressedInteger(ref a, ref b, out typeCode))
return false;
if (!TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode))
return false;
}
return true;
}
public static bool EqualsTypeSignature(BlobReader a, BlobReader b, MetadataReader contextForA, MetadataReader contextForB)
{
return EqualsTypeSignature(ref a, ref b, contextForA, contextForB);
}
static bool EqualsTypeSignature(ref BlobReader a, ref BlobReader b, MetadataReader contextForA, MetadataReader contextForB)
{
if (!IsSameCompressedInteger(ref a, ref b, out int typeCode))
return false;
return TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode);
}
static bool IsSameCompressedInteger(ref BlobReader a, ref BlobReader b, out int value)
{
return a.TryReadCompressedInteger(out value) && b.TryReadCompressedInteger(out int otherValue) && value == otherValue;
}
static bool IsSameCompressedSignedInteger(ref BlobReader a, ref BlobReader b, out int value)
{
return a.TryReadCompressedSignedInteger(out value) && b.TryReadCompressedSignedInteger(out int otherValue) && value == otherValue;
}
static bool TypesAreEqual(ref BlobReader a, ref BlobReader b, MetadataReader contextForA, MetadataReader contextForB, int typeCode)
{
switch (typeCode)
{
case 0x1: // ELEMENT_TYPE_VOID
case 0x2: // ELEMENT_TYPE_BOOLEAN
case 0x3: // ELEMENT_TYPE_CHAR
case 0x4: // ELEMENT_TYPE_I1
case 0x5: // ELEMENT_TYPE_U1
case 0x6: // ELEMENT_TYPE_I2
case 0x7: // ELEMENT_TYPE_U2
case 0x8: // ELEMENT_TYPE_I4
case 0x9: // ELEMENT_TYPE_U4
case 0xA: // ELEMENT_TYPE_I8
case 0xB: // ELEMENT_TYPE_U8
case 0xC: // ELEMENT_TYPE_R4
case 0xD: // ELEMENT_TYPE_R8
case 0xE: // ELEMENT_TYPE_STRING
case 0x16: // ELEMENT_TYPE_TYPEDBYREF
case 0x18: // ELEMENT_TYPE_I
case 0x19: // ELEMENT_TYPE_U
case 0x1C: // ELEMENT_TYPE_OBJECT
return true;
case 0xF: // ELEMENT_TYPE_PTR
case 0x10: // ELEMENT_TYPE_BYREF
case 0x45: // ELEMENT_TYPE_PINNED
case 0x1D: // ELEMENT_TYPE_SZARRAY
if (!IsSameCompressedInteger(ref a, ref b, out typeCode))
return false;
if (!TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode))
return false;
return true;
case 0x1B: // ELEMENT_TYPE_FNPTR
if (!EqualsMethodSignature(ref a, ref b, contextForA, contextForB))
return false;
return true;
case 0x14: // ELEMENT_TYPE_ARRAY
// element type
if (!IsSameCompressedInteger(ref a, ref b, out typeCode))
return false;
if (!TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode))
return false;
// rank
if (!IsSameCompressedInteger(ref a, ref b, out _))
return false;
// sizes
if (!IsSameCompressedInteger(ref a, ref b, out int numOfSizes))
return false;
for (int i = 0; i < numOfSizes; i++)
{
if (!IsSameCompressedInteger(ref a, ref b, out _))
return false;
}
// lower bounds
if (!IsSameCompressedInteger(ref a, ref b, out int numOfLowerBounds))
return false;
for (int i = 0; i < numOfLowerBounds; i++)
{
if (!IsSameCompressedSignedInteger(ref a, ref b, out _))
return false;
}
return true;
case 0x1F: // ELEMENT_TYPE_CMOD_REQD
case 0x20: // ELEMENT_TYPE_CMOD_OPT
// modifier
if (!TypeHandleEquals(ref a, ref b, contextForA, contextForB))
return false;
// unmodified type
if (!IsSameCompressedInteger(ref a, ref b, out typeCode))
return false;
if (!TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode))
return false;
return true;
case 0x15: // ELEMENT_TYPE_GENERICINST
// generic type
if (!IsSameCompressedInteger(ref a, ref b, out typeCode))
return false;
if (!TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode))
return false;
if (!IsSameCompressedInteger(ref a, ref b, out int numOfArguments))
return false;
for (int i = 0; i < numOfArguments; i++)
{
if (!IsSameCompressedInteger(ref a, ref b, out typeCode))
return false;
if (!TypesAreEqual(ref a, ref b, contextForA, contextForB, typeCode))
return false;
}
return true;
case 0x13: // ELEMENT_TYPE_VAR
case 0x1E: // ELEMENT_TYPE_MVAR
// index
if (!IsSameCompressedInteger(ref a, ref b, out _))
return false;
return true;
case 0x11: // ELEMENT_TYPE_VALUETYPE
case 0x12: // ELEMENT_TYPE_CLASS
if (!TypeHandleEquals(ref a, ref b, contextForA, contextForB))
return false;
return true;
default:
return false;
}
}
static bool TypeHandleEquals(ref BlobReader a, ref BlobReader b, MetadataReader contextForA, MetadataReader contextForB)
{
var typeA = a.ReadTypeHandle();
var typeB = b.ReadTypeHandle();
if (typeA.IsNil || typeB.IsNil)
return false;
return typeA.GetFullTypeName(contextForA) == typeB.GetFullTypeName(contextForB);
}
}
}
| ILSpy/ICSharpCode.Decompiler/Metadata/SignatureBlobComparer.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/SignatureBlobComparer.cs",
"repo_id": "ILSpy",
"token_count": 3041
} | 244 |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using ICSharpCode.Decompiler.Metadata;
namespace ICSharpCode.Decompiler
{
public static partial class SRMExtensions
{
public static ImmutableArray<MethodImplementationHandle> GetMethodImplementations(
this MethodDefinitionHandle handle, MetadataReader reader)
{
var resultBuilder = ImmutableArray.CreateBuilder<MethodImplementationHandle>();
var typeDefinition = reader.GetTypeDefinition(reader.GetMethodDefinition(handle)
.GetDeclaringType());
foreach (var methodImplementationHandle in typeDefinition.GetMethodImplementations())
{
var methodImplementation = reader.GetMethodImplementation(methodImplementationHandle);
if (methodImplementation.MethodBody == handle)
{
resultBuilder.Add(methodImplementationHandle);
}
}
return resultBuilder.ToImmutable();
}
}
}
| ILSpy/ICSharpCode.Decompiler/SRMHacks.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/SRMHacks.cs",
"repo_id": "ILSpy",
"token_count": 332
} | 245 |
// 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.Diagnostics;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Enum that describes the accessibility of an entity.
/// </summary>
public enum Accessibility : byte
{
// Note: some code depends on the fact that these values are within the range 0-7
/// <summary>
/// The entity is completely inaccessible. This is used for C# explicit interface implementations.
/// </summary>
None,
/// <summary>
/// The entity is only accessible within the same class.
/// </summary>
Private,
/// <summary>
/// The entity is accessible in derived classes within the same assembly.
/// This corresponds to C# <c>private protected</c>.
/// </summary>
ProtectedAndInternal,
/// <summary>
/// The entity is only accessible within the same class and in derived classes.
/// </summary>
Protected,
/// <summary>
/// The entity is accessible within the same assembly.
/// </summary>
Internal,
/// <summary>
/// The entity is accessible both everywhere in the assembly, and in all derived classes.
/// This corresponds to C# <c>protected internal</c>.
/// </summary>
ProtectedOrInternal,
/// <summary>
/// The entity is accessible everywhere.
/// </summary>
Public,
}
public static class AccessibilityExtensions
{
// This code depends on the fact that the enum values are sorted similar to the partial order
// where an accessibility is smaller than another if it makes an entity visibible to a subset of the code:
// digraph Accessibilities {
// none -> private -> protected_and_internal -> protected -> protected_or_internal -> public;
// none -> private -> protected_and_internal -> internal -> protected_or_internal -> public;
// }
/// <summary>
/// Gets whether a <= b in the partial order of accessibilities:
/// return true if b is accessible everywhere where a is accessible.
/// </summary>
public static bool LessThanOrEqual(this Accessibility a, Accessibility b)
{
// Exploit the enum order being similar to the partial order to dramatically simplify the logic here:
// protected vs. internal is the only pair for which the enum value order doesn't match the partial order
return a <= b && !(a == Accessibility.Protected && b == Accessibility.Internal);
}
/// <summary>
/// Computes the intersection of the two accessibilities:
/// The result is accessible from any given point in the code
/// iff both a and b are accessible from that point.
/// </summary>
public static Accessibility Intersect(this Accessibility a, Accessibility b)
{
if (a > b)
{
ExtensionMethods.Swap(ref a, ref b);
}
if (a == Accessibility.Protected && b == Accessibility.Internal)
{
return Accessibility.ProtectedAndInternal;
}
else
{
Debug.Assert(!(a == Accessibility.Internal && b == Accessibility.Protected));
return a;
}
}
/// <summary>
/// Computes the union of the two accessibilities:
/// The result is accessible from any given point in the code
/// iff at least one of a or b is accessible from that point.
/// </summary>
public static Accessibility Union(this Accessibility a, Accessibility b)
{
if (a > b)
{
ExtensionMethods.Swap(ref a, ref b);
}
if (a == Accessibility.Protected && b == Accessibility.Internal)
{
return Accessibility.ProtectedOrInternal;
}
else
{
Debug.Assert(!(a == Accessibility.Internal && b == Accessibility.Protected));
return b;
}
}
/// <summary>
/// Gets the effective accessibility of the entity.
/// For example, a public method in an internal class returns "internal".
/// </summary>
public static Accessibility EffectiveAccessibility(this IEntity entity)
{
Accessibility accessibility = entity.Accessibility;
for (ITypeDefinition typeDef = entity.DeclaringTypeDefinition; typeDef != null; typeDef = typeDef.DeclaringTypeDefinition)
{
accessibility = Intersect(accessibility, typeDef.Accessibility);
}
return accessibility;
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Accessibility.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Accessibility.cs",
"repo_id": "ILSpy",
"token_count": 1556
} | 246 |
// 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;
using System.Collections.Generic;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Type parameter of a generic class/method.
/// </summary>
public interface ITypeParameter : IType, ISymbol
{
/// <summary>
/// Get the type of this type parameter's owner.
/// </summary>
/// <returns>SymbolKind.TypeDefinition or SymbolKind.Method</returns>
SymbolKind OwnerType { get; }
/// <summary>
/// Gets the owning method/class.
/// This property may return null (for example for the dummy type parameters used by <see cref="NormalizeTypeVisitor.ReplaceMethodTypeParametersWithDummy"/>).
/// </summary>
/// <remarks>
/// For "class Outer<T> { class Inner {} }",
/// inner.TypeParameters[0].Owner will be the outer class, because the same
/// ITypeParameter instance is used both on Outer`1 and Outer`1+Inner.
/// </remarks>
IEntity? Owner { get; }
/// <summary>
/// Gets the index of the type parameter in the type parameter list of the owning method/class.
/// </summary>
int Index { get; }
/// <summary>
/// Gets the name of the type parameter.
/// </summary>
new string Name { get; }
/// <summary>
/// Gets the attributes declared on this type parameter.
/// </summary>
IEnumerable<IAttribute> GetAttributes();
/// <summary>
/// Gets the variance of this type parameter.
/// </summary>
VarianceModifier Variance { get; }
/// <summary>
/// Gets the effective base class of this type parameter.
/// </summary>
IType EffectiveBaseClass { get; }
/// <summary>
/// Gets the effective interface set of this type parameter.
/// </summary>
IReadOnlyCollection<IType> EffectiveInterfaceSet { get; }
/// <summary>
/// Gets if the type parameter has the 'new()' constraint.
/// </summary>
bool HasDefaultConstructorConstraint { get; }
/// <summary>
/// Gets if the type parameter has the 'class' constraint.
/// </summary>
bool HasReferenceTypeConstraint { get; }
/// <summary>
/// Gets if the type parameter has the 'struct' or 'unmanaged' constraint.
/// </summary>
bool HasValueTypeConstraint { get; }
/// <summary>
/// Gets if the type parameter has the 'unmanaged' constraint.
/// </summary>
bool HasUnmanagedConstraint { get; }
/// <summary>
/// Nullability of the reference type constraint. (e.g. "where T : class?").
///
/// Note that the nullability of a use of the type parameter may differ from this.
/// E.g. "T? GetNull<T>() where T : class => null;"
/// </summary>
Nullability NullabilityConstraint { get; }
IReadOnlyList<TypeConstraint> TypeConstraints { get; }
}
public readonly struct TypeConstraint
{
public SymbolKind SymbolKind => SymbolKind.Constraint;
public IType Type { get; }
public IReadOnlyList<IAttribute> Attributes { get; }
public TypeConstraint(IType type, IReadOnlyList<IAttribute>? attributes = null)
{
this.Type = type ?? throw new ArgumentNullException(nameof(type));
this.Attributes = attributes ?? EmptyList<IAttribute>.Instance;
}
}
/// <summary>
/// Represents the variance of a type parameter.
/// </summary>
public enum VarianceModifier : byte
{
/// <summary>
/// The type parameter is not variant.
/// </summary>
Invariant,
/// <summary>
/// The type parameter is covariant (used in output position).
/// </summary>
Covariant,
/// <summary>
/// The type parameter is contravariant (used in input position).
/// </summary>
Contravariant
};
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/ITypeParameter.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/ITypeParameter.cs",
"repo_id": "ILSpy",
"token_count": 1454
} | 247 |
// 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.Threading;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
public sealed class DummyTypeParameter : AbstractType, ITypeParameter
{
static ITypeParameter[] methodTypeParameters = { new DummyTypeParameter(SymbolKind.Method, 0) };
static ITypeParameter[] classTypeParameters = { new DummyTypeParameter(SymbolKind.TypeDefinition, 0) };
static IReadOnlyList<ITypeParameter>[] classTypeParameterLists = { EmptyList<ITypeParameter>.Instance };
public static ITypeParameter GetMethodTypeParameter(int index)
{
return GetTypeParameter(ref methodTypeParameters, SymbolKind.Method, index);
}
public static ITypeParameter GetClassTypeParameter(int index)
{
return GetTypeParameter(ref classTypeParameters, SymbolKind.TypeDefinition, index);
}
static ITypeParameter GetTypeParameter(ref ITypeParameter[] typeParameters, SymbolKind symbolKind, int index)
{
ITypeParameter[] tps = typeParameters;
while (index >= tps.Length)
{
// We don't have a normal type parameter for this index, so we need to extend our array.
// Because the array can be used concurrently from multiple threads, we have to use
// Interlocked.CompareExchange.
ITypeParameter[] newTps = new ITypeParameter[index + 1];
tps.CopyTo(newTps, 0);
for (int i = tps.Length; i < newTps.Length; i++)
{
newTps[i] = new DummyTypeParameter(symbolKind, i);
}
ITypeParameter[] oldTps = Interlocked.CompareExchange(ref typeParameters, newTps, tps);
if (oldTps == tps)
{
// exchange successful
tps = newTps;
}
else
{
// exchange not successful
tps = oldTps;
}
}
return tps[index];
}
/// <summary>
/// Gets a list filled with dummy type parameters.
/// </summary>
internal static IReadOnlyList<ITypeParameter> GetClassTypeParameterList(int length)
{
IReadOnlyList<ITypeParameter>[] tps = classTypeParameterLists;
while (length >= tps.Length)
{
// We don't have a normal type parameter for this index, so we need to extend our array.
// Because the array can be used concurrently from multiple threads, we have to use
// Interlocked.CompareExchange.
IReadOnlyList<ITypeParameter>[] newTps = new IReadOnlyList<ITypeParameter>[length + 1];
tps.CopyTo(newTps, 0);
for (int i = tps.Length; i < newTps.Length; i++)
{
var newList = new ITypeParameter[i];
for (int j = 0; j < newList.Length; j++)
{
newList[j] = GetClassTypeParameter(j);
}
newTps[i] = newList;
}
var oldTps = Interlocked.CompareExchange(ref classTypeParameterLists, newTps, tps);
if (oldTps == tps)
{
// exchange successful
tps = newTps;
}
else
{
// exchange not successful
tps = oldTps;
}
}
return tps[length];
}
readonly SymbolKind ownerType;
readonly int index;
private DummyTypeParameter(SymbolKind ownerType, int index)
{
this.ownerType = ownerType;
this.index = index;
}
SymbolKind ISymbol.SymbolKind {
get { return SymbolKind.TypeParameter; }
}
public override string Name {
get {
return (ownerType == SymbolKind.Method ? "!!" : "!") + index;
}
}
public override string ReflectionName {
get {
return (ownerType == SymbolKind.Method ? "``" : "`") + index;
}
}
public override string ToString()
{
return ReflectionName + " (dummy)";
}
public override bool? IsReferenceType {
get { return null; }
}
public override TypeKind Kind {
get { return TypeKind.TypeParameter; }
}
public override IType AcceptVisitor(TypeVisitor visitor)
{
return visitor.VisitTypeParameter(this);
}
public int Index {
get { return index; }
}
IEnumerable<IAttribute> ITypeParameter.GetAttributes() => EmptyList<IAttribute>.Instance;
SymbolKind ITypeParameter.OwnerType {
get { return ownerType; }
}
VarianceModifier ITypeParameter.Variance {
get { return VarianceModifier.Invariant; }
}
IEntity ITypeParameter.Owner {
get { return null; }
}
IType ITypeParameter.EffectiveBaseClass {
get { return SpecialType.UnknownType; }
}
IReadOnlyCollection<IType> ITypeParameter.EffectiveInterfaceSet {
get { return EmptyList<IType>.Instance; }
}
bool ITypeParameter.HasDefaultConstructorConstraint => false;
bool ITypeParameter.HasReferenceTypeConstraint => false;
bool ITypeParameter.HasValueTypeConstraint => false;
bool ITypeParameter.HasUnmanagedConstraint => false;
Nullability ITypeParameter.NullabilityConstraint => Nullability.Oblivious;
IReadOnlyList<TypeConstraint> ITypeParameter.TypeConstraints => EmptyList<TypeConstraint>.Instance;
public override IType ChangeNullability(Nullability nullability)
{
if (nullability == Nullability.Oblivious)
{
return this;
}
else
{
return new NullabilityAnnotatedTypeParameter(this, nullability);
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs",
"repo_id": "ILSpy",
"token_count": 2124
} | 248 |
// 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 System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
/// <summary>
/// An artificial "assembly" that contains all known types (<see cref="KnownTypeCode"/>) and no other types.
/// It does not contain any members.
/// </summary>
public sealed class MinimalCorlib : IModule
{
/// <summary>
/// Minimal corlib instance containing all known types.
/// </summary>
public static readonly IModuleReference Instance = new CorlibModuleReference(KnownTypeReference.AllKnownTypes);
public static IModuleReference CreateWithTypes(IEnumerable<KnownTypeReference> types)
{
return new CorlibModuleReference(types);
}
public ICompilation Compilation { get; }
CorlibTypeDefinition[] typeDefinitions;
readonly CorlibNamespace rootNamespace;
readonly Version asmVersion = new Version(0, 0, 0, 0);
private MinimalCorlib(ICompilation compilation, IEnumerable<KnownTypeReference> types)
{
this.Compilation = compilation;
this.typeDefinitions = types.Select(ktr => new CorlibTypeDefinition(this, ktr.KnownTypeCode)).ToArray();
this.rootNamespace = new CorlibNamespace(this, null, string.Empty, string.Empty);
}
bool IModule.IsMainModule => Compilation.MainModule == this;
string IModule.AssemblyName => "corlib";
Version IModule.AssemblyVersion => asmVersion;
string IModule.FullAssemblyName => "corlib";
string ISymbol.Name => "corlib";
SymbolKind ISymbol.SymbolKind => SymbolKind.Module;
Metadata.PEFile IModule.PEFile => null;
INamespace IModule.RootNamespace => rootNamespace;
public IEnumerable<ITypeDefinition> TopLevelTypeDefinitions => typeDefinitions.Where(td => td != null);
public IEnumerable<ITypeDefinition> TypeDefinitions => TopLevelTypeDefinitions;
public ITypeDefinition GetTypeDefinition(TopLevelTypeName topLevelTypeName)
{
foreach (var typeDef in typeDefinitions)
{
if (typeDef.FullTypeName == topLevelTypeName)
return typeDef;
}
return null;
}
IEnumerable<IAttribute> IModule.GetAssemblyAttributes() => EmptyList<IAttribute>.Instance;
IEnumerable<IAttribute> IModule.GetModuleAttributes() => EmptyList<IAttribute>.Instance;
bool IModule.InternalsVisibleTo(IModule module)
{
return module == this;
}
sealed class CorlibModuleReference : IModuleReference
{
readonly IEnumerable<KnownTypeReference> types;
public CorlibModuleReference(IEnumerable<KnownTypeReference> types)
{
this.types = types;
}
IModule IModuleReference.Resolve(ITypeResolveContext context)
{
return new MinimalCorlib(context.Compilation, types);
}
}
sealed class CorlibNamespace : INamespace
{
readonly MinimalCorlib corlib;
internal List<INamespace> childNamespaces = new List<INamespace>();
public INamespace ParentNamespace { get; }
public string FullName { get; }
public string Name { get; }
public CorlibNamespace(MinimalCorlib corlib, INamespace parentNamespace, string fullName, string name)
{
this.corlib = corlib;
this.ParentNamespace = parentNamespace;
this.FullName = fullName;
this.Name = name;
}
string INamespace.ExternAlias => string.Empty;
IEnumerable<INamespace> INamespace.ChildNamespaces => childNamespaces;
IEnumerable<ITypeDefinition> INamespace.Types => corlib.TopLevelTypeDefinitions.Where(td => td.Namespace == FullName);
IEnumerable<IModule> INamespace.ContributingModules => new[] { corlib };
SymbolKind ISymbol.SymbolKind => SymbolKind.Namespace;
ICompilation ICompilationProvider.Compilation => corlib.Compilation;
INamespace INamespace.GetChildNamespace(string name)
{
return childNamespaces.FirstOrDefault(ns => ns.Name == name);
}
ITypeDefinition INamespace.GetTypeDefinition(string name, int typeParameterCount)
{
return corlib.GetTypeDefinition(this.FullName, name, typeParameterCount);
}
}
sealed class CorlibTypeDefinition : ITypeDefinition
{
readonly MinimalCorlib corlib;
readonly KnownTypeCode typeCode;
readonly TypeKind typeKind;
public CorlibTypeDefinition(MinimalCorlib corlib, KnownTypeCode typeCode)
{
this.corlib = corlib;
this.typeCode = typeCode;
KnownTypeReference ktr = KnownTypeReference.Get(typeCode);
this.typeKind = ktr.typeKind;
this.MetadataName = ktr.Name + (ktr.TypeParameterCount > 0 ? "`" + ktr.TypeParameterCount : "");
}
IReadOnlyList<ITypeDefinition> ITypeDefinition.NestedTypes => EmptyList<ITypeDefinition>.Instance;
IReadOnlyList<IMember> ITypeDefinition.Members => EmptyList<IMember>.Instance;
IEnumerable<IField> ITypeDefinition.Fields => EmptyList<IField>.Instance;
IEnumerable<IMethod> ITypeDefinition.Methods => EmptyList<IMethod>.Instance;
IEnumerable<IProperty> ITypeDefinition.Properties => EmptyList<IProperty>.Instance;
IEnumerable<IEvent> ITypeDefinition.Events => EmptyList<IEvent>.Instance;
KnownTypeCode ITypeDefinition.KnownTypeCode => typeCode;
IType ITypeDefinition.EnumUnderlyingType => SpecialType.UnknownType;
public FullTypeName FullTypeName => KnownTypeReference.Get(typeCode).TypeName;
public string MetadataName { get; }
ITypeDefinition IEntity.DeclaringTypeDefinition => null;
IType ITypeDefinition.DeclaringType => null;
IType IType.DeclaringType => null;
IType IEntity.DeclaringType => null;
bool ITypeDefinition.HasExtensionMethods => false;
bool ITypeDefinition.IsReadOnly => false;
TypeKind IType.Kind => typeKind;
bool? IType.IsReferenceType {
get {
switch (typeKind)
{
case TypeKind.Class:
case TypeKind.Interface:
return true;
case TypeKind.Struct:
case TypeKind.Enum:
return false;
default:
return null;
}
}
}
bool IType.IsByRefLike => false;
Nullability IType.Nullability => Nullability.Oblivious;
Nullability ITypeDefinition.NullableContext => Nullability.Oblivious;
IType IType.ChangeNullability(Nullability nullability)
{
if (nullability == Nullability.Oblivious)
return this;
else
return new NullabilityAnnotatedType(this, nullability);
}
int IType.TypeParameterCount => KnownTypeReference.Get(typeCode).TypeParameterCount;
IReadOnlyList<ITypeParameter> IType.TypeParameters => DummyTypeParameter.GetClassTypeParameterList(KnownTypeReference.Get(typeCode).TypeParameterCount);
IReadOnlyList<IType> IType.TypeArguments => DummyTypeParameter.GetClassTypeParameterList(KnownTypeReference.Get(typeCode).TypeParameterCount);
IEnumerable<IType> IType.DirectBaseTypes {
get {
var baseType = KnownTypeReference.Get(typeCode).baseType;
if (baseType != KnownTypeCode.None)
return new[] { corlib.Compilation.FindType(baseType) };
else
return EmptyList<IType>.Instance;
}
}
EntityHandle IEntity.MetadataToken => MetadataTokens.TypeDefinitionHandle(0);
public string Name => KnownTypeReference.Get(typeCode).Name;
IModule IEntity.ParentModule => corlib;
Accessibility IEntity.Accessibility => Accessibility.Public;
bool IEntity.IsStatic => false;
bool IEntity.IsAbstract => typeKind == TypeKind.Interface;
bool IEntity.IsSealed => typeKind == TypeKind.Struct;
SymbolKind ISymbol.SymbolKind => SymbolKind.TypeDefinition;
ICompilation ICompilationProvider.Compilation => corlib.Compilation;
string INamedElement.FullName {
get {
var ktr = KnownTypeReference.Get(typeCode);
return ktr.Namespace + "." + ktr.Name;
}
}
string INamedElement.ReflectionName => KnownTypeReference.Get(typeCode).TypeName.ReflectionName;
string INamedElement.Namespace => KnownTypeReference.Get(typeCode).Namespace;
bool IEquatable<IType>.Equals(IType other)
{
return this == other;
}
IEnumerable<IMethod> IType.GetAccessors(Predicate<IMethod> filter, GetMemberOptions options)
{
return EmptyList<IMethod>.Instance;
}
IEnumerable<IAttribute> IEntity.GetAttributes() => EmptyList<IAttribute>.Instance;
bool IEntity.HasAttribute(KnownAttribute attribute) => false;
IAttribute IEntity.GetAttribute(KnownAttribute attribute) => null;
IEnumerable<IMethod> IType.GetConstructors(Predicate<IMethod> filter, GetMemberOptions options)
{
return EmptyList<IMethod>.Instance;
}
IEnumerable<IEvent> IType.GetEvents(Predicate<IEvent> filter, GetMemberOptions options)
{
return EmptyList<IEvent>.Instance;
}
IEnumerable<IField> IType.GetFields(Predicate<IField> filter, GetMemberOptions options)
{
return EmptyList<IField>.Instance;
}
IEnumerable<IMember> IType.GetMembers(Predicate<IMember> filter, GetMemberOptions options)
{
return EmptyList<IMember>.Instance;
}
IEnumerable<IMethod> IType.GetMethods(Predicate<IMethod> filter, GetMemberOptions options)
{
return EmptyList<IMethod>.Instance;
}
IEnumerable<IMethod> IType.GetMethods(IReadOnlyList<IType> typeArguments, Predicate<IMethod> filter, GetMemberOptions options)
{
return EmptyList<IMethod>.Instance;
}
IEnumerable<IType> IType.GetNestedTypes(Predicate<ITypeDefinition> filter, GetMemberOptions options)
{
return EmptyList<IType>.Instance;
}
IEnumerable<IType> IType.GetNestedTypes(IReadOnlyList<IType> typeArguments, Predicate<ITypeDefinition> filter, GetMemberOptions options)
{
return EmptyList<IType>.Instance;
}
IEnumerable<IProperty> IType.GetProperties(Predicate<IProperty> filter, GetMemberOptions options)
{
return EmptyList<IProperty>.Instance;
}
bool ITypeDefinition.IsRecord => false;
ITypeDefinition IType.GetDefinition() => this;
ITypeDefinitionOrUnknown IType.GetDefinitionOrUnknown() => this;
TypeParameterSubstitution IType.GetSubstitution() => TypeParameterSubstitution.Identity;
IType IType.AcceptVisitor(TypeVisitor visitor)
{
return visitor.VisitTypeDefinition(this);
}
IType IType.VisitChildren(TypeVisitor visitor)
{
return this;
}
public override string ToString()
{
return $"[MinimalCorlibType {typeCode}]";
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs",
"repo_id": "ILSpy",
"token_count": 3872
} | 249 |
// 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;
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Provides helper methods for inheritance.
/// </summary>
public static class InheritanceHelper
{
// TODO: maybe these should be extension methods?
// or even part of the interface itself? (would allow for easy caching)
#region GetBaseMember
/// <summary>
/// Gets the base member that has the same signature.
/// </summary>
public static IMember GetBaseMember(IMember member)
{
return GetBaseMembers(member, false).FirstOrDefault();
}
/// <summary>
/// Gets all base members that have the same signature.
/// </summary>
/// <returns>
/// List of base members with the same signature. The member from the derived-most base class is returned first.
/// </returns>
public static IEnumerable<IMember> GetBaseMembers(IMember member, bool includeImplementedInterfaces)
{
if (member == null)
throw new ArgumentNullException(nameof(member));
if (includeImplementedInterfaces)
{
if (member.IsExplicitInterfaceImplementation && member.ExplicitlyImplementedInterfaceMembers.Count() == 1)
{
// C#-style explicit interface implementation
member = member.ExplicitlyImplementedInterfaceMembers.First();
yield return member;
}
}
// Remove generic specialization
var substitution = member.Substitution;
member = member.MemberDefinition;
if (member.DeclaringTypeDefinition == null)
{
// For global methods, return empty list. (prevent SharpDevelop UDC crash 4524)
yield break;
}
IEnumerable<IType> allBaseTypes;
if (includeImplementedInterfaces)
{
allBaseTypes = member.DeclaringTypeDefinition.GetAllBaseTypes();
}
else
{
allBaseTypes = member.DeclaringTypeDefinition.GetNonInterfaceBaseTypes();
}
foreach (IType baseType in allBaseTypes.Reverse())
{
if (baseType == member.DeclaringTypeDefinition)
continue;
IEnumerable<IMember> baseMembers;
if (member.SymbolKind == SymbolKind.Accessor)
{
baseMembers = baseType.GetAccessors(m => m.Name == member.Name && m.Accessibility > Accessibility.Private, GetMemberOptions.IgnoreInheritedMembers);
}
else
{
baseMembers = baseType.GetMembers(m => m.Name == member.Name && m.Accessibility > Accessibility.Private, GetMemberOptions.IgnoreInheritedMembers);
}
foreach (IMember baseMember in baseMembers)
{
System.Diagnostics.Debug.Assert(baseMember.Accessibility != Accessibility.Private);
if (SignatureComparer.Ordinal.Equals(member, baseMember))
{
yield return baseMember.Specialize(substitution);
}
}
}
}
#endregion
#region GetDerivedMember
/// <summary>
/// Finds the member declared in 'derivedType' that has the same signature (could override) 'baseMember'.
/// </summary>
public static IMember GetDerivedMember(IMember baseMember, ITypeDefinition derivedType)
{
if (baseMember == null)
throw new ArgumentNullException(nameof(baseMember));
if (derivedType == null)
throw new ArgumentNullException(nameof(derivedType));
if (baseMember.Compilation != derivedType.Compilation)
throw new ArgumentException("baseMember and derivedType must be from the same compilation");
baseMember = baseMember.MemberDefinition;
bool includeInterfaces = baseMember.DeclaringTypeDefinition.Kind == TypeKind.Interface;
IMethod method = baseMember as IMethod;
if (method != null)
{
foreach (IMethod derivedMethod in derivedType.Methods)
{
if (derivedMethod.Name == method.Name && derivedMethod.Parameters.Count == method.Parameters.Count)
{
if (derivedMethod.TypeParameters.Count == method.TypeParameters.Count)
{
// The method could override the base method:
if (GetBaseMembers(derivedMethod, includeInterfaces).Any(m => m.MemberDefinition == baseMember))
return derivedMethod;
}
}
}
}
IProperty property = baseMember as IProperty;
if (property != null)
{
foreach (IProperty derivedProperty in derivedType.Properties)
{
if (derivedProperty.Name == property.Name && derivedProperty.Parameters.Count == property.Parameters.Count)
{
// The property could override the base property:
if (GetBaseMembers(derivedProperty, includeInterfaces).Any(m => m.MemberDefinition == baseMember))
return derivedProperty;
}
}
}
if (baseMember is IEvent)
{
foreach (IEvent derivedEvent in derivedType.Events)
{
if (derivedEvent.Name == baseMember.Name)
return derivedEvent;
}
}
if (baseMember is IField)
{
foreach (IField derivedField in derivedType.Fields)
{
if (derivedField.Name == baseMember.Name)
return derivedField;
}
}
return null;
}
#endregion
#region Attributes
internal static IEnumerable<IAttribute> GetAttributes(ITypeDefinition typeDef)
{
foreach (var baseType in typeDef.GetNonInterfaceBaseTypes().Reverse())
{
ITypeDefinition baseTypeDef = baseType.GetDefinition();
if (baseTypeDef == null)
continue;
foreach (var attr in baseTypeDef.GetAttributes())
{
yield return attr;
}
}
}
internal static IAttribute GetAttribute(ITypeDefinition typeDef, KnownAttribute attributeType)
{
foreach (var baseType in typeDef.GetNonInterfaceBaseTypes().Reverse())
{
ITypeDefinition baseTypeDef = baseType.GetDefinition();
if (baseTypeDef == null)
continue;
var attr = baseTypeDef.GetAttribute(attributeType);
if (attr != null)
return attr;
}
return null;
}
internal static IEnumerable<IAttribute> GetAttributes(IMember member)
{
HashSet<IMember> visitedMembers = new HashSet<IMember>();
do
{
member = member.MemberDefinition; // it's sufficient to look at the definitions
if (!visitedMembers.Add(member))
{
// abort if we seem to be in an infinite loop (cyclic inheritance)
break;
}
foreach (var attr in member.GetAttributes())
{
yield return attr;
}
} while (member.IsOverride && (member = InheritanceHelper.GetBaseMember(member)) != null);
}
internal static IAttribute GetAttribute(IMember member, KnownAttribute attributeType)
{
HashSet<IMember> visitedMembers = new HashSet<IMember>();
do
{
member = member.MemberDefinition; // it's sufficient to look at the definitions
if (!visitedMembers.Add(member))
{
// abort if we seem to be in an infinite loop (cyclic inheritance)
break;
}
var attr = member.GetAttribute(attributeType);
if (attr != null)
return attr;
} while (member.IsOverride && (member = InheritanceHelper.GetBaseMember(member)) != null);
return null;
}
#endregion
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs",
"repo_id": "ILSpy",
"token_count": 2735
} | 250 |
// Copyright (c) 2010-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;
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Helper class for dealing with System.Threading.Tasks.Task.
/// </summary>
public static class TaskType
{
/// <summary>
/// Gets the T in Task<T>.
/// Returns void for non-generic Task.
/// Any other type is returned unmodified.
/// </summary>
public static IType UnpackTask(ICompilation compilation, IType type)
{
if (!IsTask(type))
return type;
if (type.TypeParameterCount == 0)
return compilation.FindType(KnownTypeCode.Void);
else
return type.TypeArguments[0];
}
/// <summary>
/// Gets whether the specified type is Task or Task<T>.
/// </summary>
public static bool IsTask(IType type)
{
ITypeDefinition def = type.GetDefinition();
if (def != null)
{
if (def.KnownTypeCode == KnownTypeCode.Task)
return true;
if (def.KnownTypeCode == KnownTypeCode.TaskOfT)
return type is ParameterizedType;
}
return false;
}
/// <summary>
/// Gets whether the specified type is a Task-like type.
/// </summary>
public static bool IsCustomTask(IType type, out IType builderType)
{
builderType = null;
ITypeDefinition def = type.GetDefinition();
if (def != null)
{
if (def.TypeParameterCount > 1)
return false;
var attribute = def.GetAttribute(KnownAttribute.AsyncMethodBuilder);
if (attribute == null || attribute.FixedArguments.Length != 1)
return false;
var arg = attribute.FixedArguments[0];
if (!arg.Type.IsKnownType(KnownTypeCode.Type))
return false;
builderType = (IType)arg.Value;
return true;
}
return false;
}
const string ns = "System.Runtime.CompilerServices";
/// <summary>
/// Gets whether the specified type is a non-generic Task-like type.
/// </summary>
/// <param name="builderTypeName">Returns the full type-name of the builder type, if successful.</param>
public static bool IsNonGenericTaskType(IType task, out FullTypeName builderTypeName)
{
if (task.IsKnownType(KnownTypeCode.Task))
{
builderTypeName = new TopLevelTypeName(ns, "AsyncTaskMethodBuilder");
return true;
}
if (IsCustomTask(task, out var builderType))
{
builderTypeName = new FullTypeName(builderType.ReflectionName);
return builderTypeName.TypeParameterCount == 0;
}
builderTypeName = default;
return false;
}
/// <summary>
/// Gets whether the specified type is a generic Task-like type.
/// </summary>
/// <param name="builderTypeName">Returns the full type-name of the builder type, if successful.</param>
public static bool IsGenericTaskType(IType task, out FullTypeName builderTypeName)
{
if (task.IsKnownType(KnownTypeCode.TaskOfT))
{
builderTypeName = new TopLevelTypeName(ns, "AsyncTaskMethodBuilder", 1);
return true;
}
if (IsCustomTask(task, out var builderType))
{
builderTypeName = new FullTypeName(builderType.ReflectionName);
return builderTypeName.TypeParameterCount == 1;
}
builderTypeName = default;
return false;
}
/// <summary>
/// Creates a task type.
/// </summary>
public static IType Create(ICompilation compilation, IType elementType)
{
if (compilation == null)
throw new ArgumentNullException(nameof(compilation));
if (elementType == null)
throw new ArgumentNullException(nameof(elementType));
if (elementType.Kind == TypeKind.Void)
return compilation.FindType(KnownTypeCode.Task);
IType taskType = compilation.FindType(KnownTypeCode.TaskOfT);
ITypeDefinition taskTypeDef = taskType.GetDefinition();
if (taskTypeDef != null)
return new ParameterizedType(taskTypeDef, new[] { elementType });
else
return taskType;
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/TaskType.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/TaskType.cs",
"repo_id": "ILSpy",
"token_count": 1636
} | 251 |
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace ICSharpCode.Decompiler.Util
{
static class CollectionExtensions
{
public static void Deconstruct<K, V>(this KeyValuePair<K, V> pair, out K key, out V value)
{
key = pair.Key;
value = pair.Value;
}
#if !NETCORE
public static IEnumerable<(A, B)> Zip<A, B>(this IEnumerable<A> input1, IEnumerable<B> input2)
{
return input1.Zip(input2, (a, b) => (a, b));
}
#endif
public static IEnumerable<(int, A, B)> ZipWithIndex<A, B>(this IEnumerable<A> input1, IEnumerable<B> input2)
{
int index = 0;
return input1.Zip(input2, (a, b) => (index++, a, b));
}
public static IEnumerable<(A?, B?)> ZipLongest<A, B>(this IEnumerable<A> input1, IEnumerable<B> input2)
{
using (var it1 = input1.GetEnumerator())
{
using (var it2 = input2.GetEnumerator())
{
bool hasElements1 = true;
bool hasElements2 = true;
while (true)
{
if (hasElements1)
hasElements1 = it1.MoveNext();
if (hasElements2)
hasElements2 = it2.MoveNext();
if (!(hasElements1 || hasElements2))
break;
yield return ((hasElements1 ? it1.Current : default), (hasElements2 ? it2.Current : default));
}
}
}
}
public static IEnumerable<T> Slice<T>(this IReadOnlyList<T> input, int offset, int length)
{
for (int i = offset; i < offset + length; i++)
{
yield return input[i];
}
}
public static IEnumerable<T> Slice<T>(this IReadOnlyList<T> input, int offset)
{
int length = input.Count;
for (int i = offset; i < length; i++)
{
yield return input[i];
}
}
#if !NETCORE
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> input)
{
return new HashSet<T>(input);
}
#endif
public static IEnumerable<T> SkipLast<T>(this IReadOnlyCollection<T> input, int count)
{
return input.Take(input.Count - count);
}
public static IEnumerable<T> TakeLast<T>(this IReadOnlyCollection<T> input, int count)
{
return input.Skip(input.Count - count);
}
public static T? PopOrDefault<T>(this Stack<T> stack)
{
if (stack.Count == 0)
return default(T);
return stack.Pop();
}
public static T? PeekOrDefault<T>(this Stack<T> stack)
{
if (stack.Count == 0)
return default(T);
return stack.Peek();
}
public static int MaxOrDefault<T>(this IEnumerable<T> input, Func<T, int> selector, int defaultValue = 0)
{
int max = defaultValue;
foreach (var element in input)
{
int value = selector(element);
if (value > max)
max = value;
}
return max;
}
public static int IndexOf<T>(this IReadOnlyList<T> collection, T value)
{
var comparer = EqualityComparer<T>.Default;
int index = 0;
foreach (T item in collection)
{
if (comparer.Equals(item, value))
{
return index;
}
index++;
}
return -1;
}
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> input)
{
foreach (T item in input)
collection.Add(item);
}
/// <summary>
/// Equivalent to <code>collection.Select(func).ToArray()</code>, but more efficient as it makes
/// use of the input collection's known size.
/// </summary>
public static U[] SelectArray<T, U>(this ICollection<T> collection, Func<T, U> func)
{
U[] result = new U[collection.Count];
int index = 0;
foreach (var element in collection)
{
result[index++] = func(element);
}
return result;
}
/// <summary>
/// Equivalent to <code>collection.Select(func).ToImmutableArray()</code>, but more efficient as it makes
/// use of the input collection's known size.
/// </summary>
public static ImmutableArray<U> SelectImmutableArray<T, U>(this IReadOnlyCollection<T> collection, Func<T, U> func)
{
var builder = ImmutableArray.CreateBuilder<U>(collection.Count);
foreach (var element in collection)
{
builder.Add(func(element));
}
return builder.MoveToImmutable();
}
/// <summary>
/// Equivalent to <code>collection.Select(func).ToArray()</code>, but more efficient as it makes
/// use of the input collection's known size.
/// </summary>
public static U[] SelectReadOnlyArray<T, U>(this IReadOnlyCollection<T> collection, Func<T, U> func)
{
U[] result = new U[collection.Count];
int index = 0;
foreach (var element in collection)
{
result[index++] = func(element);
}
return result;
}
/// <summary>
/// Equivalent to <code>collection.Select(func).ToArray()</code>, but more efficient as it makes
/// use of the input collection's known size.
/// </summary>
public static U[] SelectArray<T, U>(this List<T> collection, Func<T, U> func)
{
U[] result = new U[collection.Count];
int index = 0;
foreach (var element in collection)
{
result[index++] = func(element);
}
return result;
}
/// <summary>
/// Equivalent to <code>collection.Select(func).ToArray()</code>, but more efficient as it makes
/// use of the input collection's known size.
/// </summary>
public static U[] SelectArray<T, U>(this T[] collection, Func<T, U> func)
{
U[] result = new U[collection.Length];
int index = 0;
foreach (var element in collection)
{
result[index++] = func(element);
}
return result;
}
/// <summary>
/// Equivalent to <code>collection.Select(func).ToList()</code>, but more efficient as it makes
/// use of the input collection's known size.
/// </summary>
public static List<U> SelectList<T, U>(this ICollection<T> collection, Func<T, U> func)
{
List<U> result = new List<U>(collection.Count);
foreach (var element in collection)
{
result.Add(func(element));
}
return result;
}
public static IEnumerable<U> SelectWithIndex<T, U>(this IEnumerable<T> source, Func<int, T, U> func)
{
int index = 0;
foreach (var element in source)
yield return func(index++, element);
}
public static IEnumerable<(int, T)> WithIndex<T>(this ICollection<T> source)
{
int index = 0;
foreach (var item in source)
{
yield return (index, item);
index++;
}
}
/// <summary>
/// The merge step of merge sort.
/// </summary>
public static IEnumerable<T> Merge<T>(this IEnumerable<T> input1, IEnumerable<T> input2, Comparison<T> comparison)
{
using (var enumA = input1.GetEnumerator())
using (var enumB = input2.GetEnumerator())
{
bool moreA = enumA.MoveNext();
bool moreB = enumB.MoveNext();
while (moreA && moreB)
{
if (comparison(enumA.Current, enumB.Current) <= 0)
{
yield return enumA.Current;
moreA = enumA.MoveNext();
}
else
{
yield return enumB.Current;
moreB = enumB.MoveNext();
}
}
while (moreA)
{
yield return enumA.Current;
moreA = enumA.MoveNext();
}
while (moreB)
{
yield return enumB.Current;
moreB = enumB.MoveNext();
}
}
}
/// <summary>
/// Returns the minimum element.
/// </summary>
/// <exception cref="InvalidOperationException">The input sequence is empty</exception>
public static T MinBy<T, K>(this IEnumerable<T> source, Func<T, K> keySelector) where K : IComparable<K>
{
return source.MinBy(keySelector, Comparer<K>.Default);
}
/// <summary>
/// Returns the minimum element.
/// </summary>
/// <exception cref="InvalidOperationException">The input sequence is empty</exception>
public static T MinBy<T, K>(this IEnumerable<T> source, Func<T, K> keySelector, IComparer<K>? keyComparer)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
if (keyComparer == null)
keyComparer = Comparer<K>.Default;
using (var enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext())
throw new InvalidOperationException("Sequence contains no elements");
T minElement = enumerator.Current;
K minKey = keySelector(minElement);
while (enumerator.MoveNext())
{
T element = enumerator.Current;
K key = keySelector(element);
if (keyComparer.Compare(key, minKey) < 0)
{
minElement = element;
minKey = key;
}
}
return minElement;
}
}
/// <summary>
/// Returns the maximum element.
/// </summary>
/// <exception cref="InvalidOperationException">The input sequence is empty</exception>
public static T MaxBy<T, K>(this IEnumerable<T> source, Func<T, K> keySelector) where K : IComparable<K>
{
return source.MaxBy(keySelector, Comparer<K>.Default);
}
/// <summary>
/// Returns the maximum element.
/// </summary>
/// <exception cref="InvalidOperationException">The input sequence is empty</exception>
public static T MaxBy<T, K>(this IEnumerable<T> source, Func<T, K> keySelector, IComparer<K>? keyComparer)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
if (keyComparer == null)
keyComparer = Comparer<K>.Default;
using (var enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext())
throw new InvalidOperationException("Sequence contains no elements");
T maxElement = enumerator.Current;
K maxKey = keySelector(maxElement);
while (enumerator.MoveNext())
{
T element = enumerator.Current;
K key = keySelector(element);
if (keyComparer.Compare(key, maxKey) > 0)
{
maxElement = element;
maxKey = key;
}
}
return maxElement;
}
}
public static void RemoveLast<T>(this IList<T> list)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
list.RemoveAt(list.Count - 1);
}
public static T? OnlyOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate) => OnlyOrDefault(source.Where(predicate));
public static T? OnlyOrDefault<T>(this IEnumerable<T> source)
{
bool any = false;
T? first = default;
foreach (var t in source)
{
if (any)
return default(T);
first = t;
any = true;
}
return first;
}
#if !NETCORE
public static int EnsureCapacity<T>(this List<T> list, int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity));
if (list.Capacity < capacity)
{
const int DefaultCapacity = 4;
const int MaxLength = 0X7FFFFFC7;
int newcapacity = list.Capacity == 0 ? DefaultCapacity : 2 * list.Capacity;
if ((uint)newcapacity > MaxLength)
newcapacity = MaxLength;
if (newcapacity < capacity)
newcapacity = capacity;
list.Capacity = newcapacity;
}
return list.Capacity;
}
#endif
#region Aliases/shortcuts for Enumerable extension methods
public static bool Any<T>(this ICollection<T> list) => list.Count > 0;
public static bool Any<T>(this T[] array, Predicate<T> match) => Array.Exists(array, match);
public static bool Any<T>(this List<T> list, Predicate<T> match) => list.Exists(match);
public static bool All<T>(this T[] array, Predicate<T> match) => Array.TrueForAll(array, match);
public static bool All<T>(this List<T> list, Predicate<T> match) => list.TrueForAll(match);
public static T? FirstOrDefault<T>(this T[] array, Predicate<T> predicate) => Array.Find(array, predicate);
public static T? FirstOrDefault<T>(this List<T> list, Predicate<T> predicate) => list.Find(predicate);
public static T Last<T>(this IList<T> list) => list[list.Count - 1];
#endregion
}
}
| ILSpy/ICSharpCode.Decompiler/Util/CollectionExtensions.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Util/CollectionExtensions.cs",
"repo_id": "ILSpy",
"token_count": 4639
} | 252 |
// Copyright (c) 2018 Daniel Grunwald
// This file is based on the Mono implementation of ResXResourceWriter.
// It is modified to add support for "ResourceSerializedObject" values.
//
// 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.
//
// Copyright (c) 2004-2005 Novell, Inc.
//
// Authors:
// Duncan Mak duncan@ximian.com
// Gonzalo Paniagua Javier gonzalo@ximian.com
// Peter Bartok pbartok@novell.com
// Gary Barnett gary.barnett.mono@gmail.com
// includes code by Mike Krüger and Lluis Sanchez
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
namespace ICSharpCode.Decompiler.Util
{
#if INSIDE_SYSTEM_WEB
internal
#else
public
#endif
class ResXResourceWriter : IDisposable
{
private string filename;
private Stream stream;
private TextWriter textwriter;
private XmlTextWriter writer;
private bool written;
private string base_path;
public static readonly string BinSerializedObjectMimeType = "application/x-microsoft.net.object.binary.base64";
public static readonly string ByteArraySerializedObjectMimeType = "application/x-microsoft.net.object.bytearray.base64";
public static readonly string DefaultSerializedObjectMimeType = BinSerializedObjectMimeType;
public static readonly string ResMimeType = "text/microsoft-resx";
public static readonly string SoapSerializedObjectMimeType = "application/x-microsoft.net.object.soap.base64";
public static readonly string Version = "2.0";
public ResXResourceWriter(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite)
throw new ArgumentException("stream is not writable.", nameof(stream));
this.stream = stream;
}
public ResXResourceWriter(TextWriter textWriter)
{
if (textWriter == null)
throw new ArgumentNullException(nameof(textWriter));
this.textwriter = textWriter;
}
public ResXResourceWriter(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
this.filename = fileName;
}
~ResXResourceWriter()
{
Dispose(false);
}
const string WinFormsAssemblyName = ", System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
const string MSCorLibAssemblyName = ", mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
const string ResXNullRefTypeName = "System.Resources.ResXNullRef" + WinFormsAssemblyName;
void InitWriter()
{
if (filename != null)
stream = File.Open(filename, FileMode.Create);
if (textwriter == null)
textwriter = new StreamWriter(stream, Encoding.UTF8);
writer = new XmlTextWriter(textwriter);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteRaw(schema);
WriteHeader("resmimetype", "text/microsoft-resx");
WriteHeader("version", "1.3");
WriteHeader("reader", "System.Resources.ResXResourceReader" + WinFormsAssemblyName);
WriteHeader("writer", "System.Resources.ResXResourceWriter" + WinFormsAssemblyName);
}
void WriteHeader(string name, string value)
{
writer.WriteStartElement("resheader");
writer.WriteAttributeString("name", name);
writer.WriteStartElement("value");
writer.WriteString(value);
writer.WriteEndElement();
writer.WriteEndElement();
}
void WriteNiceBase64(byte[] value, int offset, int length)
{
string base64 = Convert.ToBase64String(
value, offset, length,
Base64FormattingOptions.InsertLineBreaks);
writer.WriteString(base64);
}
void WriteBytes(string name, string type, byte[] value, int offset, int length, string comment)
{
writer.WriteStartElement("data");
writer.WriteAttributeString("name", name);
if (type != null)
{
writer.WriteAttributeString("type", type);
// byte[] should never get a mimetype, otherwise MS.NET won't be able
// to parse the data.
if (type != "System.Byte[]" + MSCorLibAssemblyName)
writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType);
writer.WriteStartElement("value");
WriteNiceBase64(value, offset, length);
}
else
{
writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType);
writer.WriteStartElement("value");
writer.WriteBase64(value, offset, length);
}
writer.WriteEndElement();
if (!string.IsNullOrEmpty(comment))
{
writer.WriteStartElement("comment");
writer.WriteString(comment);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
void WriteString(string name, string value, string type, string comment)
{
writer.WriteStartElement("data");
writer.WriteAttributeString("name", name);
if (type != null)
{
writer.WriteAttributeString("type", type);
}
else
{
writer.WriteAttributeString("xml:space", "preserve");
}
writer.WriteStartElement("value");
writer.WriteString(value);
writer.WriteEndElement();
if (!string.IsNullOrEmpty(comment))
{
writer.WriteStartElement("comment");
writer.WriteString(comment);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteWhitespace("\n ");
}
public void AddResource(string name, byte[] value)
{
AddResource(name, value, string.Empty);
}
public void AddResource(string name, object value)
{
AddResource(name, value, string.Empty);
}
private void AddResource(string name, object value, string comment)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (written)
throw new InvalidOperationException("The resource is already generated.");
if (writer == null)
InitWriter();
switch (value)
{
case null:
// nulls written as ResXNullRef
WriteString(name, "", ResXNullRefTypeName, comment);
break;
case string s:
WriteString(name, s, null, comment);
break;
case bool bo:
WriteString(name, bo.ToString(CultureInfo.InvariantCulture), "System.Boolean" + MSCorLibAssemblyName, comment);
break;
case char ch:
WriteString(name, ch.ToString(CultureInfo.InvariantCulture), "System.Char" + MSCorLibAssemblyName, comment);
break;
case sbyte sb:
WriteString(name, sb.ToString(CultureInfo.InvariantCulture), "System.SByte" + MSCorLibAssemblyName, comment);
break;
case byte b:
WriteString(name, b.ToString(CultureInfo.InvariantCulture), "System.Byte" + MSCorLibAssemblyName, comment);
break;
case short sh:
WriteString(name, sh.ToString(CultureInfo.InvariantCulture), "System.Int16" + MSCorLibAssemblyName, comment);
break;
case ushort ush:
WriteString(name, ush.ToString(CultureInfo.InvariantCulture), "System.UInt16" + MSCorLibAssemblyName, comment);
break;
case int i:
WriteString(name, i.ToString(CultureInfo.InvariantCulture), "System.Int32" + MSCorLibAssemblyName, comment);
break;
case uint u:
WriteString(name, u.ToString(CultureInfo.InvariantCulture), "System.UInt32" + MSCorLibAssemblyName, comment);
break;
case long l:
WriteString(name, l.ToString(CultureInfo.InvariantCulture), "System.Int64" + MSCorLibAssemblyName, comment);
break;
case ulong ul:
WriteString(name, ul.ToString(CultureInfo.InvariantCulture), "System.UInt64" + MSCorLibAssemblyName, comment);
break;
case float f:
WriteString(name, f.ToString(CultureInfo.InvariantCulture), "System.Single" + MSCorLibAssemblyName, comment);
break;
case double d:
WriteString(name, d.ToString(CultureInfo.InvariantCulture), "System.Double" + MSCorLibAssemblyName, comment);
break;
case decimal m:
WriteString(name, m.ToString(CultureInfo.InvariantCulture), "System.Decimal" + MSCorLibAssemblyName, comment);
break;
case DateTime dt:
WriteString(name, dt.ToString(CultureInfo.InvariantCulture), "System.DateTime" + MSCorLibAssemblyName, comment);
break;
case TimeSpan sp:
WriteString(name, sp.ToString(), "System.TimeSpan" + MSCorLibAssemblyName, comment);
break;
case byte[] array:
WriteBytes(name, "System.Byte[]" + MSCorLibAssemblyName, array, 0, array.Length, comment);
break;
case MemoryStream memoryStream:
var arr = memoryStream.ToArray();
WriteBytes(name, null, arr, 0, arr.Length, comment);
break;
case ResourceSerializedObject rso:
var bytes = rso.GetBytes();
WriteBytes(name, null, bytes, 0, bytes.Length, comment);
break;
default:
throw new NotSupportedException($"Value '{value}' of type {value.GetType().FullName} is not supported by this version of ResXResourceWriter. Use byte arrays or streams instead.");
}
}
public void AddResource(string name, string value)
{
AddResource(name, value, string.Empty);
}
public void Close()
{
if (writer != null)
{
if (!written)
{
Generate();
}
writer.Close();
stream = null;
filename = null;
textwriter = null;
}
}
public virtual void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Generate()
{
if (written)
throw new InvalidOperationException("The resource is already generated.");
written = true;
writer.WriteEndElement();
writer.Flush();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
Close();
}
static readonly string schema = @"
<xsd:schema id='root' xmlns='' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
<xsd:element name='root' msdata:IsDataSet='true'>
<xsd:complexType>
<xsd:choice maxOccurs='unbounded'>
<xsd:element name='data'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />
<xsd:element name='comment' type='xsd:string' minOccurs='0' msdata:Ordinal='2' />
</xsd:sequence>
<xsd:attribute name='name' type='xsd:string' msdata:Ordinal='1' />
<xsd:attribute name='type' type='xsd:string' msdata:Ordinal='3' />
<xsd:attribute name='mimetype' type='xsd:string' msdata:Ordinal='4' />
</xsd:complexType>
</xsd:element>
<xsd:element name='resheader'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />
</xsd:sequence>
<xsd:attribute name='name' type='xsd:string' use='required' />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
".Replace("'", "\"").Replace("\t", " ");
public string BasePath {
get { return base_path; }
set { base_path = value; }
}
}
}
| ILSpy/ICSharpCode.Decompiler/Util/ResXResourceWriter.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Util/ResXResourceWriter.cs",
"repo_id": "ILSpy",
"token_count": 4402
} | 253 |
// 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.Concurrent;
using System.IO;
namespace ICSharpCode.ILSpyX.Search
{
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.ILSpyX.Abstractions;
public abstract class AbstractEntitySearchStrategy : AbstractSearchStrategy
{
protected readonly ILanguage language;
protected readonly ApiVisibility apiVisibility;
protected AbstractEntitySearchStrategy(ILanguage language, ApiVisibility apiVisibility,
SearchRequest searchRequest, IProducerConsumerCollection<SearchResult> resultQueue)
: base(searchRequest, resultQueue)
{
this.language = language;
this.apiVisibility = apiVisibility;
}
protected bool CheckVisibility(IEntity? entity)
{
if (apiVisibility == ApiVisibility.All)
return true;
while (entity != null)
{
if (apiVisibility == ApiVisibility.PublicOnly)
{
if (!(entity.Accessibility == Accessibility.Public ||
entity.Accessibility == Accessibility.Protected ||
entity.Accessibility == Accessibility.ProtectedOrInternal))
return false;
}
else if (apiVisibility == ApiVisibility.PublicAndInternal)
{
if (!language.ShowMember(entity))
return false;
}
entity = entity.DeclaringTypeDefinition;
}
return true;
}
protected bool IsInNamespaceOrAssembly(IEntity entity)
{
if (searchRequest.InAssembly != null)
{
if (entity.ParentModule?.PEFile == null ||
!(Path.GetFileName(entity.ParentModule.PEFile.FileName).Contains(searchRequest.InAssembly, StringComparison.OrdinalIgnoreCase)
|| entity.ParentModule.FullAssemblyName.Contains(searchRequest.InAssembly, StringComparison.OrdinalIgnoreCase)))
{
return false;
}
}
if (searchRequest.InNamespace != null)
{
if (searchRequest.InNamespace.Length == 0)
{
return entity.Namespace.Length == 0;
}
else if (!entity.Namespace.Contains(searchRequest.InNamespace, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return true;
}
protected void OnFoundResult(IEntity entity)
{
OnFoundResult(searchRequest.SearchResultFactory.Create(entity));
}
}
}
| ILSpy/ICSharpCode.ILSpyX/Search/AbstractEntitySearchStrategy.cs/0 | {
"file_path": "ILSpy/ICSharpCode.ILSpyX/Search/AbstractEntitySearchStrategy.cs",
"repo_id": "ILSpy",
"token_count": 1077
} | 254 |
// PkgCmdID.cs
// MUST match PkgCmdID.h
namespace ICSharpCode.ILSpy.AddIn
{
static class PkgCmdIDList
{
public const uint cmdidOpenILSpy = 0x100;
public const uint cmdidOpenReferenceInILSpy = 0x200;
public const uint cmdidOpenProjectOutputInILSpy = 0x300;
public const uint cmdidOpenCodeItemInILSpy = 0x0400;
};
} | ILSpy/ILSpy.AddIn.Shared/PkgCmdID.cs/0 | {
"file_path": "ILSpy/ILSpy.AddIn.Shared/PkgCmdID.cs",
"repo_id": "ILSpy",
"token_count": 130
} | 255 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Key="grid" x:XmlAttributeProperties.XmlSpace="preserve" />
</ResourceDictionary> | ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue2052.xaml/0 | {
"file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue2052.xaml",
"repo_id": "ILSpy",
"token_count": 86
} | 256 |
using System;
using System.IO;
using System.Linq;
using System.Text;
using WixSharp;
using WixSharp.Controls;
namespace ILSpy.Installer
{
internal class Builder
{
static public void Main()
{
Compiler.AutoGeneration.IgnoreWildCardEmptyDirectories = true;
#if DEBUG
var buildConfiguration = "Debug";
#else
var buildConfiguration = "Release";
#endif
#if ARM64
var buildPlatform = "arm64";
#else
var buildPlatform = "x64";
#endif
var buildOutputDir = $@"ILSpy\bin\{buildConfiguration}\net8.0-windows\win-{buildPlatform}\publish\fwdependent";
var project = new Project("ILSpy",
new InstallDir(@"%LocalAppData%\Programs\ILSpy",
new DirFiles(Path.Combine(buildOutputDir, "*.dll")),
new DirFiles(Path.Combine(buildOutputDir, "*.exe")),
new DirFiles(Path.Combine(buildOutputDir, "*.config")),
new DirFiles(Path.Combine(buildOutputDir, "*.json")),
new Files(Path.Combine(buildOutputDir, "ILSpy.resources.dll")),
new Files(Path.Combine(buildOutputDir, "ILSpy.ReadyToRun.Plugin.resources.dll"))));
#if ARM64
project.Platform = Platform.arm64;
#else
project.Platform = Platform.x64;
#endif
project.GUID = new Guid("a12fdab1-731b-4a98-9749-d481ce8692ab");
project.Version = AppPackage.Version;
project.SourceBaseDir = Path.GetDirectoryName(Environment.CurrentDirectory);
project.InstallScope = InstallScope.perUser;
project.InstallPrivileges = InstallPrivileges.limited;
project.ControlPanelInfo.ProductIcon = @"..\ILSpy\Images\ILSpy.ico";
project.ControlPanelInfo.Manufacturer = "ICSharpCode Team";
project.LocalizationFile = Path.Combine(Environment.CurrentDirectory, "winui.wxl");
project.Encoding = Encoding.UTF8;
project.MajorUpgrade = new MajorUpgrade {
Schedule = UpgradeSchedule.afterInstallInitialize,
AllowSameVersionUpgrades = true,
DowngradeErrorMessage = "A newer release of ILSpy is already installed on this system. Please uninstall it first to continue."
};
project.UI = WUI.WixUI_InstallDir;
project.CustomUI =
new DialogSequence()
.On(NativeDialogs.WelcomeDlg, Buttons.Next,
new ShowDialog(NativeDialogs.VerifyReadyDlg))
.On(NativeDialogs.VerifyReadyDlg, Buttons.Back,
new ShowDialog(NativeDialogs.WelcomeDlg));
project.ResolveWildCards().FindFile(f => f.Name.EndsWith("ILSpy.exe")).First()
.Shortcuts = new[] {
new FileShortcut("ILSpy", @"%ProgramMenu%")
};
Compiler.WixLocation = GetWixBinLocationForPackage();
Compiler.BuildMsi(project, Path.Combine(Environment.CurrentDirectory, "wix", $"ILSpy-{AppPackage.Version}-{buildPlatform}.msi"));
}
// Copied from https://github.com/oleg-shilo/wixsharp/blob/c4f8615ce8e47c7162edb30656669d0d326f79ff/Source/src/WixSharp/Utilities/WixBinLocator.cs#L117
private static string GetWixBinLocationForPackage()
{
//The global packages may be redirected with environment variable
//https://docs.microsoft.com/en-us/nuget/consume-packages/managing-the-global-packages-and-cache-folders
string wixBinPackageDir;
var nugetPackagesEnvironmentVariable = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
if (nugetPackagesEnvironmentVariable.IsNotEmpty() && Directory.Exists(nugetPackagesEnvironmentVariable))
{
wixBinPackageDir = Path.Combine(nugetPackagesEnvironmentVariable, "wixsharp.wix.bin");
}
else
{
wixBinPackageDir = @"%userprofile%\.nuget\packages\wixsharp.wix.bin".ExpandEnvVars();
}
if (Directory.Exists(wixBinPackageDir))
{
Version greatestWixBinVersion = System.IO.Directory.GetDirectories(wixBinPackageDir)
.Select(dirPath => new Version(dirPath.PathGetFileName()))
.OrderDescending()
.FirstOrDefault();
if (greatestWixBinVersion != null)
{
return wixBinPackageDir.PathJoin(greatestWixBinVersion.ToString(), @"tools\bin");
}
}
return "";
}
}
}
| ILSpy/ILSpy.Installer/setup.cs/0 | {
"file_path": "ILSpy/ILSpy.Installer/setup.cs",
"repo_id": "ILSpy",
"token_count": 1556
} | 257 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ICSharpCode.ILSpy.Tests.Analyzers.TestCases.Main
{
class MainAssembly
{
public string UsesSystemStringEmpty()
{
return string.Empty;
}
public int UsesInt32()
{
return int.Parse("1234");
}
}
}
| ILSpy/ILSpy.Tests/Analyzers/TestCases/MainAssembly.cs/0 | {
"file_path": "ILSpy/ILSpy.Tests/Analyzers/TestCases/MainAssembly.cs",
"repo_id": "ILSpy",
"token_count": 134
} | 258 |
// 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.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.ILSpy.Analyzers.Builtin
{
[ExportAnalyzer(Header = "Applied To", Order = 10)]
class AttributeAppliedToAnalyzer : IAnalyzer
{
public IEnumerable<ISymbol> Analyze(ISymbol analyzedSymbol, AnalyzerContext context)
{
if (!(analyzedSymbol is ITypeDefinition attributeType))
return Empty<ISymbol>.Array;
var scope = context.GetScopeOf(attributeType);
// TODO: DeclSecurity attributes are not supported.
if (!IsBuiltinAttribute(attributeType, out var knownAttribute))
{
return HandleCustomAttribute(attributeType, scope, context.CancellationToken).Distinct();
}
else
{
return HandleBuiltinAttribute(knownAttribute, scope, context.CancellationToken).SelectMany(s => s);
}
}
bool IsBuiltinAttribute(ITypeDefinition attributeType, out KnownAttribute knownAttribute)
{
knownAttribute = attributeType.IsBuiltinAttribute();
return !knownAttribute.IsCustomAttribute();
}
IEnumerable<IEnumerable<ISymbol>> HandleBuiltinAttribute(KnownAttribute attribute, AnalyzerScope scope, CancellationToken ct)
{
IEnumerable<ISymbol> ScanTypes(DecompilerTypeSystem ts)
{
return ts.MainModule.TypeDefinitions
.Where(t => t.HasAttribute(attribute));
}
IEnumerable<ISymbol> ScanMethods(DecompilerTypeSystem ts)
{
return ts.MainModule.TypeDefinitions
.SelectMany(t => t.Members.OfType<IMethod>())
.Where(m => m.HasAttribute(attribute))
.Select(m => m.AccessorOwner ?? m);
}
IEnumerable<ISymbol> ScanFields(DecompilerTypeSystem ts)
{
return ts.MainModule.TypeDefinitions
.SelectMany(t => t.Fields)
.Where(f => f.HasAttribute(attribute));
}
IEnumerable<ISymbol> ScanProperties(DecompilerTypeSystem ts)
{
return ts.MainModule.TypeDefinitions
.SelectMany(t => t.Properties)
.Where(p => p.HasAttribute(attribute));
}
IEnumerable<ISymbol> ScanParameters(DecompilerTypeSystem ts)
{
return ts.MainModule.TypeDefinitions
.SelectMany(t => t.Members.OfType<IMethod>())
.Where(m => m.Parameters.Any(p => p.HasAttribute(attribute)))
.Select(m => m.AccessorOwner ?? m);
}
foreach (Decompiler.Metadata.PEFile module in scope.GetModulesInScope(ct))
{
var ts = scope.ConstructTypeSystem(module);
ct.ThrowIfCancellationRequested();
switch (attribute)
{
case KnownAttribute.Serializable:
case KnownAttribute.ComImport:
case KnownAttribute.StructLayout:
yield return ScanTypes(ts);
break;
case KnownAttribute.DllImport:
case KnownAttribute.PreserveSig:
case KnownAttribute.MethodImpl:
yield return ScanMethods(ts);
break;
case KnownAttribute.FieldOffset:
case KnownAttribute.NonSerialized:
yield return ScanFields(ts);
break;
case KnownAttribute.MarshalAs:
yield return ScanFields(ts);
yield return ScanParameters(ts);
goto case KnownAttribute.Out;
case KnownAttribute.Optional:
case KnownAttribute.In:
case KnownAttribute.Out:
yield return ScanParameters(ts);
break;
case KnownAttribute.IndexerName:
yield return ScanProperties(ts);
break;
}
}
}
IEnumerable<ISymbol> HandleCustomAttribute(ITypeDefinition attributeType, AnalyzerScope scope, CancellationToken ct)
{
var genericContext = new Decompiler.TypeSystem.GenericContext(); // type arguments do not matter for this analyzer.
foreach (var module in scope.GetModulesInScope(ct))
{
var ts = scope.ConstructTypeSystem(module);
ct.ThrowIfCancellationRequested();
var decoder = new FindTypeDecoder(ts.MainModule, attributeType);
var referencedParameters = new HashSet<ParameterHandle>();
foreach (var h in module.Metadata.CustomAttributes)
{
var customAttribute = module.Metadata.GetCustomAttribute(h);
if (IsCustomAttributeOfType(customAttribute.Constructor, module.Metadata, decoder))
{
if (customAttribute.Parent.Kind == HandleKind.Parameter)
{
referencedParameters.Add((ParameterHandle)customAttribute.Parent);
}
else
{
var parent = AnalyzerHelpers.GetParentEntity(ts, customAttribute);
if (parent != null)
yield return parent;
}
}
}
if (referencedParameters.Count > 0)
{
foreach (var h in module.Metadata.MethodDefinitions)
{
var md = module.Metadata.GetMethodDefinition(h);
foreach (var p in md.GetParameters())
{
if (referencedParameters.Contains(p))
{
var method = ts.MainModule.ResolveMethod(h, genericContext);
if (method != null)
{
if (method.IsAccessor)
yield return method.AccessorOwner;
else
yield return method;
}
break;
}
}
}
}
}
}
internal static bool IsCustomAttributeOfType(EntityHandle customAttributeCtor, MetadataReader metadata, FindTypeDecoder decoder)
{
var declaringAttributeType = customAttributeCtor.GetDeclaringType(metadata);
return decoder.GetTypeFromEntity(metadata, declaringAttributeType);
}
public bool Show(ISymbol symbol)
{
return symbol is ITypeDefinition type && type.GetNonInterfaceBaseTypes()
.Any(t => t.IsKnownType(KnownTypeCode.Attribute));
}
}
}
| ILSpy/ILSpy/Analyzers/Builtin/AttributeAppliedToAnalyzer.cs/0 | {
"file_path": "ILSpy/ILSpy/Analyzers/Builtin/AttributeAppliedToAnalyzer.cs",
"repo_id": "ILSpy",
"token_count": 2447
} | 259 |
// Copyright (c) 2018 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Disassembler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.ILSpy.Analyzers.Builtin
{
/// <summary>
/// Shows entities that use a type.
/// </summary>
[ExportAnalyzer(Header = "Used By", Order = 30)]
class TypeUsedByAnalyzer : IAnalyzer
{
public IEnumerable<ISymbol> Analyze(ISymbol analyzedSymbol, AnalyzerContext context)
{
Debug.Assert(analyzedSymbol is ITypeDefinition);
var analyzedType = (ITypeDefinition)analyzedSymbol;
var scope = context.GetScopeOf(analyzedType);
context.SortResults = true;
return scope.GetModulesInScope(context.CancellationToken)
.AsParallel().AsOrdered()
.SelectMany(AnalyzeModuleAndFilter);
IEnumerable<ISymbol> AnalyzeModuleAndFilter(PEFile module)
{
return AnalyzeModule(analyzedType, scope, module)
.Distinct()
.Where(s => !analyzedType.Equals((s as IEntity)?.DeclaringTypeDefinition));
}
}
static IEnumerable<ISymbol> AnalyzeModule(ITypeDefinition analyzedType, AnalyzerScope scope, PEFile module)
{
var metadata = module.Metadata;
var typeSystem = scope.ConstructTypeSystem(module);
var decoder = new FindTypeDecoder(typeSystem.MainModule, analyzedType);
//// resolve type refs
//int rowCount = metadata.GetTableRowCount(TableIndex.TypeRef);
//BitSet typeReferences = new BitSet(rowCount);
//for (int row = 0; row < rowCount; row++)
//{
// var h = MetadataTokens.TypeReferenceHandle(row + 1);
// typeReferences[row] = decoder.GetTypeFromReference(metadata, h, 0);
//}
//// resolve type specs
//rowCount = metadata.GetTableRowCount(TableIndex.TypeSpec);
//BitSet typeSpecifications = new BitSet(rowCount);
//for (int row = 0; row < rowCount; row++)
//{
// var h = MetadataTokens.TypeSpecificationHandle(row + 1);
// typeSpecifications[row] = decoder.GetTypeFromSpecification(metadata, default, h, 0);
//}
foreach (ISymbol result in FindUsesInAttributes(typeSystem, metadata, decoder, analyzedType))
yield return result;
foreach (var h in metadata.TypeDefinitions)
{
var td = metadata.GetTypeDefinition(h);
bool found = decoder.GetTypeFromEntity(metadata, td.GetBaseTypeOrNil());
foreach (var ih in td.GetInterfaceImplementations())
{
var ii = metadata.GetInterfaceImplementation(ih);
found |= decoder.GetTypeFromEntity(metadata, ii.Interface);
}
found |= FindUsesInGenericConstraints(metadata, td.GetGenericParameters(), decoder);
if (found)
yield return typeSystem.MainModule.GetDefinition(h);
}
foreach (var h in metadata.MethodDefinitions)
{
var md = metadata.GetMethodDefinition(h);
var msig = md.DecodeSignature(decoder, default);
bool found = FindTypeDecoder.AnyInMethodSignature(msig);
found |= FindUsesInGenericConstraints(metadata, md.GetGenericParameters(), decoder);
if (found || ScanMethodBody(analyzedType, module, md, decoder))
{
var method = typeSystem.MainModule.GetDefinition(h);
yield return method?.AccessorOwner ?? method;
}
}
foreach (var h in metadata.FieldDefinitions)
{
var fd = metadata.GetFieldDefinition(h);
if (fd.DecodeSignature(decoder, default))
yield return typeSystem.MainModule.GetDefinition(h);
}
foreach (var h in metadata.PropertyDefinitions)
{
var pd = metadata.GetPropertyDefinition(h);
var psig = pd.DecodeSignature(decoder, default);
if (FindTypeDecoder.AnyInMethodSignature(psig))
yield return typeSystem.MainModule.GetDefinition(h);
}
foreach (var h in metadata.EventDefinitions)
{
var ed = metadata.GetEventDefinition(h);
if (decoder.GetTypeFromEntity(metadata, ed.Type))
yield return typeSystem.MainModule.GetDefinition(h);
}
}
static bool FindUsesInGenericConstraints(MetadataReader metadata, GenericParameterHandleCollection collection, FindTypeDecoder decoder)
{
foreach (var h in collection)
{
var gp = metadata.GetGenericParameter(h);
foreach (var hc in gp.GetConstraints())
{
var gc = metadata.GetGenericParameterConstraint(hc);
if (decoder.GetTypeFromEntity(metadata, gc.Type))
return true;
}
}
return false;
}
static IEnumerable<ISymbol> FindUsesInAttributes(DecompilerTypeSystem typeSystem, MetadataReader metadata, FindTypeDecoder decoder, ITypeDefinition analyzedType)
{
var attrDecoder = new FindTypeInAttributeDecoder(typeSystem.MainModule, analyzedType);
var referencedParameters = new HashSet<ParameterHandle>();
foreach (var h in metadata.CustomAttributes)
{
var customAttribute = metadata.GetCustomAttribute(h);
CustomAttributeValue<TokenSearchResult> value;
try
{
value = customAttribute.DecodeValue(attrDecoder);
}
catch (EnumUnderlyingTypeResolveException)
{
continue;
}
if (AttributeAppliedToAnalyzer.IsCustomAttributeOfType(customAttribute.Constructor, metadata, decoder)
|| AnalyzeCustomAttributeValue(value))
{
if (customAttribute.Parent.Kind == HandleKind.Parameter)
{
referencedParameters.Add((ParameterHandle)customAttribute.Parent);
}
else
{
var parent = AnalyzerHelpers.GetParentEntity(typeSystem, customAttribute);
if (parent != null)
yield return parent;
}
}
}
if (referencedParameters.Count > 0)
{
foreach (var h in metadata.MethodDefinitions)
{
var md = metadata.GetMethodDefinition(h);
foreach (var p in md.GetParameters())
{
if (referencedParameters.Contains(p))
{
var method = typeSystem.MainModule.ResolveMethod(h, default);
if (method != null)
{
if (method.IsAccessor)
yield return method.AccessorOwner;
else
yield return method;
}
break;
}
}
}
}
}
private static bool AnalyzeCustomAttributeValue(CustomAttributeValue<TokenSearchResult> attribute)
{
foreach (var fa in attribute.FixedArguments)
{
if (CheckAttributeValue(fa.Value))
return true;
}
foreach (var na in attribute.NamedArguments)
{
if (CheckAttributeValue(na.Value))
return true;
}
return false;
bool CheckAttributeValue(object value)
{
if (value is TokenSearchResult typeofType)
{
if ((typeofType & TokenSearchResult.Found) != 0)
return true;
}
else if (value is ImmutableArray<CustomAttributeTypedArgument<IType>> arr)
{
foreach (var element in arr)
{
if (CheckAttributeValue(element.Value))
return true;
}
}
return false;
}
}
static bool ScanMethodBody(ITypeDefinition analyzedType, PEFile module, in MethodDefinition md, FindTypeDecoder decoder)
{
if (!md.HasBody())
return false;
var methodBody = module.Reader.GetMethodBody(md.RelativeVirtualAddress);
var metadata = module.Metadata;
if (!methodBody.LocalSignature.IsNil)
{
try
{
var ss = metadata.GetStandaloneSignature(methodBody.LocalSignature);
if (HandleStandaloneSignature(ss))
{
return true;
}
}
catch (BadImageFormatException)
{
// Issue #2197: ignore invalid local signatures
}
}
var blob = methodBody.GetILReader();
while (blob.RemainingBytes > 0)
{
var opCode = blob.DecodeOpCode();
switch (opCode.GetOperandType())
{
case OperandType.Field:
case OperandType.Method:
case OperandType.Sig:
case OperandType.Tok:
case OperandType.Type:
if (HandleMember(MetadataTokenHelpers.EntityHandleOrNil(blob.ReadInt32())))
return true;
break;
default:
blob.SkipOperand(opCode);
break;
}
}
return false;
bool HandleMember(EntityHandle member)
{
if (member.IsNil)
return false;
switch (member.Kind)
{
case HandleKind.TypeReference:
return decoder.GetTypeFromReference(metadata, (TypeReferenceHandle)member, 0);
case HandleKind.TypeSpecification:
return decoder.GetTypeFromSpecification(metadata, default, (TypeSpecificationHandle)member, 0);
case HandleKind.TypeDefinition:
return decoder.GetTypeFromDefinition(metadata, (TypeDefinitionHandle)member, 0);
case HandleKind.FieldDefinition:
var fd = metadata.GetFieldDefinition((FieldDefinitionHandle)member);
return HandleMember(fd.GetDeclaringType()) || fd.DecodeSignature(decoder, default);
case HandleKind.MethodDefinition:
var md = metadata.GetMethodDefinition((MethodDefinitionHandle)member);
if (HandleMember(md.GetDeclaringType()))
return true;
var msig = md.DecodeSignature(decoder, default);
if (msig.ReturnType)
return true;
foreach (var t in msig.ParameterTypes)
{
if (t)
return true;
}
break;
case HandleKind.MemberReference:
var mr = metadata.GetMemberReference((MemberReferenceHandle)member);
if (HandleMember(mr.Parent))
return true;
switch (mr.GetKind())
{
case MemberReferenceKind.Method:
msig = mr.DecodeMethodSignature(decoder, default);
if (msig.ReturnType)
return true;
foreach (var t in msig.ParameterTypes)
{
if (t)
return true;
}
break;
case MemberReferenceKind.Field:
return mr.DecodeFieldSignature(decoder, default);
}
break;
case HandleKind.MethodSpecification:
var ms = metadata.GetMethodSpecification((MethodSpecificationHandle)member);
if (HandleMember(ms.Method))
return true;
var mssig = ms.DecodeSignature(decoder, default);
foreach (var t in mssig)
{
if (t)
return true;
}
break;
case HandleKind.StandaloneSignature:
var ss = metadata.GetStandaloneSignature((StandaloneSignatureHandle)member);
return HandleStandaloneSignature(ss);
}
return false;
}
bool HandleStandaloneSignature(StandaloneSignature signature)
{
switch (signature.GetKind())
{
case StandaloneSignatureKind.Method:
var msig = signature.DecodeMethodSignature(decoder, default);
if (msig.ReturnType)
return true;
foreach (var t in msig.ParameterTypes)
{
if (t)
return true;
}
break;
case StandaloneSignatureKind.LocalVariables:
var sig = signature.DecodeLocalSignature(decoder, default);
foreach (var t in sig)
{
if (t)
return true;
}
break;
}
return false;
}
}
public bool Show(ISymbol symbol) => symbol is ITypeDefinition;
}
class TypeDefinitionUsedVisitor : TypeVisitor
{
public readonly ITypeDefinition TypeDefinition;
public bool Found { get; set; }
readonly bool topLevelOnly;
public TypeDefinitionUsedVisitor(ITypeDefinition definition, bool topLevelOnly)
{
this.TypeDefinition = definition;
this.topLevelOnly = topLevelOnly;
}
public override IType VisitTypeDefinition(ITypeDefinition type)
{
Found |= TypeDefinition.MetadataToken == type.MetadataToken
&& TypeDefinition.ParentModule.PEFile == type.ParentModule.PEFile;
return base.VisitTypeDefinition(type);
}
public override IType VisitParameterizedType(ParameterizedType type)
{
if (topLevelOnly)
return type.GenericType.AcceptVisitor(this);
return base.VisitParameterizedType(type);
}
}
}
| ILSpy/ILSpy/Analyzers/Builtin/TypeUsedByAnalyzer.cs/0 | {
"file_path": "ILSpy/ILSpy/Analyzers/Builtin/TypeUsedByAnalyzer.cs",
"repo_id": "ILSpy",
"token_count": 4924
} | 260 |
// 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;
namespace ICSharpCode.ILSpy
{
sealed class CommandLineArguments
{
// see /doc/Command Line.txt for details
public List<string> AssembliesToLoad = new List<string>();
public bool? SingleInstance;
public string NavigateTo;
public string Search;
public string Language;
public bool NoActivate;
public string ConfigFile;
public CommandLineArguments(IEnumerable<string> arguments)
{
foreach (string arg in arguments)
{
if (arg.Length == 0)
continue;
if (arg[0] == '/')
{
if (arg.Equals("/singleInstance", StringComparison.OrdinalIgnoreCase))
this.SingleInstance = true;
else if (arg.Equals("/separate", StringComparison.OrdinalIgnoreCase))
this.SingleInstance = false;
else if (arg.StartsWith("/navigateTo:", StringComparison.OrdinalIgnoreCase))
this.NavigateTo = arg.Substring("/navigateTo:".Length);
else if (arg.StartsWith("/search:", StringComparison.OrdinalIgnoreCase))
this.Search = arg.Substring("/search:".Length);
else if (arg.StartsWith("/language:", StringComparison.OrdinalIgnoreCase))
this.Language = arg.Substring("/language:".Length);
else if (arg.Equals("/noActivate", StringComparison.OrdinalIgnoreCase))
this.NoActivate = true;
else if (arg.StartsWith("/config:", StringComparison.OrdinalIgnoreCase))
this.ConfigFile = arg.Substring("/config:".Length);
}
else
{
this.AssembliesToLoad.Add(arg);
}
}
}
}
}
| ILSpy/ILSpy/CommandLineArguments.cs/0 | {
"file_path": "ILSpy/ILSpy/CommandLineArguments.cs",
"repo_id": "ILSpy",
"token_count": 886
} | 261 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.TreeView;
namespace ICSharpCode.ILSpy
{
public interface IProtocolHandler
{
ILSpyTreeNode Resolve(string protocol, PEFile module, Handle handle, out bool newTabPage);
}
}
| ILSpy/ILSpy/Commands/IProtocolHandler.cs/0 | {
"file_path": "ILSpy/ILSpy/Commands/IProtocolHandler.cs",
"repo_id": "ILSpy",
"token_count": 142
} | 262 |
// 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.ComponentModel;
using System.Windows.Input;
namespace ICSharpCode.ILSpy
{
public abstract class SimpleCommand : ICommand
{
public event EventHandler CanExecuteChanged {
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public abstract void Execute(object parameter);
public virtual bool CanExecute(object parameter)
{
return true;
}
}
public abstract class ToggleableCommand : ICommand, INotifyPropertyChanged
{
private bool isChecked;
public event EventHandler CanExecuteChanged {
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public event PropertyChangedEventHandler PropertyChanged;
void ICommand.Execute(object parameter)
{
IsChecked = Execute(parameter);
}
public bool IsChecked {
get => isChecked;
set {
if (isChecked != value)
{
isChecked = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsChecked)));
}
}
}
public abstract bool Execute(object parameter);
public virtual bool CanExecute(object parameter)
{
return true;
}
}
}
| ILSpy/ILSpy/Commands/SimpleCommand.cs/0 | {
"file_path": "ILSpy/ILSpy/Commands/SimpleCommand.cs",
"repo_id": "ILSpy",
"token_count": 698
} | 263 |
// 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.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace ICSharpCode.ILSpy.Controls
{
/// <summary>
/// Allows to automatically sort a grid view.
/// </summary>
public class SortableGridViewColumn : GridViewColumn
{
// This class was copied from ICSharpCode.Core.Presentation.
static readonly ComponentResourceKey headerTemplateKey = new ComponentResourceKey(typeof(SortableGridViewColumn), "ColumnHeaderTemplate");
public SortableGridViewColumn()
{
this.SetValueToExtension(HeaderTemplateProperty, new DynamicResourceExtension(headerTemplateKey));
}
string sortBy;
public string SortBy {
get { return sortBy; }
set {
if (sortBy != value)
{
sortBy = value;
OnPropertyChanged(new PropertyChangedEventArgs("SortBy"));
}
}
}
#region SortDirection property
public static readonly DependencyProperty SortDirectionProperty =
DependencyProperty.RegisterAttached("SortDirection", typeof(ColumnSortDirection), typeof(SortableGridViewColumn),
new FrameworkPropertyMetadata(ColumnSortDirection.None, OnSortDirectionChanged));
public ColumnSortDirection SortDirection {
get { return (ColumnSortDirection)GetValue(SortDirectionProperty); }
set { SetValue(SortDirectionProperty, value); }
}
public static ColumnSortDirection GetSortDirection(ListView listView)
{
return (ColumnSortDirection)listView.GetValue(SortDirectionProperty);
}
public static void SetSortDirection(ListView listView, ColumnSortDirection value)
{
listView.SetValue(SortDirectionProperty, value);
}
static void OnSortDirectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
ListView grid = sender as ListView;
if (grid != null)
{
SortableGridViewColumn col = GetCurrentSortColumn(grid);
if (col != null)
col.SortDirection = (ColumnSortDirection)args.NewValue;
Sort(grid);
}
}
#endregion
#region CurrentSortColumn property
public static readonly DependencyProperty CurrentSortColumnProperty =
DependencyProperty.RegisterAttached("CurrentSortColumn", typeof(SortableGridViewColumn), typeof(SortableGridViewColumn),
new FrameworkPropertyMetadata(OnCurrentSortColumnChanged));
public static SortableGridViewColumn GetCurrentSortColumn(ListView listView)
{
return (SortableGridViewColumn)listView.GetValue(CurrentSortColumnProperty);
}
public static void SetCurrentSortColumn(ListView listView, SortableGridViewColumn value)
{
listView.SetValue(CurrentSortColumnProperty, value);
}
static void OnCurrentSortColumnChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
ListView grid = sender as ListView;
if (grid != null)
{
SortableGridViewColumn oldColumn = (SortableGridViewColumn)args.OldValue;
if (oldColumn != null)
oldColumn.SortDirection = ColumnSortDirection.None;
SortableGridViewColumn newColumn = (SortableGridViewColumn)args.NewValue;
if (newColumn != null)
{
newColumn.SortDirection = GetSortDirection(grid);
}
Sort(grid);
}
}
#endregion
#region SortMode property
public static readonly DependencyProperty SortModeProperty =
DependencyProperty.RegisterAttached("SortMode", typeof(ListViewSortMode), typeof(SortableGridViewColumn),
new FrameworkPropertyMetadata(ListViewSortMode.None, OnSortModeChanged));
public static ListViewSortMode GetSortMode(ListView listView)
{
return (ListViewSortMode)listView.GetValue(SortModeProperty);
}
public static void SetSortMode(ListView listView, ListViewSortMode value)
{
listView.SetValue(SortModeProperty, value);
}
static void OnSortModeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
ListView grid = sender as ListView;
if (grid != null)
{
if ((ListViewSortMode)args.NewValue != ListViewSortMode.None)
grid.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickHandler));
else
grid.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickHandler));
}
}
static void GridViewColumnHeaderClickHandler(object sender, RoutedEventArgs e)
{
ListView grid = sender as ListView;
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
if (grid != null && headerClicked != null && headerClicked.Role != GridViewColumnHeaderRole.Padding)
{
if (headerClicked.Column == GetCurrentSortColumn(grid))
{
switch (GetSortDirection(grid))
{
case ColumnSortDirection.None:
SetSortDirection(grid, ColumnSortDirection.Ascending);
break;
case ColumnSortDirection.Ascending:
SetSortDirection(grid, ColumnSortDirection.Descending);
break;
case ColumnSortDirection.Descending:
SetSortDirection(grid, ColumnSortDirection.None);
break;
}
}
else
{
SetSortDirection(grid, ColumnSortDirection.Ascending);
SetCurrentSortColumn(grid, headerClicked.Column as SortableGridViewColumn);
}
}
}
#endregion
static void Sort(ListView grid)
{
ColumnSortDirection currentDirection = GetSortDirection(grid);
SortableGridViewColumn column = GetCurrentSortColumn(grid);
ICollectionView dataView = CollectionViewSource.GetDefaultView(grid.ItemsSource);
if (dataView == null)
return;
if (column != null && GetSortMode(grid) == ListViewSortMode.Automatic && currentDirection != ColumnSortDirection.None)
{
string sortBy = column.SortBy;
if (sortBy == null)
{
Binding binding = column.DisplayMemberBinding as Binding;
if (binding != null && binding.Path != null)
{
sortBy = binding.Path.Path;
}
}
dataView.SortDescriptions.Clear();
if (sortBy != null)
{
ListSortDirection direction;
if (currentDirection == ColumnSortDirection.Descending)
direction = ListSortDirection.Descending;
else
direction = ListSortDirection.Ascending;
dataView.SortDescriptions.Add(new SortDescription(sortBy, direction));
}
}
else
{
dataView.SortDescriptions.Clear();
}
dataView.Refresh();
}
}
public enum ColumnSortDirection
{
None,
Ascending,
Descending
}
public enum ListViewSortMode
{
/// <summary>
/// Disable automatic sorting when sortable columns are clicked.
/// </summary>
None,
/// <summary>
/// Fully automatic sorting.
/// </summary>
Automatic,
/// <summary>
/// Automatically update SortDirection and CurrentSortColumn properties,
/// but do not actually sort the data.
/// </summary>
HalfAutomatic
}
sealed class ColumnSortDirectionToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Equals(value, parameter) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
| ILSpy/ILSpy/Controls/SortableGridViewColumn.cs/0 | {
"file_path": "ILSpy/ILSpy/Controls/SortableGridViewColumn.cs",
"repo_id": "ILSpy",
"token_count": 2776
} | 264 |
// 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.IO;
using System.Text;
using System.Xml;
namespace ICSharpCode.ILSpy
{
/// <summary>
/// Static methods for determining the type of a file.
/// </summary>
static class GuessFileType
{
public static FileType DetectFileType(Stream stream)
{
StreamReader reader;
if (stream.Length >= 2)
{
int firstByte = stream.ReadByte();
int secondByte = stream.ReadByte();
switch ((firstByte << 8) | secondByte)
{
case 0xfffe: // UTF-16 LE BOM / UTF-32 LE BOM
case 0xfeff: // UTF-16 BE BOM
stream.Position -= 2;
reader = new StreamReader(stream, detectEncodingFromByteOrderMarks: true);
break;
case 0xefbb: // start of UTF-8 BOM
if (stream.ReadByte() == 0xbf)
{
reader = new StreamReader(stream, Encoding.UTF8);
break;
}
else
{
return FileType.Binary;
}
default:
if (IsUTF8(stream, (byte)firstByte, (byte)secondByte))
{
stream.Position = 0;
reader = new StreamReader(stream, Encoding.UTF8);
break;
}
else
{
return FileType.Binary;
}
}
}
else
{
return FileType.Binary;
}
// Now we got a StreamReader with the correct encoding
// Check for XML now
try
{
XmlTextReader xmlReader = new XmlTextReader(reader);
xmlReader.XmlResolver = null;
xmlReader.MoveToContent();
return FileType.Xml;
}
catch (XmlException)
{
return FileType.Text;
}
}
static bool IsUTF8(Stream fs, byte firstByte, byte secondByte)
{
int max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB
const int ASCII = 0;
const int Error = 1;
const int UTF8 = 2;
const int UTF8Sequence = 3;
int state = ASCII;
int sequenceLength = 0;
byte b;
for (int i = 0; i < max; i++)
{
if (i == 0)
{
b = firstByte;
}
else if (i == 1)
{
b = secondByte;
}
else
{
b = (byte)fs.ReadByte();
}
if (b < 0x80)
{
// normal ASCII character
if (state == UTF8Sequence)
{
state = Error;
break;
}
}
else if (b < 0xc0)
{
// 10xxxxxx : continues UTF8 byte sequence
if (state == UTF8Sequence)
{
--sequenceLength;
if (sequenceLength < 0)
{
state = Error;
break;
}
else if (sequenceLength == 0)
{
state = UTF8;
}
}
else
{
state = Error;
break;
}
}
else if (b >= 0xc2 && b < 0xf5)
{
// beginning of byte sequence
if (state == UTF8 || state == ASCII)
{
state = UTF8Sequence;
if (b < 0xe0)
{
sequenceLength = 1; // one more byte following
}
else if (b < 0xf0)
{
sequenceLength = 2; // two more bytes following
}
else
{
sequenceLength = 3; // three more bytes following
}
}
else
{
state = Error;
break;
}
}
else
{
// 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629)
state = Error;
break;
}
}
return state != Error;
}
}
enum FileType
{
Binary,
Text,
Xml
}
}
| ILSpy/ILSpy/GuessFileType.cs/0 | {
"file_path": "ILSpy/ILSpy/GuessFileType.cs",
"repo_id": "ILSpy",
"token_count": 1920
} | 265 |
<!-- 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="F1M0,0L16,0 16,16 0,16z" />
<GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M0,2.9688L0,11.9688C0,12.5858 0.227,13.0718 0.57,13.4038 1.14,13.9478 2,13.9688 2,13.9688L13.677,13.9688 16,8.1648 16,6.9688 15,6.9688 15,4.9688C15,3.6698,13.97,2.9688,13,2.9688L10.116,2.9688 9.116,0.9688 2,0.9688C1.005,0.9688,0,1.6658,0,2.9688" />
<GeometryDrawing Brush="#FFDCB67A" Geometry="F1M1,3L1,12C1,12.97,1.94,12.984,1.997,12.984L2,12.984 2,3 8,3 9,5 13,5 13,8 4,8 2,13 13,13 15,8 14,8 14,5C14,4,12.764,4,13,4L9.5,4 8.5,2 2,2C2,2,1,2,1,3" />
</DrawingGroup.Children>
</DrawingGroup>
| ILSpy/ILSpy/Images/Folder.Open.xaml/0 | {
"file_path": "ILSpy/ILSpy/Images/Folder.Open.xaml",
"repo_id": "ILSpy",
"token_count": 440
} | 266 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="16"
height="16"
version="1.1"
id="svg9"
sodipodi:docname="OverlayPrivate.svg"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
inkscape:export-filename="C:\Users\sie_p\Projects\ILSpy master\ILSpy\Images\OverlayPrivate.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96">
<metadata
id="metadata15">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs13" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="2048"
inkscape:window-height="1089"
id="namedview11"
showgrid="false"
showguides="true"
inkscape:guide-bbox="true"
inkscape:zoom="45.254834"
inkscape:cx="4.5858528"
inkscape:cy="6.3901414"
inkscape:window-x="1912"
inkscape:window-y="-8"
inkscape:window-maximized="1"
inkscape:current-layer="svg9" />
<style
type="text/css"
id="style2">.icon-canvas-transparent{opacity:0;fill:#F6F6F6;} .icon-vs-out{fill:#F6F6F6;} .icon-vs-bg{fill:#424242;} .icon-vs-fg{fill:#F0EFF1;} .icon-vs-action-orange{fill:#C27D1A;}</style>
<path
class="icon-canvas-transparent"
d="M16 16h-16v-16h16v16z"
id="canvas" />
<path
class="icon-vs-out"
d="m 16,11 v 5 H 9 V 10.99501 H 9.1 C 9.2310581,9.8293885 9.2629692,8.007 12.422,8.007 L 12.594,8 c 2.78,0 3.21,1.827 3.329,3 z"
id="outline"
inkscape:connector-curvature="0"
style="fill:#f6f6f6"
sodipodi:nodetypes="ccccccccc" />
<path
class="icon-vs-bg"
d="M10.018 11.531c.13-1.125.18-2.531 2.576-2.531 2.227 0 2.285 1.412 2.37 2.531h-.966c-.014-.746-.155-1.541-1.404-1.541-1.241 0-1.516.812-1.575 1.541h-1.001zm4.982.469v3h-5v-3h5zm-2 1h-1v1h1v-1z"
id="notificationBg" />
<path
class="icon-vs-fg"
d="M12 13h1v1h-1v-1z"
id="notificationFg" />
<style
id="style17"
type="text/css">.icon-canvas-transparent{opacity:0;fill:#F6F6F6;} .icon-vs-out{fill:#F6F6F6;} .icon-vs-bg{fill:#424242;} .icon-vs-fg{fill:#F0EFF1;} .icon-vs-action-green{fill:#388A34;}</style>
</svg>
| ILSpy/ILSpy/Images/OverlayPrivate.svg/0 | {
"file_path": "ILSpy/ILSpy/Images/OverlayPrivate.svg",
"repo_id": "ILSpy",
"token_count": 1495
} | 267 |
<!-- 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="F1M3.9996,-0.000199999999999534L3.9996,4.9998 -0.000399999999999956,4.9998 -0.000399999999999956,15.9998 11.9996,15.9998 11.9996,10.9998 16.0006,10.9998 16.0006,-0.000199999999999534z" />
<GeometryDrawing Brush="#FFEFEFF0" Geometry="F1M14,9L11,9 11,6 6,6 6,2 14,2z M10,14L2,14 2,7 10,7z" />
<GeometryDrawing Brush="#FF00529C" Geometry="F1M14,9L11,9 11,6 6,6 6,2 14,2z M10,14L2,14 2,7 10,7z M5,1L5,6 1,6 1,15 11,15 11,10 15,10 15,1z" />
</DrawingGroup.Children>
</DrawingGroup> | ILSpy/ILSpy/Images/ShowPublicOnly.xaml/0 | {
"file_path": "ILSpy/ILSpy/Images/ShowPublicOnly.xaml",
"repo_id": "ILSpy",
"token_count": 385
} | 268 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
viewBox="0 0 16 16"
version="1.1"
id="svg8"
sodipodi:docname="ZoomIn.svg"
inkscape:version="1.1 (c68e22c387, 2021-05-23)"
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="defs12" />
<sodipodi:namedview
id="namedview10"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
showgrid="false"
inkscape:zoom="52"
inkscape:cx="8"
inkscape:cy="7.7211538"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="2552"
inkscape:window-y="605"
inkscape:window-maximized="1"
inkscape:current-layer="svg8" />
<style
id="style2">.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vs-out{fill:#f6f6f6}.icon-vs-bg{fill:#424242}.icon-vs-fg{fill:#f0eff1}</style>
<path
class="icon-canvas-transparent"
d="M16 16H0V0h16v16z"
id="canvas" />
<path
class="icon-vs-out"
d="M16 5.833a5.84 5.84 0 0 1-5.833 5.833 5.688 5.688 0 0 1-2.913-.8L2.56 15.559a1.494 1.494 0 0 1-2.121.002 1.501 1.501 0 0 1 0-2.121l4.694-4.695a5.69 5.69 0 0 1-.8-2.911C4.333 2.617 6.95 0 10.167 0S16 2.617 16 5.833z"
id="outline" />
<path
class="icon-vs-fg"
d="M14 5.833a3.837 3.837 0 0 1-3.833 3.833c-2.114 0-3.833-1.72-3.833-3.833S8.053 2 10.167 2A3.838 3.838 0 0 1 14 5.833z"
id="iconFg" />
<path
class="icon-vs-bg"
d="M10.167 1a4.84 4.84 0 0 0-4.834 4.833c0 1.152.422 2.197 1.097 3.028l-5.284 5.285a.5.5 0 0 0 .708.708l5.284-5.285c.832.676 1.877 1.098 3.029 1.098 2.665 0 4.833-2.168 4.833-4.833S12.832 1 10.167 1zm0 8.667c-2.114 0-3.833-1.72-3.833-3.833S8.053 2 10.167 2C12.28 2 14 3.72 14 5.833s-1.72 3.834-3.833 3.834z"
id="iconBg" />
<rect
style="fill:#424242;fill-opacity:1"
id="rect884"
width="4.6153846"
height="0.88461536"
x="7.8649998"
y="5.3461561" />
<rect
style="fill:#424242;fill-opacity:1"
id="rect4051"
width="4.6153846"
height="0.88461536"
x="3.4807715"
y="-10.615"
transform="rotate(90)" />
</svg>
| ILSpy/ILSpy/Images/ZoomIn.svg/0 | {
"file_path": "ILSpy/ILSpy/Images/ZoomIn.svg",
"repo_id": "ILSpy",
"token_count": 1286
} | 269 |
// 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.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.ILSpy.ViewModels;
using ICSharpCode.ILSpyX.Extensions;
namespace ICSharpCode.ILSpy.Metadata
{
class CoffHeaderTreeNode : ILSpyTreeNode
{
private PEFile module;
public CoffHeaderTreeNode(PEFile module)
{
this.module = module;
}
public override object Text => "COFF Header";
public override object Icon => Images.Header;
public override bool View(TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
var dataGrid = Helpers.PrepareDataGrid(tabPage, this);
dataGrid.RowDetailsTemplateSelector = new CharacteristicsDataTemplateSelector("Characteristics");
dataGrid.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.Collapsed;
dataGrid.Columns.Clear();
dataGrid.AutoGenerateColumns = false;
dataGrid.Columns.AddRange(
new[] {
new DataGridTextColumn { IsReadOnly = true, Header = "Member", Binding = new Binding("Member") },
new DataGridTextColumn { IsReadOnly = true, Header = "Offset", Binding = new Binding("Offset") { StringFormat = "X8" } },
new DataGridTextColumn { IsReadOnly = true, Header = "Size", Binding = new Binding("Size") },
new DataGridTextColumn { IsReadOnly = true, Header = "Value", Binding = new Binding(".") { Converter = ByteWidthConverter.Instance } },
new DataGridTextColumn { IsReadOnly = true, Header = "Meaning", Binding = new Binding("Meaning") }
}
);
var headers = module.Reader.PEHeaders;
var header = headers.CoffHeader;
var linkerDateTime = DateTimeOffset.FromUnixTimeSeconds(unchecked((uint)header.TimeDateStamp)).DateTime;
var entries = new List<Entry>();
entries.Add(new Entry(headers.CoffHeaderStartOffset, (int)header.Machine, 2, "Machine", header.Machine.ToString()));
entries.Add(new Entry(headers.CoffHeaderStartOffset + 2, (int)header.NumberOfSections, 2, "Number of Sections", "Number of sections; indicates size of the Section Table, which immediately follows the headers."));
entries.Add(new Entry(headers.CoffHeaderStartOffset + 4, header.TimeDateStamp, 4, "Time/Date Stamp", $"{linkerDateTime} (UTC) / {linkerDateTime.ToLocalTime()} - Time and date the file was created in seconds since January 1st 1970 00:00:00 or 0. Note that for deterministic builds this value is meaningless."));
entries.Add(new Entry(headers.CoffHeaderStartOffset + 8, header.PointerToSymbolTable, 4, "Pointer to Symbol Table", "Always 0 in .NET executables."));
entries.Add(new Entry(headers.CoffHeaderStartOffset + 12, header.NumberOfSymbols, 4, "Number of Symbols", "Always 0 in .NET executables."));
entries.Add(new Entry(headers.CoffHeaderStartOffset + 16, (int)header.SizeOfOptionalHeader, 2, "Optional Header Size", "Size of the optional header."));
Entry characteristics;
entries.Add(characteristics = new Entry(headers.CoffHeaderStartOffset + 18, (int)header.Characteristics, 2, "Characteristics", "Flags indicating attributes of the file.", new[] {
new BitEntry(((int)header.Characteristics & 0x0001) != 0, "<0001> Relocation info stripped from file"),
new BitEntry(((int)header.Characteristics & 0x0002) != 0, "<0002> File is executable"),
new BitEntry(((int)header.Characteristics & 0x0004) != 0, "<0004> Line numbers stripped from file"),
new BitEntry(((int)header.Characteristics & 0x0008) != 0, "<0008> Local symbols stripped from file"),
new BitEntry(((int)header.Characteristics & 0x0010) != 0, "<0010> Aggressively trim working set"),
new BitEntry(((int)header.Characteristics & 0x0020) != 0, "<0020> Large address aware"),
new BitEntry(((int)header.Characteristics & 0x0040) != 0, "<0040> Reserved"),
new BitEntry(((int)header.Characteristics & 0x0080) != 0, "<0080> Bytes of machine words are reversed (Low)"),
new BitEntry(((int)header.Characteristics & 0x0100) != 0, "<0100> 32-bit word machine"),
new BitEntry(((int)header.Characteristics & 0x0200) != 0, "<0200> Debugging info stripped from file in .DBG file"),
new BitEntry(((int)header.Characteristics & 0x0400) != 0, "<0400> If image is on removable media, copy and run from the swap file"),
new BitEntry(((int)header.Characteristics & 0x0800) != 0, "<0800> If image is on Net, copy and run from the swap file"),
new BitEntry(((int)header.Characteristics & 0x1000) != 0, "<1000> System"),
new BitEntry(((int)header.Characteristics & 0x2000) != 0, "<2000> DLL"),
new BitEntry(((int)header.Characteristics & 0x4000) != 0, "<4000> File should only be run on a UP machine"),
new BitEntry(((int)header.Characteristics & 0x8000) != 0, "<8000> Bytes of machine words are reversed (High)"),
}));
dataGrid.ItemsSource = entries;
dataGrid.SetDetailsVisibilityForItem(characteristics, Visibility.Visible);
tabPage.Content = dataGrid;
return true;
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "COFF Header");
}
}
public class CharacteristicsDataTemplateSelector : DataTemplateSelector
{
string detailsFieldName;
public CharacteristicsDataTemplateSelector(string detailsFieldName)
{
this.detailsFieldName = detailsFieldName;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (((Entry)item).Member == detailsFieldName)
return (DataTemplate)MetadataTableViews.Instance["HeaderFlagsDetailsDataGrid"];
return null;
}
}
}
| ILSpy/ILSpy/Metadata/CoffHeaderTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/CoffHeaderTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 2140
} | 270 |
// 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.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
namespace ICSharpCode.ILSpy.Metadata
{
internal class GenericParamTableTreeNode : MetadataTableTreeNode
{
public GenericParamTableTreeNode(MetadataFile metadataFile)
: base(HandleKind.GenericParameter, metadataFile)
{
}
public override object Text => $"2A GenericParam ({metadataFile.Metadata.GetTableRowCount(TableIndex.GenericParam)})";
public override bool View(ViewModels.TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
var view = Helpers.PrepareDataGrid(tabPage, this);
var list = new List<GenericParamEntry>();
GenericParamEntry scrollTargetEntry = default;
for (int row = 1; row <= metadataFile.Metadata.GetTableRowCount(TableIndex.GenericParam); row++)
{
GenericParamEntry entry = new GenericParamEntry(metadataFile, MetadataTokens.GenericParameterHandle(row));
if (entry.RID == this.scrollTarget)
{
scrollTargetEntry = entry;
}
list.Add(entry);
}
view.ItemsSource = list;
tabPage.Content = view;
if (scrollTargetEntry.RID > 0)
{
ScrollItemIntoView(view, scrollTargetEntry);
}
return true;
}
struct GenericParamEntry
{
readonly MetadataFile metadataFile;
readonly GenericParameterHandle handle;
readonly GenericParameter genericParam;
public int RID => MetadataTokens.GetRowNumber(handle);
public int Token => MetadataTokens.GetToken(handle);
public int Offset => metadataFile.MetadataOffset
+ metadataFile.Metadata.GetTableMetadataOffset(TableIndex.GenericParam)
+ metadataFile.Metadata.GetTableRowSize(TableIndex.GenericParam) * (RID - 1);
public int Number => genericParam.Index;
[ColumnInfo("X8", Kind = ColumnKind.Other)]
public GenericParameterAttributes Attributes => genericParam.Attributes;
public object AttributesTooltip => new FlagsTooltip {
FlagGroup.CreateSingleChoiceGroup(typeof(GenericParameterAttributes), "Code type: ", (int)GenericParameterAttributes.VarianceMask, (int)(genericParam.Attributes & GenericParameterAttributes.VarianceMask), new Flag("None (0000)", 0, false), includeAny: false),
FlagGroup.CreateSingleChoiceGroup(typeof(GenericParameterAttributes), "Managed type: ", (int)GenericParameterAttributes.SpecialConstraintMask, (int)(genericParam.Attributes & GenericParameterAttributes.SpecialConstraintMask), new Flag("None (0000)", 0, false), includeAny: false),
};
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int Owner => MetadataTokens.GetToken(genericParam.Parent);
public void OnOwnerClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, genericParam.Parent, protocol: "metadata"));
}
string ownerTooltip;
public string OwnerTooltip => GenerateTooltip(ref ownerTooltip, metadataFile, genericParam.Parent);
public string Name => metadataFile.Metadata.GetString(genericParam.Name);
public string NameTooltip => $"{MetadataTokens.GetHeapOffset(genericParam.Name):X} \"{Name}\"";
public GenericParamEntry(MetadataFile metadataFile, GenericParameterHandle handle)
{
this.metadataFile = metadataFile;
this.handle = handle;
this.genericParam = metadataFile.Metadata.GetGenericParameter(handle);
this.ownerTooltip = null;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "GenericParams");
}
}
} | ILSpy/ILSpy/Metadata/CorTables/GenericParamTableTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/CorTables/GenericParamTableTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 1447
} | 271 |
// 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.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Disassembler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.ILSpy.TreeNodes;
namespace ICSharpCode.ILSpy.Metadata
{
internal class TypeDefTableTreeNode : MetadataTableTreeNode
{
public TypeDefTableTreeNode(MetadataFile metadataFile)
: base(HandleKind.TypeDefinition, metadataFile)
{
}
public override object Text => $"02 TypeDef ({metadataFile.Metadata.GetTableRowCount(TableIndex.TypeDef)})";
public override bool View(ViewModels.TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
var view = Helpers.PrepareDataGrid(tabPage, this);
var metadata = metadataFile.Metadata;
var list = new List<TypeDefEntry>();
TypeDefEntry scrollTargetEntry = default;
foreach (var row in metadata.TypeDefinitions)
{
TypeDefEntry entry = new TypeDefEntry(metadataFile, row);
if (entry.RID == this.scrollTarget)
{
scrollTargetEntry = entry;
}
list.Add(entry);
}
view.ItemsSource = list;
tabPage.Content = view;
if (scrollTargetEntry.RID > 0)
{
ScrollItemIntoView(view, scrollTargetEntry);
}
return true;
}
struct TypeDefEntry : IMemberTreeNode
{
readonly MetadataFile metadataFile;
readonly TypeDefinitionHandle handle;
readonly TypeDefinition typeDef;
public int RID => MetadataTokens.GetRowNumber(handle);
public int Token => MetadataTokens.GetToken(handle);
public int Offset => metadataFile.MetadataOffset
+ metadataFile.Metadata.GetTableMetadataOffset(TableIndex.TypeDef)
+ metadataFile.Metadata.GetTableRowSize(TableIndex.TypeDef) * (RID - 1);
[ColumnInfo("X8", Kind = ColumnKind.Other)]
public TypeAttributes Attributes => typeDef.Attributes;
const TypeAttributes otherFlagsMask = ~(TypeAttributes.VisibilityMask | TypeAttributes.LayoutMask | TypeAttributes.ClassSemanticsMask | TypeAttributes.StringFormatMask | TypeAttributes.CustomFormatMask);
public object AttributesTooltip => new FlagsTooltip {
FlagGroup.CreateSingleChoiceGroup(typeof(TypeAttributes), "Visibility: ", (int)TypeAttributes.VisibilityMask, (int)(typeDef.Attributes & TypeAttributes.VisibilityMask), new Flag("NotPublic (0000)", 0, false), includeAny: false),
FlagGroup.CreateSingleChoiceGroup(typeof(TypeAttributes), "Class layout: ", (int)TypeAttributes.LayoutMask, (int)(typeDef.Attributes & TypeAttributes.LayoutMask), new Flag("AutoLayout (0000)", 0, false), includeAny: false),
FlagGroup.CreateSingleChoiceGroup(typeof(TypeAttributes), "Class semantics: ", (int)TypeAttributes.ClassSemanticsMask, (int)(typeDef.Attributes & TypeAttributes.ClassSemanticsMask), new Flag("Class (0000)", 0, false), includeAny: false),
FlagGroup.CreateSingleChoiceGroup(typeof(TypeAttributes), "String format: ", (int)TypeAttributes.StringFormatMask, (int)(typeDef.Attributes & TypeAttributes.StringFormatMask), new Flag("AnsiClass (0000)", 0, false), includeAny: false),
FlagGroup.CreateSingleChoiceGroup(typeof(TypeAttributes), "Custom format: ", (int)TypeAttributes.CustomFormatMask, (int)(typeDef.Attributes & TypeAttributes.CustomFormatMask), new Flag("Value0 (0000)", 0, false), includeAny: false),
FlagGroup.CreateMultipleChoiceGroup(typeof(TypeAttributes), "Flags:", (int)otherFlagsMask, (int)(typeDef.Attributes & otherFlagsMask), includeAll: false),
};
public string NameTooltip => $"{MetadataTokens.GetHeapOffset(typeDef.Name):X} \"{Name}\"";
public string Name => metadataFile.Metadata.GetString(typeDef.Name);
public string NamespaceTooltip => $"{MetadataTokens.GetHeapOffset(typeDef.Namespace):X} \"{Namespace}\"";
public string Namespace => metadataFile.Metadata.GetString(typeDef.Namespace);
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int BaseType => MetadataTokens.GetToken(typeDef.BaseType);
public void OnBaseTypeClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, typeDef.BaseType, protocol: "metadata"));
}
public string BaseTypeTooltip {
get {
var output = new PlainTextOutput();
var provider = new DisassemblerSignatureTypeProvider(metadataFile, output);
if (typeDef.BaseType.IsNil)
return null;
switch (typeDef.BaseType.Kind)
{
case HandleKind.TypeDefinition:
provider.GetTypeFromDefinition(metadataFile.Metadata, (TypeDefinitionHandle)typeDef.BaseType, 0)(ILNameSyntax.Signature);
return output.ToString();
case HandleKind.TypeReference:
provider.GetTypeFromReference(metadataFile.Metadata, (TypeReferenceHandle)typeDef.BaseType, 0)(ILNameSyntax.Signature);
return output.ToString();
case HandleKind.TypeSpecification:
provider.GetTypeFromSpecification(metadataFile.Metadata, new Decompiler.Metadata.MetadataGenericContext(default(TypeDefinitionHandle), metadataFile.Metadata), (TypeSpecificationHandle)typeDef.BaseType, 0)(ILNameSyntax.Signature);
return output.ToString();
default:
return null;
}
}
}
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int FieldList => MetadataTokens.GetToken(typeDef.GetFields().FirstOrDefault());
public void OnFieldListClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, typeDef.GetFields().FirstOrDefault(), protocol: "metadata"));
}
string fieldListTooltip;
public string FieldListTooltip {
get {
var field = typeDef.GetFields().FirstOrDefault();
if (field.IsNil)
return null;
return GenerateTooltip(ref fieldListTooltip, metadataFile, field);
}
}
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int MethodList => MetadataTokens.GetToken(typeDef.GetMethods().FirstOrDefault());
public void OnMethodListClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, typeDef.GetMethods().FirstOrDefault(), protocol: "metadata"));
}
string methodListTooltip;
public string MethodListTooltip {
get {
var method = typeDef.GetMethods().FirstOrDefault();
if (method.IsNil)
return null;
return GenerateTooltip(ref methodListTooltip, metadataFile, method);
}
}
IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle);
public TypeDefEntry(MetadataFile metadataFile, TypeDefinitionHandle handle)
{
this.metadataFile = metadataFile;
this.handle = handle;
this.typeDef = metadataFile.Metadata.GetTypeDefinition(handle);
this.methodListTooltip = null;
this.fieldListTooltip = null;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "TypeDefs");
}
}
} | ILSpy/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 2643
} | 272 |
// 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.ComponentModel.Composition;
using System.Linq;
using System.Reflection.Metadata;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.TreeNodes;
namespace ICSharpCode.ILSpy.Metadata
{
[Export(typeof(IProtocolHandler))]
class MetadataProtocolHandler : IProtocolHandler
{
public ILSpyTreeNode Resolve(string protocol, PEFile module, Handle handle, out bool newTabPage)
{
newTabPage = true;
if (protocol != "metadata")
return null;
var assemblyTreeNode = MainWindow.Instance.FindTreeNode(module) as AssemblyTreeNode;
if (assemblyTreeNode == null)
return null;
var mxNode = assemblyTreeNode.Children.OfType<MetadataTreeNode>().FirstOrDefault();
if (mxNode != null)
{
mxNode.EnsureLazyChildren();
var node = mxNode.FindNodeByHandleKind(handle.Kind);
node?.ScrollTo(handle);
return node;
}
return null;
}
}
}
| ILSpy/ILSpy/Metadata/MetadataProtocolHandler.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/MetadataProtocolHandler.cs",
"repo_id": "ILSpy",
"token_count": 622
} | 273 |
<UserControl x:Class="ICSharpCode.ILSpy.Options.MiscSettingsPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:properties="clr-namespace:ICSharpCode.ILSpy.Properties"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Vertical">
<GroupBox Header="{x:Static properties:Resources.Misc}">
<StackPanel Margin="10">
<CheckBox IsChecked="{Binding AllowMultipleInstances}" Content="{x:Static properties:Resources.AllowMultipleInstances}" />
<CheckBox IsChecked="{Binding LoadPreviousAssemblies}" Content="{x:Static properties:Resources.LoadAssembliesThatWereLoadedInTheLastInstance}"/>
<Button Command="{Binding AddRemoveShellIntegrationCommand}" Content="{Binding AddRemoveShellIntegrationText}" Margin="3" />
</StackPanel>
</GroupBox>
</StackPanel>
</UserControl>
| ILSpy/ILSpy/Options/MiscSettingsPanel.xaml/0 | {
"file_path": "ILSpy/ILSpy/Options/MiscSettingsPanel.xaml",
"repo_id": "ILSpy",
"token_count": 425
} | 274 |
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Solution;
using ICSharpCode.Decompiler.Util;
using ICSharpCode.ILSpy.TextView;
using ICSharpCode.ILSpyX;
namespace ICSharpCode.ILSpy
{
/// <summary>
/// An utility class that creates a Visual Studio solution containing projects for the
/// decompiled assemblies.
/// </summary>
internal class SolutionWriter
{
/// <summary>
/// Creates a Visual Studio solution that contains projects with decompiled code
/// of the specified <paramref name="assemblies"/>. The solution file will be saved
/// to the <paramref name="solutionFilePath"/>. The directory of this file must either
/// be empty or not exist.
/// </summary>
/// <param name="textView">A reference to the <see cref="DecompilerTextView"/> instance.</param>
/// <param name="solutionFilePath">The target file path of the solution file.</param>
/// <param name="assemblies">The assembly nodes to decompile.</param>
///
/// <exception cref="ArgumentException">Thrown when <paramref name="solutionFilePath"/> is null,
/// an empty or a whitespace string.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="textView"/>> or
/// <paramref name="assemblies"/> is null.</exception>
public static void CreateSolution(DecompilerTextView textView, string solutionFilePath, Language language, IEnumerable<LoadedAssembly> assemblies)
{
if (textView == null)
{
throw new ArgumentNullException(nameof(textView));
}
if (string.IsNullOrWhiteSpace(solutionFilePath))
{
throw new ArgumentException("The solution file path cannot be null or empty.", nameof(solutionFilePath));
}
if (assemblies == null)
{
throw new ArgumentNullException(nameof(assemblies));
}
var writer = new SolutionWriter(solutionFilePath);
textView
.RunWithCancellation(ct => writer.CreateSolution(assemblies, language, ct))
.Then(output => textView.ShowText(output))
.HandleExceptions();
}
readonly string solutionFilePath;
readonly string solutionDirectory;
readonly ConcurrentBag<ProjectItem> projects;
readonly ConcurrentBag<string> statusOutput;
SolutionWriter(string solutionFilePath)
{
this.solutionFilePath = solutionFilePath;
solutionDirectory = Path.GetDirectoryName(solutionFilePath);
statusOutput = new ConcurrentBag<string>();
projects = new ConcurrentBag<ProjectItem>();
}
async Task<AvalonEditTextOutput> CreateSolution(IEnumerable<LoadedAssembly> assemblies, Language language, CancellationToken ct)
{
var result = new AvalonEditTextOutput();
var duplicates = new HashSet<string>();
if (assemblies.Any(asm => !duplicates.Add(asm.ShortName)))
{
result.WriteLine("Duplicate assembly names selected, cannot generate a solution.");
return result;
}
Stopwatch stopwatch = Stopwatch.StartNew();
try
{
// Explicitly create an enumerable partitioner here to avoid Parallel.ForEach's special cases for lists,
// as those seem to use static partitioning which is inefficient if assemblies take differently
// long to decompile.
await Task.Run(() => Parallel.ForEach(Partitioner.Create(assemblies),
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct },
n => WriteProject(n, language, solutionDirectory, ct)))
.ConfigureAwait(false);
if (projects.Count == 0)
{
result.WriteLine();
result.WriteLine("Solution could not be created, because none of the selected assemblies could be decompiled into a project.");
}
else
{
await Task.Run(() => SolutionCreator.WriteSolutionFile(solutionFilePath, projects))
.ConfigureAwait(false);
}
}
catch (AggregateException ae)
{
if (ae.Flatten().InnerExceptions.All(e => e is OperationCanceledException))
{
result.WriteLine();
result.WriteLine("Generation was cancelled.");
return result;
}
result.WriteLine();
result.WriteLine("Failed to generate the Visual Studio Solution. Errors:");
ae.Handle(e => {
result.WriteLine(e.Message);
return true;
});
return result;
}
foreach (var item in statusOutput)
{
result.WriteLine(item);
}
if (statusOutput.Count == 0)
{
result.WriteLine("Successfully decompiled the following assemblies into Visual Studio projects:");
foreach (var item in assemblies.Select(n => n.Text.ToString()))
{
result.WriteLine(item);
}
result.WriteLine();
if (assemblies.Count() == projects.Count)
{
result.WriteLine("Created the Visual Studio Solution file.");
}
result.WriteLine();
result.WriteLine("Elapsed time: " + stopwatch.Elapsed.TotalSeconds.ToString("F1") + " seconds.");
result.WriteLine();
result.AddButton(null, "Open Explorer", delegate { Process.Start("explorer", "/select,\"" + solutionFilePath + "\""); });
}
return result;
}
void WriteProject(LoadedAssembly loadedAssembly, Language language, string targetDirectory, CancellationToken ct)
{
targetDirectory = Path.Combine(targetDirectory, loadedAssembly.ShortName);
if (language.ProjectFileExtension == null)
{
statusOutput.Add("-------------");
statusOutput.Add($"Language '{language.Name}' does not support exporting assemblies as projects!");
return;
}
string projectFileName = Path.Combine(targetDirectory, loadedAssembly.ShortName + language.ProjectFileExtension);
if (File.Exists(targetDirectory))
{
statusOutput.Add("-------------");
statusOutput.Add($"Failed to create a directory '{targetDirectory}':{Environment.NewLine}A file with the same name already exists!");
return;
}
if (!Directory.Exists(targetDirectory))
{
try
{
Directory.CreateDirectory(targetDirectory);
}
catch (Exception e)
{
statusOutput.Add("-------------");
statusOutput.Add($"Failed to create a directory '{targetDirectory}':{Environment.NewLine}{e}");
return;
}
}
try
{
using (var projectFileWriter = new StreamWriter(projectFileName))
{
var projectFileOutput = new PlainTextOutput(projectFileWriter);
var options = MainWindow.Instance.CreateDecompilationOptions();
options.FullDecompilation = true;
options.CancellationToken = ct;
options.SaveAsProjectDirectory = targetDirectory;
var projectInfo = language.DecompileAssembly(loadedAssembly, projectFileOutput, options);
if (projectInfo != null)
{
projects.Add(new ProjectItem(projectFileName, projectInfo.PlatformName, projectInfo.Guid, projectInfo.TypeGuid));
}
}
}
catch (NotSupportedException e)
{
statusOutput.Add("-------------");
statusOutput.Add($"Failed to decompile the assembly '{loadedAssembly.FileName}':{Environment.NewLine}{e.Message}");
}
catch (PathTooLongException e)
{
statusOutput.Add("-------------");
statusOutput.Add(string.Format(Properties.Resources.ProjectExportPathTooLong, loadedAssembly.FileName)
+ Environment.NewLine + Environment.NewLine
+ e.ToString());
}
catch (Exception e) when (!(e is OperationCanceledException))
{
statusOutput.Add("-------------");
statusOutput.Add($"Failed to decompile the assembly '{loadedAssembly.FileName}':{Environment.NewLine}{e}");
}
}
}
}
| ILSpy/ILSpy/SolutionWriter.cs/0 | {
"file_path": "ILSpy/ILSpy/SolutionWriter.cs",
"repo_id": "ILSpy",
"token_count": 2888
} | 275 |
using System;
using System.Collections.Generic;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.ILSpy.Themes;
namespace ICSharpCode.ILSpy.TextView;
#nullable enable
public class ThemeAwareHighlightingColorizer : HighlightingColorizer
{
private readonly Dictionary<HighlightingColor, HighlightingColor> _darkColors = new();
private readonly bool _isHighlightingThemeAware;
public ThemeAwareHighlightingColorizer(IHighlightingDefinition highlightingDefinition)
: base(highlightingDefinition)
{
_isHighlightingThemeAware = ThemeManager.Current.IsThemeAware(highlightingDefinition);
}
protected override void ApplyColorToElement(VisualLineElement element, HighlightingColor color)
{
if (!_isHighlightingThemeAware && ThemeManager.Current.IsDarkTheme)
{
color = GetColorForDarkTheme(color);
}
base.ApplyColorToElement(element, color);
}
private HighlightingColor GetColorForDarkTheme(HighlightingColor lightColor)
{
if (lightColor.Foreground is null && lightColor.Background is null)
{
return lightColor;
}
if (!_darkColors.TryGetValue(lightColor, out var darkColor))
{
darkColor = lightColor.Clone();
darkColor.Foreground = AdjustForDarkTheme(darkColor.Foreground);
darkColor.Background = AdjustForDarkTheme(darkColor.Background);
_darkColors[lightColor] = darkColor;
}
return darkColor;
}
private static HighlightingBrush? AdjustForDarkTheme(HighlightingBrush? lightBrush)
{
if (lightBrush is SimpleHighlightingBrush simpleBrush && simpleBrush.GetBrush(null) is SolidColorBrush brush)
{
return new SimpleHighlightingBrush(AdjustForDarkTheme(brush.Color));
}
return lightBrush;
}
private static Color AdjustForDarkTheme(Color color)
{
var c = System.Drawing.Color.FromArgb(color.R, color.G, color.B);
var (h, s, l) = (c.GetHue(), c.GetSaturation(), c.GetBrightness());
// Invert the lightness, but also increase it a bit
l = 1f - MathF.Pow(l, 1.2f);
// Desaturate the colors, as they'd be too intense otherwise
if (s > 0.75f && l < 0.75f)
{
s *= 0.75f;
l *= 1.2f;
}
var (r, g, b) = HslToRgb(h, s, l);
return Color.FromArgb(color.A, r, g, b);
}
private static (byte r, byte g, byte b) HslToRgb(float h, float s, float l)
{
// https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB
var c = (1f - Math.Abs(2f * l - 1f)) * s;
h = h % 360f / 60f;
var x = c * (1f - Math.Abs(h % 2f - 1f));
var (r1, g1, b1) = (int)Math.Floor(h) switch {
0 => (c, x, 0f),
1 => (x, c, 0f),
2 => (0f, c, x),
3 => (0f, x, c),
4 => (x, 0f, c),
_ => (c, 0f, x)
};
var m = l - c / 2f;
var r = (byte)((r1 + m) * 255f);
var g = (byte)((g1 + m) * 255f);
var b = (byte)((b1 + m) * 255f);
return (r, g, b);
}
}
| ILSpy/ILSpy/TextView/ThemeAwareHighlightingColorizer.cs/0 | {
"file_path": "ILSpy/ILSpy/TextView/ThemeAwareHighlightingColorizer.cs",
"repo_id": "ILSpy",
"token_count": 1100
} | 276 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:ICSharpCode.ILSpy.Controls"
xmlns:themes="clr-namespace:ICSharpCode.ILSpy.Themes">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Controls/SearchBoxStyle.xaml" />
<ResourceDictionary Source="../Controls/ZoomScrollViewer.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- SortableGridViewColumn.
Displays an up arrow or down arrow in the column header when the grid is sorted using that column.
-->
<controls:ColumnSortDirectionToVisibilityConverter x:Key="ColumnSortDirectionToVisibilityConverter"/>
<DataTemplate x:Key="{ComponentResourceKey {x:Type controls:SortableGridViewColumn}, ColumnHeaderTemplate}">
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Center" Text="{Binding}"/>
<Path x:Name="upArrow"
Visibility="{Binding Path=Column.SortDirection, ConverterParameter={x:Static controls:ColumnSortDirection.Ascending}, RelativeSource={RelativeSource AncestorType={x:Type GridViewColumnHeader}}, Converter={StaticResource ColumnSortDirectionToVisibilityConverter}}"
StrokeThickness = "1"
Fill = "Gray"
Data = "M 5,10 L 15,10 L 10,5 L 5,10"/>
<Path x:Name="downArrow"
Visibility="{Binding Path=Column.SortDirection, ConverterParameter={x:Static controls:ColumnSortDirection.Descending}, RelativeSource={RelativeSource AncestorType={x:Type GridViewColumnHeader}}, Converter={StaticResource ColumnSortDirectionToVisibilityConverter}}"
StrokeThickness = "1"
Fill = "Gray"
Data = "M 5,5 L 10,10 L 15,5 L 5,5"/>
</StackPanel>
</DataTemplate>
<Color x:Key="{x:Static themes:ResourceKeys.TextMarkerBackgroundColor}">GreenYellow</Color>
<Color x:Key="{x:Static themes:ResourceKeys.TextMarkerDefinitionBackgroundColor}">LightSeaGreen</Color>
<SolidColorBrush x:Key="{x:Static themes:ResourceKeys.LinkTextForegroundBrush}">Blue</SolidColorBrush>
</ResourceDictionary> | ILSpy/ILSpy/Themes/generic.xaml/0 | {
"file_path": "ILSpy/ILSpy/Themes/generic.xaml",
"repo_id": "ILSpy",
"token_count": 770
} | 277 |
// 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.Reflection.Metadata;
using System.Windows.Media;
using ICSharpCode.Decompiler;
namespace ICSharpCode.ILSpy.TreeNodes
{
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.ILSpyX;
/// <summary>
/// Tree Node representing a field, method, property, or event.
/// </summary>
public sealed class MethodTreeNode : ILSpyTreeNode, IMemberTreeNode
{
public IMethod MethodDefinition { get; }
public MethodTreeNode(IMethod method)
{
this.MethodDefinition = method ?? throw new ArgumentNullException(nameof(method));
}
public override object Text => GetText(GetMethodDefinition(), Language) + GetSuffixString(MethodDefinition);
private IMethod GetMethodDefinition()
{
return ((MetadataModule)MethodDefinition.ParentModule.PEFile
?.GetTypeSystemWithCurrentOptionsOrNull()
?.MainModule)?.GetDefinition((MethodDefinitionHandle)MethodDefinition.MetadataToken) ?? MethodDefinition;
}
public static object GetText(IMethod method, Language language)
{
return language.MethodToString(method, false, false, false);
}
public override object Icon => GetIcon(GetMethodDefinition());
public static ImageSource GetIcon(IMethod method)
{
if (method.IsOperator)
return Images.GetIcon(MemberIcon.Operator, GetOverlayIcon(method.Accessibility), false);
if (method.IsExtensionMethod)
return Images.GetIcon(MemberIcon.ExtensionMethod, GetOverlayIcon(method.Accessibility), false);
if (method.IsConstructor)
return Images.GetIcon(MemberIcon.Constructor, GetOverlayIcon(method.Accessibility), method.IsStatic);
if (!method.HasBody && method.HasAttribute(KnownAttribute.DllImport))
return Images.GetIcon(MemberIcon.PInvokeMethod, GetOverlayIcon(method.Accessibility), true);
return Images.GetIcon(method.IsVirtual ? MemberIcon.VirtualMethod : MemberIcon.Method,
GetOverlayIcon(method.Accessibility), method.IsStatic);
}
internal static AccessOverlayIcon GetOverlayIcon(Accessibility accessibility)
{
switch (accessibility)
{
case Accessibility.Public:
return AccessOverlayIcon.Public;
case Accessibility.Internal:
return AccessOverlayIcon.Internal;
case Accessibility.ProtectedAndInternal:
return AccessOverlayIcon.PrivateProtected;
case Accessibility.Protected:
return AccessOverlayIcon.Protected;
case Accessibility.ProtectedOrInternal:
return AccessOverlayIcon.ProtectedInternal;
case Accessibility.Private:
return AccessOverlayIcon.Private;
default:
return AccessOverlayIcon.CompilerControlled;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.DecompileMethod(MethodDefinition, output, options);
}
public override FilterResult Filter(FilterSettings settings)
{
if (settings.ShowApiLevel == ApiVisibility.PublicOnly && !IsPublicAPI)
return FilterResult.Hidden;
if (settings.SearchTermMatches(MethodDefinition.Name) && (settings.ShowApiLevel == ApiVisibility.All || settings.Language.ShowMember(MethodDefinition)))
return FilterResult.Match;
else
return FilterResult.Hidden;
}
public override bool IsPublicAPI {
get {
switch (GetMethodDefinition().Accessibility)
{
case Accessibility.Public:
case Accessibility.Protected:
case Accessibility.ProtectedOrInternal:
return true;
default:
return false;
}
}
}
IEntity IMemberTreeNode.Member => MethodDefinition;
public override string ToString()
{
return Languages.ILLanguage.MethodToString(MethodDefinition, false, false, false);
}
}
}
| ILSpy/ILSpy/TreeNodes/MethodTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/TreeNodes/MethodTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 1483
} | 278 |
// 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.ComponentModel.Composition;
using System.IO;
using System.Threading.Tasks;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.TextView;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.ILSpy.ViewModels;
using ICSharpCode.ILSpyX.Abstractions;
namespace ICSharpCode.ILSpy.Xaml
{
[Export(typeof(IResourceNodeFactory))]
sealed class XamlResourceNodeFactory : IResourceNodeFactory
{
public ITreeNode CreateNode(Resource resource)
{
if (resource.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase))
return new XamlResourceEntryNode(resource.Name, resource.TryOpenStream);
else
return null;
}
}
sealed class XamlResourceEntryNode : ResourceEntryNode
{
string xaml;
public XamlResourceEntryNode(string key, Func<Stream> openStream) : base(key, openStream)
{
}
public override bool View(TabPageModel tabPage)
{
AvalonEditTextOutput output = new AvalonEditTextOutput();
IHighlightingDefinition highlighting = null;
tabPage.ShowTextView(textView => textView.RunWithCancellation(
token => Task.Factory.StartNew(
() => {
try
{
// cache read XAML because stream will be closed after first read
if (xaml == null)
{
using var data = OpenStream();
if (data == null)
{
output.Write("ILSpy: Failed opening resource stream.");
output.WriteLine();
return output;
}
using (var reader = new StreamReader(data))
{
xaml = reader.ReadToEnd();
}
}
output.Write(xaml);
highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
}
catch (Exception ex)
{
output.Write(ex.ToString());
}
return output;
}, token)
).Then(t => textView.ShowNode(t, this, highlighting)).HandleExceptions());
tabPage.SupportsLanguageSwitching = false;
return true;
}
}
}
| ILSpy/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs/0 | {
"file_path": "ILSpy/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs",
"repo_id": "ILSpy",
"token_count": 1100
} | 279 |
// Copyright (c) 2019 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ICSharpCode.ILSpy.TextView;
using ICSharpCode.ILSpyX;
namespace ICSharpCode.ILSpy.ViewModels
{
public class TabPageModel : PaneModel
{
public TabPageModel()
{
this.Title = Properties.Resources.NewTab;
}
private FilterSettings filterSettings;
public FilterSettings FilterSettings {
get => filterSettings;
set {
if (filterSettings != value)
{
filterSettings = value;
RaisePropertyChanged(nameof(FilterSettings));
}
}
}
public Language Language {
get => filterSettings.Language;
set => filterSettings.Language = value;
}
public LanguageVersion LanguageVersion {
get => filterSettings.LanguageVersion;
set => filterSettings.LanguageVersion = value;
}
private bool supportsLanguageSwitching = true;
public bool SupportsLanguageSwitching {
get => supportsLanguageSwitching;
set {
if (supportsLanguageSwitching != value)
{
supportsLanguageSwitching = value;
RaisePropertyChanged(nameof(SupportsLanguageSwitching));
}
}
}
private object content;
public object Content {
get => content;
set {
if (content != value)
{
content = value;
RaisePropertyChanged(nameof(Content));
}
}
}
public ViewState GetState()
{
return (Content as IHaveState)?.GetState();
}
}
public static class TabPageModelExtensions
{
public static Task<T> ShowTextViewAsync<T>(this TabPageModel tabPage, Func<DecompilerTextView, Task<T>> action)
{
if (!(tabPage.Content is DecompilerTextView textView))
{
textView = new DecompilerTextView();
tabPage.Content = textView;
}
tabPage.Title = Properties.Resources.Decompiling;
return action(textView);
}
public static Task ShowTextViewAsync(this TabPageModel tabPage, Func<DecompilerTextView, Task> action)
{
if (!(tabPage.Content is DecompilerTextView textView))
{
textView = new DecompilerTextView();
tabPage.Content = textView;
}
tabPage.Title = Properties.Resources.Decompiling;
return action(textView);
}
public static void ShowTextView(this TabPageModel tabPage, Action<DecompilerTextView> action)
{
if (!(tabPage.Content is DecompilerTextView textView))
{
textView = new DecompilerTextView();
tabPage.Content = textView;
}
tabPage.Title = Properties.Resources.Decompiling;
action(textView);
}
}
public interface IHaveState
{
ViewState GetState();
}
} | ILSpy/ILSpy/ViewModels/TabPageModel.cs/0 | {
"file_path": "ILSpy/ILSpy/ViewModels/TabPageModel.cs",
"repo_id": "ILSpy",
"token_count": 1220
} | 280 |
// Copyright (c) 2020 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.Runtime.InteropServices;
using System.Windows;
using System.Windows.Threading;
namespace ICSharpCode.TreeView
{
/// <summary>
/// Custom TextSearch-implementation.
/// Fixes #67 - Moving to class member in tree view by typing in first character of member name selects parent assembly
/// </summary>
public class SharpTreeViewTextSearch : DependencyObject
{
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
static extern int GetDoubleClickTime();
static readonly DependencyPropertyKey TextSearchInstancePropertyKey = DependencyProperty.RegisterAttachedReadOnly("TextSearchInstance",
typeof(SharpTreeViewTextSearch), typeof(SharpTreeViewTextSearch), new FrameworkPropertyMetadata(null));
static readonly DependencyProperty TextSearchInstanceProperty = TextSearchInstancePropertyKey.DependencyProperty;
DispatcherTimer timer;
bool isActive;
int lastMatchIndex;
string matchPrefix;
readonly Stack<string> inputStack;
readonly SharpTreeView treeView;
private SharpTreeViewTextSearch(SharpTreeView treeView)
{
if (treeView == null)
throw new ArgumentNullException(nameof(treeView));
this.treeView = treeView;
inputStack = new Stack<string>(8);
ClearState();
}
public static SharpTreeViewTextSearch GetInstance(SharpTreeView sharpTreeView)
{
var textSearch = (SharpTreeViewTextSearch)sharpTreeView.GetValue(TextSearchInstanceProperty);
if (textSearch == null)
{
textSearch = new SharpTreeViewTextSearch(sharpTreeView);
sharpTreeView.SetValue(TextSearchInstancePropertyKey, textSearch);
}
return textSearch;
}
public bool RevertLastCharacter()
{
if (!isActive || inputStack.Count == 0)
return false;
matchPrefix = matchPrefix.Substring(0, matchPrefix.Length - inputStack.Pop().Length);
ResetTimeout();
return true;
}
public bool Search(string nextChar)
{
int startIndex = isActive ? lastMatchIndex : Math.Max(0, treeView.SelectedIndex);
bool lookBackwards = inputStack.Count > 0 && string.Compare(inputStack.Peek(), nextChar, StringComparison.OrdinalIgnoreCase) == 0;
int nextMatchIndex = IndexOfMatch(matchPrefix + nextChar, startIndex, lookBackwards, out bool wasNewCharUsed);
if (nextMatchIndex != -1)
{
if (!isActive || nextMatchIndex != startIndex)
{
treeView.SelectedItem = treeView.Items[nextMatchIndex];
treeView.FocusNode((SharpTreeNode)treeView.SelectedItem);
lastMatchIndex = nextMatchIndex;
}
if (wasNewCharUsed)
{
matchPrefix += nextChar;
inputStack.Push(nextChar);
}
isActive = true;
}
if (isActive)
{
ResetTimeout();
}
return nextMatchIndex != -1;
}
int IndexOfMatch(string needle, int startIndex, bool tryBackward, out bool charWasUsed)
{
charWasUsed = false;
if (treeView.Items.Count == 0 || string.IsNullOrEmpty(needle))
return -1;
int index = -1;
int fallbackIndex = -1;
bool fallbackMatch = false;
int i = startIndex;
var comparisonType = treeView.IsTextSearchCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
do
{
var item = (SharpTreeNode)treeView.Items[i];
if (item != null && item.Text != null)
{
string text = item.Text.ToString();
if (text.StartsWith(needle, comparisonType))
{
charWasUsed = true;
index = i;
break;
}
if (tryBackward)
{
if (fallbackMatch && matchPrefix != string.Empty)
{
if (fallbackIndex == -1 && text.StartsWith(matchPrefix, comparisonType))
{
fallbackIndex = i;
}
}
else
{
fallbackMatch = true;
}
}
}
i++;
if (i >= treeView.Items.Count)
i = 0;
} while (i != startIndex);
return index == -1 ? fallbackIndex : index;
}
void ClearState()
{
isActive = false;
matchPrefix = string.Empty;
lastMatchIndex = -1;
inputStack.Clear();
timer?.Stop();
timer = null;
}
void ResetTimeout()
{
if (timer == null)
{
timer = new DispatcherTimer(DispatcherPriority.Normal);
timer.Tick += (sender, e) => ClearState();
}
else
{
timer.Stop();
}
timer.Interval = TimeSpan.FromMilliseconds(GetDoubleClickTime() * 2);
timer.Start();
}
}
} | ILSpy/SharpTreeView/SharpTreeViewTextSearch.cs/0 | {
"file_path": "ILSpy/SharpTreeView/SharpTreeViewTextSearch.cs",
"repo_id": "ILSpy",
"token_count": 1950
} | 281 |
@setlocal enabledelayedexpansion
@set MSBUILD=
@for /D %%M in ("%ProgramFiles%\Microsoft Visual Studio\2022"\*) do @(
@if exist "%%M\MSBuild\Current\Bin\MSBuild.exe" (
@set "MSBUILD=%%M\MSBuild\Current\Bin\MSBuild.exe"
)
)
@if "%MSBUILD%" == "" (
@echo Could not find VS2022 MSBuild
@exit /b 1
)
@nuget restore ILSpy.sln || (pause && exit /b 1)
"%MSBUILD%" ILSpy.sln /p:Configuration=Debug "/p:Platform=Any CPU" || (pause && exit /b 1)
| ILSpy/debugbuild.bat/0 | {
"file_path": "ILSpy/debugbuild.bat",
"repo_id": "ILSpy",
"token_count": 198
} | 282 |
// 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.U2D.Interface;
namespace UnityEditor.U2D.Common
{
internal class TexturePlatformSettingsView : ITexturePlatformSettingsView
{
class Styles
{
public readonly GUIContent textureFormatLabel = EditorGUIUtility.TrTextContent("Format");
public readonly GUIContent maxTextureSizeLabel = EditorGUIUtility.TrTextContent("Max Texture Size", "Maximum size of the packed texture.");
public readonly GUIContent compressionLabel = EditorGUIUtility.TrTextContent("Compression", "How will this texture be compressed?");
public readonly GUIContent useCrunchedCompressionLabel = EditorGUIUtility.TrTextContent("Use Crunch Compression", "Texture is crunch-compressed to save space on disk when applicable.");
public readonly GUIContent useAlphaSplitLabel = EditorGUIUtility.TrTextContent("Split Alpha Channel", "Alpha for this texture will be preserved by splitting the alpha channel to another texture, and both resulting textures will be compressed using ETC1.");
public readonly GUIContent compressionQualityLabel = EditorGUIUtility.TrTextContent("Compressor Quality");
public readonly GUIContent compressionQualitySliderLabel = EditorGUIUtility.TrTextContent("Compressor Quality", "Use the slider to adjust compression quality from 0 (Fastest) to 100 (Best)");
public readonly int[] kMaxTextureSizeValues = { 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 };
public readonly GUIContent[] kMaxTextureSizeStrings;
public readonly GUIContent[] kTextureCompressionOptions =
{
EditorGUIUtility.TrTextContent("None", "Texture is not compressed."),
EditorGUIUtility.TrTextContent("Low Quality", "Texture compressed with low quality but high performance, high compression format."),
EditorGUIUtility.TrTextContent("Normal Quality", "Texture is compressed with a standard format."),
EditorGUIUtility.TrTextContent("High Quality", "Texture compressed with a high quality format."),
};
public readonly int[] kTextureCompressionValues =
{
(int)TextureImporterCompression.Uncompressed,
(int)TextureImporterCompression.CompressedLQ,
(int)TextureImporterCompression.Compressed,
(int)TextureImporterCompression.CompressedHQ
};
public readonly GUIContent[] kMobileCompressionQualityOptions =
{
EditorGUIUtility.TrTextContent("Fast"),
EditorGUIUtility.TrTextContent("Normal"),
EditorGUIUtility.TrTextContent("Best")
};
public Styles()
{
kMaxTextureSizeStrings = new GUIContent[kMaxTextureSizeValues.Length];
for (var i = 0; i < kMaxTextureSizeValues.Length; ++i)
kMaxTextureSizeStrings[i] = EditorGUIUtility.TextContent(string.Format("{0}", kMaxTextureSizeValues[i]));
}
}
private static Styles s_Styles;
public string buildPlatformTitle { get; set; }
internal TexturePlatformSettingsView()
{
s_Styles = s_Styles ?? new Styles();
}
public virtual TextureImporterCompression DrawCompression(TextureImporterCompression defaultValue, bool isMixedValue, bool isDisabled, out bool changed)
{
using (new EditorGUI.DisabledScope(isDisabled))
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = isMixedValue;
defaultValue = (TextureImporterCompression)EditorGUILayout.IntPopup(s_Styles.compressionLabel,
(int)defaultValue, s_Styles.kTextureCompressionOptions, s_Styles.kTextureCompressionValues);
EditorGUI.showMixedValue = false;
changed = EditorGUI.EndChangeCheck();
return defaultValue;
}
}
public virtual bool DrawUseCrunchedCompression(bool defaultValue, bool isMixedValue, bool isDisabled, out bool changed)
{
using (new EditorGUI.DisabledScope(isDisabled))
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = isMixedValue;
defaultValue = EditorGUILayout.Toggle(s_Styles.useCrunchedCompressionLabel, defaultValue);
EditorGUI.showMixedValue = false;
changed = EditorGUI.EndChangeCheck();
return defaultValue;
}
}
public virtual bool DrawOverride(bool defaultValue, bool isMixedValue, out bool changed)
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = isMixedValue;
defaultValue = EditorGUILayout.ToggleLeft(EditorGUIUtility.TempContent("Override for " + buildPlatformTitle), defaultValue);
EditorGUI.showMixedValue = false;
changed = EditorGUI.EndChangeCheck();
return defaultValue;
}
public virtual int DrawMaxSize(int defaultValue, bool isMixedValue, bool isDisabled, out bool changed)
{
using (new EditorGUI.DisabledScope(isDisabled))
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = isMixedValue;
defaultValue = EditorGUILayout.IntPopup(s_Styles.maxTextureSizeLabel, defaultValue,
s_Styles.kMaxTextureSizeStrings, s_Styles.kMaxTextureSizeValues);
EditorGUI.showMixedValue = false;
changed = EditorGUI.EndChangeCheck();
return defaultValue;
}
}
public virtual TextureImporterFormat DrawFormat(TextureImporterFormat defaultValue, int[] displayValues, string[] displayStrings, bool isMixedValue, bool isDisabled, out bool changed)
{
using (new EditorGUI.DisabledScope(isDisabled))
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = isMixedValue;
defaultValue = (TextureImporterFormat)EditorGUILayout.IntPopup(s_Styles.textureFormatLabel, (int)defaultValue, EditorGUIUtility.TempContent(displayStrings), displayValues);
EditorGUI.showMixedValue = false;
changed = EditorGUI.EndChangeCheck();
return defaultValue;
}
}
public virtual int DrawCompressionQualityPopup(int defaultValue, bool isMixedValue, bool isDisabled, out bool changed)
{
using (new EditorGUI.DisabledScope(isDisabled))
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = isMixedValue;
defaultValue = EditorGUILayout.Popup(s_Styles.compressionQualityLabel, defaultValue,
s_Styles.kMobileCompressionQualityOptions);
EditorGUI.showMixedValue = false;
changed = EditorGUI.EndChangeCheck();
return defaultValue;
}
}
public virtual int DrawCompressionQualitySlider(int defaultValue, bool isMixedValue, bool isDisabled, out bool changed)
{
using (new EditorGUI.DisabledScope(isDisabled))
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = isMixedValue;
defaultValue = EditorGUILayout.IntSlider(s_Styles.compressionQualitySliderLabel, defaultValue, 0, 100);
EditorGUI.showMixedValue = false;
changed = EditorGUI.EndChangeCheck();
return defaultValue;
}
}
public virtual bool DrawAlphaSplit(bool defaultValue, bool isMixedValue, bool isDisabled, out bool changed)
{
using (new EditorGUI.DisabledScope(isDisabled))
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = isMixedValue;
defaultValue = EditorGUILayout.Toggle(s_Styles.useAlphaSplitLabel, defaultValue);
EditorGUI.showMixedValue = false;
changed = EditorGUI.EndChangeCheck();
return defaultValue;
}
}
}
}
| UnityCsReference/Editor/Mono/2D/Common/TexturePlatformSettingsView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/2D/Common/TexturePlatformSettingsView.cs",
"repo_id": "UnityCsReference",
"token_count": 3568
} | 283 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System;
using System.Linq;
using UnityEditor.IMGUI.Controls;
using Object = UnityEngine.Object;
namespace UnityEditorInternal
{
struct AddCurvesPopupHierarchyBuilder
{
struct KeyComparer : IComparer<Key>
{
static readonly Type s_GameObjectType = typeof(GameObject);
static readonly Type s_TransformType = typeof(Transform);
public int Compare(Key x, Key y)
{
var result = String.Compare(x.path, y.path, StringComparison.Ordinal);
if (result == 0 && x.type != y.type)
{
// Make sure GameObject properties appear first, then Transform.
if (x.type == s_GameObjectType)
return -1;
if (y.type == s_GameObjectType)
return 1;
if (x.type == typeof(Transform))
return -1;
if (y.type == typeof(Transform))
return 1;
return String.Compare(x.type.Name, y.type.Name, StringComparison.Ordinal);
}
return result;
}
}
struct Key
{
public string path;
public Type type;
}
SortedDictionary<Key, List<EditorCurveBinding>> m_AccumulatedBindings;
AnimationWindowState m_State;
public AddCurvesPopupHierarchyBuilder(AnimationWindowState state)
{
m_AccumulatedBindings = new SortedDictionary<Key, List<EditorCurveBinding>>(new KeyComparer());
m_State = state;
}
public void Add(EditorCurveBinding binding)
{
var key = new Key { path = binding.path, type = binding.type };
if (m_AccumulatedBindings.TryGetValue(key, out var bindings))
bindings.Add(binding);
else
m_AccumulatedBindings[key] = new List<EditorCurveBinding>(new [] {binding});
}
void RemoveUnnecessaryBindings(List<EditorCurveBinding> bindings)
{
for (int i = bindings.Count - 1; i >= 0; --i)
{
// Let's not add those that already have a existing curve.
if (AnimationWindowUtility.IsCurveCreated(m_State.activeAnimationClip, bindings[i]))
bindings.RemoveAt(i);
// Remove animator enabled property which shouldn't be animated.
else if (bindings[i].type == typeof(Animator) && bindings[i].propertyName == "m_Enabled")
bindings.RemoveAt(i);
// For RectTransform.position we only want .z
else if (AnimationWindowUtility.IsRectTransformPosition(bindings[i]) && !bindings[i].propertyName.EndsWith(".z"))
bindings.RemoveAt(i);
// Don't show for the root go
else if (bindings[i].type == typeof(GameObject) && string.IsNullOrEmpty(bindings[i].path))
bindings.RemoveAt(i);
}
}
public TreeViewItem CreateTreeView()
{
TreeViewItem rootNode;
// Bindings of a single Component/ScriptableObject, skip the group node.
if (m_AccumulatedBindings.Count == 1)
{
var bindings = m_AccumulatedBindings.First().Value;
RemoveUnnecessaryBindings(bindings);
if (bindings.Count > 0)
{
rootNode = AddAnimatableObjectToHierarchy(bindings, null, "");
}
else
{
rootNode = new AddCurvesPopupObjectNode(null, string.Empty, string.Empty);
}
}
else
{
var groupNodes = new Dictionary<string, TreeViewItem>();
var childNodes = new Dictionary<TreeViewItem, List<TreeViewItem>>();
var inheritedNodeWeights = new Dictionary<TreeViewItem, int>();
rootNode = new AddCurvesPopupObjectNode(null, string.Empty, string.Empty);
TreeViewItem groupNode = rootNode;
groupNodes.Add(string.Empty, (rootNode));
childNodes.Add(groupNode, new List<TreeViewItem>());
inheritedNodeWeights.Add(groupNode, 0);
string currentPath = string.Empty;
foreach (var kvp in m_AccumulatedBindings)
{
if (!currentPath.Equals(kvp.Key.path))
{
TreeViewItem parentNode = rootNode;
var parentPath = GetParentPath(kvp.Key.path);
while (parentPath != null)
{
if (groupNodes.TryGetValue(parentPath, out var node))
{
parentNode = node;
break;
}
parentPath = GetParentPath(parentPath);
}
groupNode = new AddCurvesPopupObjectNode(parentNode, kvp.Key.path, "", GetObjectName(kvp.Key.path));
groupNodes.Add(kvp.Key.path, groupNode);
childNodes.Add(groupNode, new List<TreeViewItem>());
inheritedNodeWeights.Add(groupNode, 0);
childNodes[parentNode].Add(groupNode);
currentPath = kvp.Key.path;
}
var bindings = kvp.Value;
RemoveUnnecessaryBindings(bindings);
if (bindings.Count > 0)
{
// Builtin GameObject attributes.
if (kvp.Key.type == typeof(GameObject))
{
TreeViewItem newNode = CreateNode(bindings.ToArray(), groupNode, null);
if (newNode != null)
childNodes[groupNode].Add(newNode);
}
else
{
childNodes[groupNode].Add(AddAnimatableObjectToHierarchy(bindings, groupNode, kvp.Key.path));
var parentGroupNode = groupNode;
while (parentGroupNode != null)
{
inheritedNodeWeights[parentGroupNode] += bindings.Count;
parentGroupNode = parentGroupNode.parent;
}
}
}
}
// Remove empty leaves from tree view.
foreach (var kvp in inheritedNodeWeights)
{
// Remove Leaves nodes without properties.
if (inheritedNodeWeights[kvp.Key] == 0 && kvp.Key.parent != null)
{
childNodes[kvp.Key.parent].Remove(kvp.Key);
kvp.Key.parent = null;
}
}
// Set child parent references.
foreach (var kvp in childNodes)
{
TreeViewUtility.SetChildParentReferences(kvp.Value, kvp.Key);
}
}
m_AccumulatedBindings.Clear();
return rootNode;
}
private string GetParentPath(string path)
{
if (String.IsNullOrEmpty(path))
return null;
int index = path.LastIndexOf('/');
if (index == -1)
return string.Empty;
return path.Substring(0, index);
}
private string GetObjectName(string path)
{
if (String.IsNullOrEmpty(path))
return null;
int index = path.LastIndexOf('/');
if (index == -1)
return path;
return path.Substring(index + 1);
}
private string GetClassName(EditorCurveBinding binding)
{
if (m_State.activeRootGameObject != null)
{
Object target = AnimationUtility.GetAnimatedObject(m_State.activeRootGameObject, binding);
if (target != null)
return ObjectNames.GetInspectorTitle(target);
}
return binding.type.Name;
}
private Texture2D GetIcon(EditorCurveBinding binding)
{
return AssetPreview.GetMiniTypeThumbnail(binding.type);
}
private TreeViewItem AddAnimatableObjectToHierarchy(List<EditorCurveBinding> curveBindings, TreeViewItem parentNode, string path)
{
TreeViewItem node = new AddCurvesPopupObjectNode(parentNode, path, GetClassName(curveBindings[0]));
node.icon = GetIcon(curveBindings[0]);
List<TreeViewItem> childNodes = new List<TreeViewItem>();
List<EditorCurveBinding> singlePropertyBindings = new List<EditorCurveBinding>();
SerializedObject so = null;
for (int i = 0; i < curveBindings.Count; i++)
{
EditorCurveBinding curveBinding = curveBindings[i];
if (m_State.activeRootGameObject && curveBinding.isSerializeReferenceCurve)
{
var animatedObject = AnimationUtility.GetAnimatedObject(m_State.activeRootGameObject, curveBinding);
if (animatedObject != null && (so == null || so.targetObject != animatedObject))
so = new SerializedObject(animatedObject);
}
singlePropertyBindings.Add(curveBinding);
// We expect curveBindings to come sorted by propertyname
if (i == curveBindings.Count - 1 || AnimationWindowUtility.GetPropertyGroupName(curveBindings[i + 1].propertyName) != AnimationWindowUtility.GetPropertyGroupName(curveBinding.propertyName))
{
TreeViewItem newNode = CreateNode(singlePropertyBindings.ToArray(), node, so);
if (newNode != null)
childNodes.Add(newNode);
singlePropertyBindings.Clear();
}
}
childNodes.Sort();
TreeViewUtility.SetChildParentReferences(childNodes, node);
return node;
}
private TreeViewItem CreateNode(EditorCurveBinding[] curveBindings, TreeViewItem parentNode, SerializedObject so)
{
var node = new AddCurvesPopupPropertyNode(parentNode, curveBindings, AnimationWindowUtility.GetNicePropertyGroupDisplayName(curveBindings[0], so));
node.icon = parentNode.icon;
return node;
}
}
class AddCurvesPopupObjectNode : TreeViewItem
{
public AddCurvesPopupObjectNode(TreeViewItem parent, string path, string className, string displayName = null)
: base((path + className).GetHashCode(), parent != null ? parent.depth + 1 : -1, parent, displayName ?? className)
{
}
}
class AddCurvesPopupPropertyNode : TreeViewItem
{
public EditorCurveBinding[] curveBindings;
public AddCurvesPopupPropertyNode(TreeViewItem parent, EditorCurveBinding[] curveBindings, string displayName)
: base(curveBindings[0].GetHashCode(), parent.depth + 1, parent, displayName)
{
this.curveBindings = curveBindings;
}
public override int CompareTo(TreeViewItem other)
{
AddCurvesPopupPropertyNode otherNode = other as AddCurvesPopupPropertyNode;
if (otherNode != null)
{
if (displayName.Contains("Rotation") && otherNode.displayName.Contains("Position"))
return 1;
if (displayName.Contains("Position") && otherNode.displayName.Contains("Rotation"))
return -1;
}
return base.CompareTo(other);
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyBuilder.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyBuilder.cs",
"repo_id": "UnityCsReference",
"token_count": 6311
} | 284 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Linq;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using System;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[CustomEditor(typeof(AnimationWindowEvent))]
[CanEditMultipleObjects]
internal class AnimationWindowEventInspector : Editor
{
public static GUIContent s_OverloadWarning = EditorGUIUtility.TrTextContent("Some functions were overloaded in MonoBehaviour components and may not work as intended if used with Animation Events!");
public static GUIContent s_DuplicatesWarning = EditorGUIUtility.TrTextContent("Some functions have the same name across several Monobehaviour components and may not work as intended if used with Animation Events!");
const string kNotSupportedPostFix = " (Function Not Supported)";
const string kNoneSelected = "(No Function Selected)";
AnimationEventEditorState m_State = new();
public override void OnInspectorGUI()
{
var awes = targets.Select(o => o as AnimationWindowEvent).ToArray();
OnEditAnimationEvents(awes, m_State);
}
protected override void OnHeaderGUI()
{
string targetTitle = (targets.Length == 1) ? "Animation Event" : targets.Length + " Animation Events";
DrawHeaderGUI(this, targetTitle);
}
public static void OnEditAnimationEvent(AnimationWindowEvent awe, AnimationEventEditorState state)
{
OnEditAnimationEvents(new AnimationWindowEvent[] {awe}, state);
}
// These are used so we don't alloc new lists on every call
static List<AnimationMethodMap> supportedMethods;
static List<AnimationMethodMap> overloads;
static List<AnimationMethodMap> duplicates;
public static void OnEditAnimationEvents(AnimationWindowEvent[] awEvents, AnimationEventEditorState state)
{
AnimationWindowEventData data = GetData(awEvents);
if (data.events == null || data.selectedEvents == null || data.selectedEvents.Length == 0)
return;
AnimationEvent firstEvent = data.selectedEvents[0];
bool singleFunctionName = Array.TrueForAll(data.selectedEvents, evt => evt.functionName == firstEvent.functionName);
EditorGUI.BeginChangeCheck();
if (data.root != null)
{
supportedMethods ??= new List<AnimationMethodMap>();
overloads ??= new List<AnimationMethodMap>();
duplicates ??= new List<AnimationMethodMap>();
supportedMethods.Clear();
overloads.Clear();
duplicates.Clear();
CollectSupportedMethods(data.root, supportedMethods, overloads, duplicates);
int selected = supportedMethods.FindIndex(method => method.Name == firstEvent.functionName);
// A non-empty array used for rendering the contents of the popup
// It is of size 1 greater than the list of supported methods to account for the "None" option
string[] methodsFormatted = new string[supportedMethods.Count + 1];
for (int i = 0; i < supportedMethods.Count; ++i)
{
AnimationMethodMap methodMap = supportedMethods[i];
string menuPath = methodMap.methodMenuPath;
methodsFormatted[i] = menuPath;
}
// Add a final option to set the function to no selected function
int notSupportedIndex = supportedMethods.Count;
if (selected == -1)
{
selected = notSupportedIndex;
// Display that the current function is not supported if applicable
if (string.IsNullOrEmpty(firstEvent.functionName))
methodsFormatted[notSupportedIndex] = kNoneSelected;
else
methodsFormatted[notSupportedIndex] = firstEvent.functionName + kNotSupportedPostFix;
var emptyMethodMap = new AnimationMethodMap();
supportedMethods.Add(emptyMethodMap);
}
EditorGUIUtility.labelWidth = 130;
EditorGUI.showMixedValue = !singleFunctionName;
int wasSelected = singleFunctionName ? selected : -1;
selected = EditorGUILayout.Popup("Function: ", selected, methodsFormatted);
if (wasSelected != selected && selected != -1 && selected != notSupportedIndex)
{
foreach (var evt in data.selectedEvents)
{
evt.functionName = supportedMethods[selected].Name;
evt.stringParameter = string.Empty;
}
}
EditorGUI.showMixedValue = false;
var selectedParameter = supportedMethods[selected].parameterType;
if (singleFunctionName && selectedParameter != null)
{
EditorGUILayout.Space();
if (selectedParameter == typeof(AnimationEvent))
EditorGUILayout.PrefixLabel("Event Data");
else
EditorGUILayout.PrefixLabel("Parameters");
DoEditRegularParameters(data.selectedEvents, selectedParameter);
}
if (overloads.Count > 0)
{
EditorGUILayout.Space();
EditorGUILayout.HelpBox(s_OverloadWarning.text, MessageType.Warning, true);
state.ShowOverloadedFunctionsDetails = EditorGUILayout.Foldout(state.ShowOverloadedFunctionsDetails, "Show Details");
if (state.ShowOverloadedFunctionsDetails)
{
string overloadedFunctionDetails = "Overloaded Functions: \n" + GetFormattedMethodsText(overloads);
GUILayout.Label(overloadedFunctionDetails, EditorStyles.helpBox);
}
}
if (duplicates.Count > 0)
{
EditorGUILayout.Space();
EditorGUILayout.HelpBox(s_DuplicatesWarning.text, MessageType.Warning, true);
state.ShowDuplicatedFunctionsDetails = EditorGUILayout.Foldout(state.ShowDuplicatedFunctionsDetails, "Show Details");
if (state.ShowDuplicatedFunctionsDetails)
{
string duplicatedFunctionDetails = "Duplicated Functions: \n" + GetFormattedMethodsText(duplicates);
GUILayout.Label(duplicatedFunctionDetails, EditorStyles.helpBox);
}
}
}
else
{
EditorGUI.showMixedValue = !singleFunctionName;
string oldFunctionName = singleFunctionName ? firstEvent.functionName : "";
string functionName = EditorGUILayout.TextField(EditorGUIUtility.TrTextContent("Function"), oldFunctionName).Replace(" ", "");
if (functionName != oldFunctionName)
{
foreach (var evt in data.selectedEvents)
{
evt.functionName = functionName;
}
}
EditorGUI.showMixedValue = false;
if (singleFunctionName)
{
DoEditRegularParameters(data.selectedEvents, typeof(AnimationEvent));
}
else
{
using (new EditorGUI.DisabledScope(true))
{
AnimationEvent dummyEvent = new AnimationEvent();
DoEditRegularParameters(new AnimationEvent[] { dummyEvent }, typeof(AnimationEvent));
}
}
}
if (EditorGUI.EndChangeCheck())
SetData(awEvents, data);
}
static string GetFormattedMethodsText(List<AnimationMethodMap> methods)
{
string text = "";
foreach (AnimationMethodMap methodMap in methods)
{
text += string.Format("{0}.{1} ( {2} )\n", methodMap.sourceBehaviour.GetType().Name, methodMap.Name, GetTypeName(methodMap.parameterType));
}
text = text.Trim();
return text;
}
static string GetTypeName(Type t)
{
if (t == null)
return "";
if (t == typeof(int))
return "int";
if (t == typeof(float))
return "float";
if (t == typeof(string))
return "string";
if (t == typeof(bool))
return "bool";
return t.Name;
}
static string GetFormattedMethodName(AnimationMethodMap methodMap)
{
string targetName = methodMap.sourceBehaviour.GetType().Name;
string methodName = methodMap.Name;
string args = GetTypeName(methodMap.parameterType);
if (methodName.StartsWith("set_") || methodName.StartsWith("get_"))
return string.Format("{0}/Properties/{1} ( {2} )", targetName, methodName, args);
else
return string.Format("{0}/Methods/{1} ( {2} )", targetName, methodName, args);
}
public static void OnDisabledAnimationEvent()
{
AnimationEvent dummyEvent = new AnimationEvent();
using (new EditorGUI.DisabledScope(true))
{
dummyEvent.functionName = EditorGUILayout.TextField(EditorGUIUtility.TrTextContent("Function"), dummyEvent.functionName);
DoEditRegularParameters(new AnimationEvent[] { dummyEvent }, typeof(AnimationEvent));
}
}
static Dictionary<Type, IReadOnlyList<AnimationMethodMap>> s_TypeAnimationMethodMapCache = new Dictionary<Type, IReadOnlyList<AnimationMethodMap>>();
static void CollectSupportedMethods(GameObject gameObject, List<AnimationMethodMap> supportedMethods, List<AnimationMethodMap> overloadedMethods, List<AnimationMethodMap> duplicatedMethods)
{
if (gameObject == null)
return;
MonoBehaviour[] behaviours = gameObject.GetComponents<MonoBehaviour>();
foreach (MonoBehaviour behaviour in behaviours)
{
if (behaviour == null)
continue;
Type type = behaviour.GetType();
while (type != typeof(MonoBehaviour) && type != null)
{
if (!s_TypeAnimationMethodMapCache.TryGetValue(type, out IReadOnlyList<AnimationMethodMap> validMethods))
{
var pendingValidMethods = new List<AnimationMethodMap>();
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly );
for (int i = 0; i < methods.Length; i++)
{
MethodInfo method = methods[i];
string name = method.Name;
if (!IsSupportedMethodName(name))
continue;
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length > 1)
continue;
Type parameterType = null;
if (parameters.Length == 1)
{
parameterType = parameters[0].ParameterType;
if (!(parameterType == typeof(string) ||
parameterType == typeof(float) ||
parameterType == typeof(int) ||
parameterType == typeof(AnimationEvent) ||
parameterType == typeof(UnityEngine.Object) ||
parameterType.IsSubclassOf(typeof(UnityEngine.Object)) ||
parameterType.IsEnum))
continue;
}
AnimationMethodMap newMethodMap = new AnimationMethodMap
{
sourceBehaviour = behaviour,
methodInfo = method,
parameterType = parameterType
};
newMethodMap.methodMenuPath = GetFormattedMethodName(newMethodMap);
pendingValidMethods.Add(newMethodMap);
}
validMethods = pendingValidMethods.AsReadOnly();
s_TypeAnimationMethodMapCache.Add(type, validMethods);
}
foreach (var method in validMethods)
{
// Since AnimationEvents only stores method name, it can't handle functions with multiple overloads.
// or functions with the same name across multiple monobehaviours
// Only retrieve first found method, and discard overloads and duplicate names.
int existingMethodIndex = supportedMethods.FindIndex(m => m.Name == method.Name);
if (existingMethodIndex != -1)
{
// The method is only ambiguous if it has a different signature to the one we saw before
if (supportedMethods[existingMethodIndex].parameterType != method.parameterType)
{
overloadedMethods.Add(method);
}
// Otherwise, there is another monobehaviour with the same method name.
else
{
duplicatedMethods.Add(method);
}
}
else
{
supportedMethods.Add(method);
}
}
type = type.BaseType;
}
}
}
/// <summary>
/// Maps the methodInfo and paramter type of a considered animation method to a source monobeheaviour.
/// Mimics the structure of <see cref="UnityEditorInternal.UnityEventDrawer.ValidMethodMap"/>
/// </summary>
struct AnimationMethodMap
{
public Object sourceBehaviour;
public MethodInfo methodInfo;
public Type parameterType;
// Used for caching
public string methodMenuPath;
public string Name => methodInfo?.Name ?? "";
}
public static string FormatEvent(GameObject root, AnimationEvent evt)
{
if (string.IsNullOrEmpty(evt.functionName))
return kNoneSelected;
if (!IsSupportedMethodName(evt.functionName))
return evt.functionName + kNotSupportedPostFix;
if (root == null)
return evt.functionName + kNotSupportedPostFix;
foreach (var behaviour in root.GetComponents<MonoBehaviour>())
{
if (behaviour == null) continue;
var type = behaviour.GetType();
if (type == typeof(MonoBehaviour) ||
(type.BaseType != null && type.BaseType.Name == "GraphBehaviour"))
continue;
MethodInfo method = null;
try
{
method = type.GetMethod(evt.functionName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
}
catch (AmbiguousMatchException)
{
}
if (method == null)
continue;
var parameterTypes = method.GetParameters();
return evt.functionName + FormatEventArguments(parameterTypes, evt);
}
return evt.functionName + kNotSupportedPostFix;
}
private static void DoEditRegularParameters(AnimationEvent[] events, Type selectedParameter)
{
AnimationEvent firstEvent = events[0];
if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(float))
{
bool singleParamValue = Array.TrueForAll(events, evt => evt.floatParameter == firstEvent.floatParameter);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = !singleParamValue;
float newValue = EditorGUILayout.FloatField("Float", firstEvent.floatParameter);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
foreach (var evt in events)
evt.floatParameter = newValue;
}
}
if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(int) || selectedParameter.IsEnum)
{
bool singleParamValue = Array.TrueForAll(events, evt => evt.intParameter == firstEvent.intParameter);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = !singleParamValue;
int newValue = 0;
if (selectedParameter.IsEnum)
newValue = EnumPopup("Enum", selectedParameter, firstEvent.intParameter);
else
newValue = EditorGUILayout.IntField("Int", firstEvent.intParameter);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
foreach (var evt in events)
evt.intParameter = newValue;
}
}
if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(string))
{
bool singleParamValue = Array.TrueForAll(events, evt => evt.stringParameter == firstEvent.stringParameter);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = !singleParamValue;
string newValue = EditorGUILayout.TextField("String", firstEvent.stringParameter);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
foreach (var evt in events)
evt.stringParameter = newValue;
}
}
if (selectedParameter == typeof(AnimationEvent) || selectedParameter.IsSubclassOf(typeof(UnityEngine.Object)) || selectedParameter == typeof(UnityEngine.Object))
{
bool singleParamValue = Array.TrueForAll(events, evt => evt.objectReferenceParameter == firstEvent.objectReferenceParameter);
EditorGUI.BeginChangeCheck();
Type type = typeof(UnityEngine.Object);
if (selectedParameter != typeof(AnimationEvent))
type = selectedParameter;
EditorGUI.showMixedValue = !singleParamValue;
bool allowSceneObjects = false;
Object newValue = EditorGUILayout.ObjectField(ObjectNames.NicifyVariableName(type.Name), firstEvent.objectReferenceParameter, type, allowSceneObjects);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
foreach (var evt in events)
evt.objectReferenceParameter = newValue;
}
}
}
private static int EnumPopup(string label, Type enumType, int selected)
{
if (!enumType.IsEnum)
throw new Exception("parameter _enum must be of type System.Enum");
string[] enumStrings = System.Enum.GetNames(enumType);
int i = System.Array.IndexOf(enumStrings, Enum.GetName(enumType, selected));
i = EditorGUILayout.Popup(label, i, enumStrings, EditorStyles.popup);
if (i == -1)
return selected;
else
{
System.Enum res = (System.Enum)Enum.Parse(enumType, enumStrings[i]);
return Convert.ToInt32(res);
}
}
private static bool IsSupportedMethodName(string name)
{
return name != "Main" && name != "Start" && name != "Awake" && name != "Update";
}
private static string FormatEventArguments(ParameterInfo[] paramTypes, AnimationEvent evt)
{
if (paramTypes.Length == 0)
return " ( )";
if (paramTypes.Length > 1)
return kNotSupportedPostFix;
var paramType = paramTypes[0].ParameterType;
if (paramType == typeof(string))
return " ( \"" + evt.stringParameter + "\" )";
if (paramType == typeof(float))
return " ( " + evt.floatParameter + " )";
if (paramType == typeof(int))
return " ( " + evt.intParameter + " )";
if (paramType.IsEnum)
return " ( " + paramType.Name + "." + Enum.GetName(paramType, evt.intParameter) + " )";
if (paramType == typeof(AnimationEvent))
return " ( "
+ evt.floatParameter + " / "
+ evt.intParameter + " / \""
+ evt.stringParameter + "\" / "
+ (evt.objectReferenceParameter == null ? "null" : evt.objectReferenceParameter.name) + " )";
if (paramType.IsSubclassOf(typeof(UnityEngine.Object)) || paramType == typeof(UnityEngine.Object))
return " ( " + (evt.objectReferenceParameter == null ? "null" : evt.objectReferenceParameter.name) + " )";
return kNotSupportedPostFix;
}
private struct AnimationWindowEventData
{
public GameObject root;
public AnimationClip clip;
public AnimationClipInfoProperties clipInfo;
public AnimationEvent[] events;
public AnimationEvent[] selectedEvents;
}
// this are used so we don't alloc new lists on every call
static List<AnimationEvent> getDataSelectedEvents;
private static AnimationWindowEventData GetData(AnimationWindowEvent[] awEvents)
{
var data = new AnimationWindowEventData();
if (awEvents.Length == 0)
return data;
AnimationWindowEvent firstAwEvent = awEvents[0];
data.root = firstAwEvent.root;
data.clip = firstAwEvent.clip;
data.clipInfo = firstAwEvent.clipInfo;
if (data.clip != null)
data.events = AnimationUtility.GetAnimationEvents(data.clip);
else if (data.clipInfo != null)
data.events = data.clipInfo.GetEvents();
if (data.events != null)
{
getDataSelectedEvents ??= new List<AnimationEvent>();
getDataSelectedEvents.Clear();
foreach (var awEvent in awEvents)
{
if (awEvent.eventIndex >= 0 && awEvent.eventIndex < data.events.Length)
getDataSelectedEvents.Add(data.events[awEvent.eventIndex]);
}
data.selectedEvents = getDataSelectedEvents.ToArray();
}
return data;
}
private static void SetData(AnimationWindowEvent[] awEvents, AnimationWindowEventData data)
{
if (data.events == null)
return;
if (data.clip != null)
{
Undo.RegisterCompleteObjectUndo(data.clip, "Animation Event Change");
AnimationUtility.SetAnimationEvents(data.clip, data.events);
}
else if (data.clipInfo != null)
{
foreach (var awEvent in awEvents)
{
if (awEvent.eventIndex >= 0 && awEvent.eventIndex < data.events.Length)
data.clipInfo.SetEvent(awEvent.eventIndex, data.events[awEvent.eventIndex]);
}
}
}
[MenuItem("CONTEXT/AnimationWindowEvent/Reset", secondaryPriority = 7)]
static void ResetValues(MenuCommand command)
{
AnimationWindowEvent awEvent = command.context as AnimationWindowEvent;
AnimationWindowEvent[] awEvents = new AnimationWindowEvent[] { awEvent };
AnimationWindowEventData data = GetData(awEvents);
if (data.events == null || data.selectedEvents == null || data.selectedEvents.Length == 0)
return;
foreach (var evt in data.selectedEvents)
{
evt.functionName = "";
evt.stringParameter = string.Empty;
evt.floatParameter = 0f;
evt.intParameter = 0;
evt.objectReferenceParameter = null;
}
SetData(awEvents, data);
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowEventInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowEventInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 12525
} | 285 |
// 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;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using RectangleToolFlags = UnityEditor.CurveEditorSettings.RectangleToolFlags;
namespace UnityEditor
{
internal class CurveEditorRectangleTool : RectangleTool
{
const int kHBarMinWidth = 14;
const int kHBarHeight = 13;
const int kHBarLeftWidth = 15;
const int kHBarLeftHeight = 13;
const int kHBarRightWidth = 15;
const int kHBarRightHeight = 13;
const int kHLabelMarginHorizontal = 3;
const int kHLabelMarginVertical = 1;
const int kVBarMinHeight = 15;
const int kVBarWidth = 13;
const int kVBarBottomWidth = 13;
const int kVBarBottomHeight = 15;
const int kVBarTopWidth = 13;
const int kVBarTopHeight = 15;
const int kVLabelMarginHorizontal = 1;
const int kVLabelMarginVertical = 2;
const int kScaleLeftWidth = 17;
const int kScaleLeftMarginHorizontal = 0;
const float kScaleLeftRatio = 0.80f;
const int kScaleRightWidth = 17;
const int kScaleRightMarginHorizontal = 0;
const float kScaleRightRatio = 0.80f;
const int kScaleBottomHeight = 17;
const int kScaleBottomMarginVertical = 0;
const float kScaleBottomRatio = 0.80f;
const int kScaleTopHeight = 17;
const int kScaleTopMarginVertical = 0;
const float kScaleTopRatio = 0.80f;
static Rect g_EmptyRect = new Rect(0f, 0f, 0f, 0f);
struct ToolLayout
{
public Rect selectionRect;
public Rect hBarRect;
public Rect hBarLeftRect;
public Rect hBarRightRect;
public bool displayHScale;
public Rect vBarRect;
public Rect vBarBottomRect;
public Rect vBarTopRect;
public bool displayVScale;
public Rect selectionLeftRect;
public Rect selectionTopRect;
public Rect underlayTopRect;
public Rect underlayLeftRect;
public Rect scaleLeftRect;
public Rect scaleRightRect;
public Rect scaleTopRect;
public Rect scaleBottomRect;
public Vector2 leftLabelAnchor;
public Vector2 rightLabelAnchor;
public Vector2 bottomLabelAnchor;
public Vector2 topLabelAnchor;
}
private CurveEditor m_CurveEditor;
private ToolLayout m_Layout;
private Vector2 m_Pivot;
private Vector2 m_Previous;
private Vector2 m_MouseOffset;
enum DragMode
{
None = 0,
MoveHorizontal = 1 << 0,
MoveVertical = 1 << 1,
MoveBothAxis = MoveHorizontal | MoveVertical,
ScaleHorizontal = 1 << 2,
ScaleVertical = 1 << 3,
ScaleBothAxis = ScaleHorizontal | ScaleVertical,
MoveScaleHorizontal = MoveHorizontal | ScaleHorizontal,
MoveScaleVertical = MoveVertical | ScaleVertical
}
private DragMode m_DragMode;
private bool m_RippleTime;
private float m_RippleTimeStart;
private float m_RippleTimeEnd;
private AreaManipulator m_HBarLeft;
private AreaManipulator m_HBarRight;
private AreaManipulator m_HBar;
private AreaManipulator m_VBarBottom;
private AreaManipulator m_VBarTop;
private AreaManipulator m_VBar;
private AreaManipulator m_SelectionBox;
private AreaManipulator m_SelectionScaleLeft;
private AreaManipulator m_SelectionScaleRight;
private AreaManipulator m_SelectionRippleLeft;
private AreaManipulator m_SelectionRippleRight;
private AreaManipulator m_SelectionScaleBottom;
private AreaManipulator m_SelectionScaleTop;
private bool hasSelection { get { return m_CurveEditor.hasSelection && !m_CurveEditor.IsDraggingCurveOrRegion(); } }
private Bounds selectionBounds { get { return m_CurveEditor.selectionBounds; } }
private float frameRate { get { return m_CurveEditor.invSnap; } }
private bool rippleTime { get { return m_CurveEditor.rippleTime; } }
private DragMode dragMode
{
get
{
if (m_DragMode != DragMode.None)
return m_DragMode;
if (m_CurveEditor.IsDraggingKey())
return DragMode.MoveBothAxis;
return DragMode.None;
}
}
public override void Initialize(TimeArea timeArea)
{
base.Initialize(timeArea);
m_CurveEditor = timeArea as CurveEditor;
if (m_HBarLeft == null)
{
m_HBarLeft = new AreaManipulator(styles.rectangleToolHBarLeft, MouseCursor.ResizeHorizontal);
m_HBarLeft.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Right, ToolCoord.Left, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), DragMode.ScaleHorizontal, rippleTime);
return true;
}
return false;
};
m_HBarLeft.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_HBarLeft.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_HBarRight == null)
{
m_HBarRight = new AreaManipulator(styles.rectangleToolHBarRight, MouseCursor.ResizeHorizontal);
m_HBarRight.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Left, ToolCoord.Right, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), DragMode.ScaleHorizontal, rippleTime);
return true;
}
return false;
};
m_HBarRight.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_HBarRight.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_HBar == null)
{
m_HBar = new AreaManipulator(styles.rectangleToolHBar, MouseCursor.MoveArrow);
m_HBar.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartMove(new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), DragMode.MoveHorizontal, rippleTime);
return true;
}
return false;
};
m_HBar.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnMove(new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f));
return true;
};
m_HBar.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndMove();
return true;
};
}
if (m_VBarBottom == null)
{
m_VBarBottom = new AreaManipulator(styles.rectangleToolVBarBottom, MouseCursor.ResizeVertical);
m_VBarBottom.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Top, ToolCoord.Bottom, new Vector2(0f, PixelToValue(evt.mousePosition.y)), DragMode.ScaleVertical, false);
return true;
}
return false;
};
m_VBarBottom.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleValue(PixelToValue(evt.mousePosition.y));
return true;
};
m_VBarBottom.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_VBarTop == null)
{
m_VBarTop = new AreaManipulator(styles.rectangleToolVBarTop, MouseCursor.ResizeVertical);
m_VBarTop.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Bottom, ToolCoord.Top, new Vector2(0f, PixelToValue(evt.mousePosition.y)), DragMode.ScaleVertical, false);
return true;
}
return false;
};
m_VBarTop.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleValue(PixelToValue(evt.mousePosition.y));
return true;
};
m_VBarTop.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_VBar == null)
{
m_VBar = new AreaManipulator(styles.rectangleToolVBar, MouseCursor.MoveArrow);
m_VBar.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartMove(new Vector2(0f, PixelToValue(evt.mousePosition.y)), DragMode.MoveVertical, false);
return true;
}
return false;
};
m_VBar.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnMove(new Vector2(0f, PixelToValue(evt.mousePosition.y)));
return true;
};
m_VBar.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndMove();
return true;
};
}
if (m_SelectionBox == null)
{
m_SelectionBox = new AreaManipulator(styles.rectangleToolSelection, MouseCursor.MoveArrow);
m_SelectionBox.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
bool curveEditorOverride = evt.shift || EditorGUI.actionKey;
if (!curveEditorOverride && hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartMove(new Vector2(PixelToTime(evt.mousePosition.x, frameRate), PixelToValue(evt.mousePosition.y)), DragMode.MoveBothAxis, rippleTime);
return true;
}
return false;
};
m_SelectionBox.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
// Only drag along x OR y when shift is held down
if (evt.shift && m_DragMode == DragMode.MoveBothAxis)
{
float deltaX = evt.mousePosition.x - TimeToPixel(m_Previous.x);
float deltaY = evt.mousePosition.y - ValueToPixel(m_Previous.y);
m_DragMode = Mathf.Abs(deltaX) > Mathf.Abs(deltaY) ? DragMode.MoveHorizontal : DragMode.MoveVertical;
}
float posX = ((m_DragMode & DragMode.MoveHorizontal) != 0) ? PixelToTime(evt.mousePosition.x, frameRate) : m_Previous.x;
float posY = ((m_DragMode & DragMode.MoveVertical) != 0) ? PixelToValue(evt.mousePosition.y) : m_Previous.y;
OnMove(new Vector2(posX, posY));
return true;
};
m_SelectionBox.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndMove();
return true;
};
}
if (m_SelectionScaleLeft == null)
{
m_SelectionScaleLeft = new AreaManipulator(styles.rectangleToolScaleLeft, MouseCursor.ResizeHorizontal);
m_SelectionScaleLeft.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Right, ToolCoord.Left, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), DragMode.ScaleHorizontal, false);
return true;
}
return false;
};
m_SelectionScaleLeft.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_SelectionScaleLeft.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_SelectionScaleRight == null)
{
m_SelectionScaleRight = new AreaManipulator(styles.rectangleToolScaleRight, MouseCursor.ResizeHorizontal);
m_SelectionScaleRight.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Left, ToolCoord.Right, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), DragMode.ScaleHorizontal, false);
return true;
}
return false;
};
m_SelectionScaleRight.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_SelectionScaleRight.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_SelectionRippleLeft == null)
{
m_SelectionRippleLeft = new AreaManipulator(styles.rectangleToolRippleLeft, MouseCursor.ResizeHorizontal);
m_SelectionRippleLeft.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Right, ToolCoord.Left, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), DragMode.ScaleHorizontal, true);
return true;
}
return false;
};
m_SelectionRippleLeft.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_SelectionRippleLeft.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_SelectionRippleRight == null)
{
m_SelectionRippleRight = new AreaManipulator(styles.rectangleToolRippleRight, MouseCursor.ResizeHorizontal);
m_SelectionRippleRight.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Left, ToolCoord.Right, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), DragMode.ScaleHorizontal, true);
return true;
}
return false;
};
m_SelectionRippleRight.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_SelectionRippleRight.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_SelectionScaleBottom == null)
{
m_SelectionScaleBottom = new AreaManipulator(styles.rectangleToolScaleBottom, MouseCursor.ResizeVertical);
m_SelectionScaleBottom.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Top, ToolCoord.Bottom, new Vector2(0f, PixelToValue(evt.mousePosition.y)), DragMode.ScaleVertical, false);
return true;
}
return false;
};
m_SelectionScaleBottom.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleValue(PixelToValue(evt.mousePosition.y));
return true;
};
m_SelectionScaleBottom.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_SelectionScaleTop == null)
{
m_SelectionScaleTop = new AreaManipulator(styles.rectangleToolScaleTop, MouseCursor.ResizeVertical);
m_SelectionScaleTop.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Bottom, ToolCoord.Top, new Vector2(0f, PixelToValue(evt.mousePosition.y)), DragMode.ScaleVertical, false);
return true;
}
return false;
};
m_SelectionScaleTop.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleValue(PixelToValue(evt.mousePosition.y));
return true;
};
m_SelectionScaleTop.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
}
public void OnGUI()
{
if (!hasSelection)
return;
if (Event.current.type != EventType.Repaint)
return;
RectangleToolFlags flags = m_CurveEditor.settings.rectangleToolFlags;
if (flags == RectangleToolFlags.NoRectangleTool)
return;
Color oldColor = GUI.color;
GUI.color = Color.white;
m_Layout = CalculateLayout();
if (flags == RectangleToolFlags.FullRectangleTool)
{
GUI.Label(m_Layout.selectionLeftRect, GUIContent.none, styles.rectangleToolHighlight);
GUI.Label(m_Layout.selectionTopRect, GUIContent.none, styles.rectangleToolHighlight);
GUI.Label(m_Layout.underlayLeftRect, GUIContent.none, styles.rectangleToolHighlight);
GUI.Label(m_Layout.underlayTopRect, GUIContent.none, styles.rectangleToolHighlight);
}
m_SelectionBox.OnGUI(m_Layout.selectionRect);
m_SelectionScaleTop.OnGUI(m_Layout.scaleTopRect);
m_SelectionScaleBottom.OnGUI(m_Layout.scaleBottomRect);
bool showRippleHandles = (rippleTime && dragMode == DragMode.None) || (m_RippleTime && dragMode != DragMode.None);
if (showRippleHandles)
{
m_SelectionRippleLeft.OnGUI(m_Layout.scaleLeftRect);
m_SelectionRippleRight.OnGUI(m_Layout.scaleRightRect);
}
else
{
m_SelectionScaleLeft.OnGUI(m_Layout.scaleLeftRect);
m_SelectionScaleRight.OnGUI(m_Layout.scaleRightRect);
}
GUI.color = oldColor;
}
public void OverlayOnGUI(Rect bounds)
{
if (!hasSelection)
return;
if (Event.current.type != EventType.Repaint)
return;
Color oldColor = GUI.color;
RectangleToolFlags flags = m_CurveEditor.settings.rectangleToolFlags;
if (flags == RectangleToolFlags.FullRectangleTool)
{
GUI.color = Color.white;
m_HBar.OnGUI(m_Layout.hBarRect);
m_HBarLeft.OnGUI(m_Layout.hBarLeftRect);
m_HBarRight.OnGUI(m_Layout.hBarRightRect);
m_VBar.OnGUI(m_Layout.vBarRect);
m_VBarBottom.OnGUI(m_Layout.vBarBottomRect);
m_VBarTop.OnGUI(m_Layout.vBarTopRect);
}
DrawLabels(bounds);
GUI.color = oldColor;
}
public void HandleEvents()
{
RectangleToolFlags flags = m_CurveEditor.settings.rectangleToolFlags;
if (flags == RectangleToolFlags.NoRectangleTool)
return;
m_SelectionScaleTop.HandleEvents();
m_SelectionScaleBottom.HandleEvents();
if (rippleTime)
{
m_SelectionRippleLeft.HandleEvents();
m_SelectionRippleRight.HandleEvents();
}
else
{
m_SelectionScaleLeft.HandleEvents();
m_SelectionScaleRight.HandleEvents();
}
m_SelectionBox.HandleEvents();
}
public void HandleOverlayEvents()
{
RectangleToolFlags flags = m_CurveEditor.settings.rectangleToolFlags;
if (flags == RectangleToolFlags.NoRectangleTool)
return;
if (flags == RectangleToolFlags.FullRectangleTool)
{
m_VBarBottom.HandleEvents();
m_VBarTop.HandleEvents();
m_VBar.HandleEvents();
m_HBarLeft.HandleEvents();
m_HBarRight.HandleEvents();
m_HBar.HandleEvents();
}
}
private ToolLayout CalculateLayout()
{
ToolLayout layout = new ToolLayout();
bool canScaleX = !Mathf.Approximately(selectionBounds.size.x, 0f);
bool canScaleY = !Mathf.Approximately(selectionBounds.size.y, 0f);
float xMin = TimeToPixel(selectionBounds.min.x);
float xMax = TimeToPixel(selectionBounds.max.x);
float yMin = ValueToPixel(selectionBounds.max.y);
float yMax = ValueToPixel(selectionBounds.min.y);
layout.selectionRect = new Rect(xMin, yMin, xMax - xMin, yMax - yMin);
// Horizontal layout
layout.displayHScale = true;
float dragHorizWidth = layout.selectionRect.width - kHBarLeftWidth - kHBarRightWidth;
if (dragHorizWidth < kHBarMinWidth)
{
layout.displayHScale = false;
dragHorizWidth = layout.selectionRect.width;
if (dragHorizWidth < kHBarMinWidth)
{
layout.selectionRect.x = layout.selectionRect.center.x - kHBarMinWidth * 0.5f;
layout.selectionRect.width = kHBarMinWidth;
dragHorizWidth = kHBarMinWidth;
}
}
if (layout.displayHScale)
{
layout.hBarLeftRect = new Rect(layout.selectionRect.xMin, contentRect.yMin, kHBarLeftWidth, kHBarLeftHeight);
layout.hBarRect = new Rect(layout.hBarLeftRect.xMax, contentRect.yMin, dragHorizWidth, kHBarHeight);
layout.hBarRightRect = new Rect(layout.hBarRect.xMax, contentRect.yMin, kHBarLeftWidth, kHBarRightHeight);
}
else
{
layout.hBarRect = new Rect(layout.selectionRect.xMin, contentRect.yMin, dragHorizWidth, kHBarHeight);
layout.hBarLeftRect = new Rect(0f, 0f, 0f, 0f);
layout.hBarRightRect = new Rect(0f, 0f, 0f, 0f);
}
// Vertical layout
layout.displayVScale = true;
float dragVertHeight = layout.selectionRect.height - kVBarBottomHeight - kVBarTopHeight;
if (dragVertHeight < kVBarMinHeight)
{
layout.displayVScale = false;
dragVertHeight = layout.selectionRect.height;
if (dragVertHeight < kVBarMinHeight)
{
layout.selectionRect.y = layout.selectionRect.center.y - kVBarMinHeight * 0.5f;
layout.selectionRect.height = kVBarMinHeight;
dragVertHeight = kVBarMinHeight;
}
}
if (layout.displayVScale)
{
layout.vBarTopRect = new Rect(contentRect.xMin, layout.selectionRect.yMin, kVBarTopWidth, kVBarTopHeight);
layout.vBarRect = new Rect(contentRect.xMin, layout.vBarTopRect.yMax, kVBarWidth, dragVertHeight);
layout.vBarBottomRect = new Rect(contentRect.xMin, layout.vBarRect.yMax, kVBarBottomWidth, kVBarBottomHeight);
}
else
{
layout.vBarRect = new Rect(contentRect.xMin, layout.selectionRect.yMin, kVBarWidth, dragVertHeight);
layout.vBarTopRect = g_EmptyRect;
layout.vBarBottomRect = g_EmptyRect;
}
// Scale handles.
if (canScaleX)
{
float leftRatio = (1.0f - kScaleLeftRatio) * 0.5f;
float rightRatio = (1.0f - kScaleRightRatio) * 0.5f;
layout.scaleLeftRect = new Rect(layout.selectionRect.xMin - kScaleLeftMarginHorizontal - kScaleLeftWidth, layout.selectionRect.yMin + layout.selectionRect.height * leftRatio, kScaleLeftWidth, layout.selectionRect.height * kScaleLeftRatio);
layout.scaleRightRect = new Rect(layout.selectionRect.xMax + kScaleRightMarginHorizontal, layout.selectionRect.yMin + layout.selectionRect.height * rightRatio, kScaleRightWidth, layout.selectionRect.height * kScaleRightRatio);
}
else
{
layout.scaleLeftRect = g_EmptyRect;
layout.scaleRightRect = g_EmptyRect;
}
if (canScaleY)
{
float bottomRatio = (1.0f - kScaleBottomRatio) * 0.5f;
float topRatio = (1.0f - kScaleTopRatio) * 0.5f;
layout.scaleTopRect = new Rect(layout.selectionRect.xMin + layout.selectionRect.width * topRatio, layout.selectionRect.yMin - kScaleTopMarginVertical - kScaleTopHeight, layout.selectionRect.width * kScaleTopRatio, kScaleTopHeight);
layout.scaleBottomRect = new Rect(layout.selectionRect.xMin + layout.selectionRect.width * bottomRatio, layout.selectionRect.yMax + kScaleBottomMarginVertical, layout.selectionRect.width * kScaleBottomRatio, kScaleBottomHeight);
}
else
{
layout.scaleTopRect = g_EmptyRect;
layout.scaleBottomRect = g_EmptyRect;
}
// Labels.
if (canScaleX)
{
layout.leftLabelAnchor = new Vector2(layout.selectionRect.xMin - kHLabelMarginHorizontal, contentRect.yMin + kHLabelMarginVertical);
layout.rightLabelAnchor = new Vector2(layout.selectionRect.xMax + kHLabelMarginHorizontal, contentRect.yMin + kHLabelMarginVertical);
}
else
{
layout.leftLabelAnchor = layout.rightLabelAnchor = new Vector2(layout.selectionRect.xMax + kHLabelMarginHorizontal, contentRect.yMin + kHLabelMarginVertical);
}
if (canScaleY)
{
layout.bottomLabelAnchor = new Vector2(contentRect.xMin + kVLabelMarginHorizontal, layout.selectionRect.yMax + kVLabelMarginVertical);
layout.topLabelAnchor = new Vector2(contentRect.xMin + kVLabelMarginHorizontal, layout.selectionRect.yMin - kVLabelMarginVertical);
}
else
{
layout.bottomLabelAnchor = layout.topLabelAnchor = new Vector2(contentRect.xMin + kVLabelMarginHorizontal, layout.selectionRect.yMin - kVLabelMarginVertical);
}
// Extra ui.
layout.selectionLeftRect = new Rect(contentRect.xMin + kVBarWidth, layout.selectionRect.yMin, layout.selectionRect.xMin - kVBarWidth, layout.selectionRect.height);
layout.selectionTopRect = new Rect(layout.selectionRect.xMin, contentRect.yMin + kHBarHeight, layout.selectionRect.width, layout.selectionRect.yMin - kHBarHeight);
layout.underlayTopRect = new Rect(contentRect.xMin, contentRect.yMin, contentRect.width, kHBarHeight);
layout.underlayLeftRect = new Rect(contentRect.xMin, contentRect.yMin + kHBarHeight, kVBarWidth, contentRect.height - kHBarHeight);
return layout;
}
private void DrawLabels(Rect bounds)
{
if (dragMode == DragMode.None)
return;
RectangleToolFlags flags = m_CurveEditor.settings.rectangleToolFlags;
bool canScaleX = !Mathf.Approximately(selectionBounds.size.x, 0f);
bool canScaleY = !Mathf.Approximately(selectionBounds.size.y, 0f);
if (flags == RectangleToolFlags.FullRectangleTool)
{
// Horizontal labels
if ((dragMode & DragMode.MoveScaleHorizontal) != 0)
{
if (canScaleX)
{
GUIContent leftLabelContent = new GUIContent(string.Format("{0}", m_CurveEditor.FormatTime(selectionBounds.min.x, m_CurveEditor.invSnap, m_CurveEditor.timeFormat)));
GUIContent rightLabelContent = new GUIContent(string.Format("{0}", m_CurveEditor.FormatTime(selectionBounds.max.x, m_CurveEditor.invSnap, m_CurveEditor.timeFormat)));
Vector2 leftLabelSize = styles.dragLabel.CalcSize(leftLabelContent);
Vector2 rightLabelSize = styles.dragLabel.CalcSize(rightLabelContent);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.leftLabelAnchor.x - leftLabelSize.x, m_Layout.leftLabelAnchor.y, leftLabelSize.x, leftLabelSize.y), leftLabelContent, styles.dragLabel, 0.3f);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.rightLabelAnchor.x, m_Layout.rightLabelAnchor.y, rightLabelSize.x, rightLabelSize.y), rightLabelContent, styles.dragLabel, 0.3f);
}
else
{
GUIContent labelContent = new GUIContent(string.Format("{0}", m_CurveEditor.FormatTime(selectionBounds.center.x, m_CurveEditor.invSnap, m_CurveEditor.timeFormat)));
Vector2 labelSize = styles.dragLabel.CalcSize(labelContent);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.leftLabelAnchor.x, m_Layout.leftLabelAnchor.y, labelSize.x, labelSize.y), labelContent, styles.dragLabel, 0.3f);
}
}
// Vertical labels
if ((dragMode & DragMode.MoveScaleVertical) != 0)
{
if (canScaleY)
{
GUIContent bottomLabelContent = new GUIContent(string.Format("{0}", m_CurveEditor.FormatValue(selectionBounds.min.y)));
GUIContent topLabelContent = new GUIContent(string.Format("{0}", m_CurveEditor.FormatValue(selectionBounds.max.y)));
Vector2 bottomLabelSize = styles.dragLabel.CalcSize(bottomLabelContent);
Vector2 topLabelSize = styles.dragLabel.CalcSize(topLabelContent);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.bottomLabelAnchor.x, m_Layout.bottomLabelAnchor.y, bottomLabelSize.x, bottomLabelSize.y), bottomLabelContent, styles.dragLabel, 0.3f);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.topLabelAnchor.x, m_Layout.topLabelAnchor.y - topLabelSize.y, topLabelSize.x, topLabelSize.y), topLabelContent, styles.dragLabel, 0.3f);
}
else
{
GUIContent labelContent = new GUIContent(string.Format("{0}", m_CurveEditor.FormatValue(selectionBounds.center.y)));
Vector2 labelSize = styles.dragLabel.CalcSize(labelContent);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.topLabelAnchor.x, m_Layout.topLabelAnchor.y - labelSize.y, labelSize.x, labelSize.y), labelContent, styles.dragLabel, 0.3f);
}
}
}
else if (flags == RectangleToolFlags.MiniRectangleTool)
{
if ((dragMode & DragMode.MoveBothAxis) != 0)
{
Vector2 localPosition = (canScaleX || canScaleY) ? new Vector2(PixelToTime(Event.current.mousePosition.x, frameRate), PixelToValue(Event.current.mousePosition.y)) : (Vector2)selectionBounds.center;
Vector2 labelPosition = new Vector2(TimeToPixel(localPosition.x), ValueToPixel(localPosition.y));
GUIContent labelContent = new GUIContent(string.Format("{0}, {1}", m_CurveEditor.FormatTime(localPosition.x, m_CurveEditor.invSnap, m_CurveEditor.timeFormat), m_CurveEditor.FormatValue(localPosition.y)));
Vector2 labelSize = styles.dragLabel.CalcSize(labelContent);
// Clamp popup to remain inside the curve editor window
var labelRect = new Rect(labelPosition.x, labelPosition.y - labelSize.y, labelSize.x, labelSize.y);
labelRect.x += Mathf.Max(0.0f, bounds.xMin - labelRect.xMin);
labelRect.x -= Mathf.Max(0.0f, labelRect.xMax - bounds.xMax);
labelRect.y += Mathf.Max(0.0f, bounds.yMin - labelRect.yMin);
labelRect.y -= Mathf.Max(0.0f, labelRect.yMax - bounds.yMax);
EditorGUI.DoDropShadowLabel(labelRect, labelContent, styles.dragLabel, 0.3f);
}
}
}
private void OnStartScale(ToolCoord pivotCoord, ToolCoord pickedCoord, Vector2 mousePos, DragMode dragMode, bool rippleTime)
{
Bounds bounds = selectionBounds;
m_DragMode = dragMode;
m_Pivot = ToolCoordToPosition(pivotCoord, bounds);
m_Previous = ToolCoordToPosition(pickedCoord, bounds);
m_MouseOffset = mousePos - m_Previous;
m_RippleTime = rippleTime;
m_RippleTimeStart = bounds.min.x;
m_RippleTimeEnd = bounds.max.x;
m_CurveEditor.StartLiveEdit();
}
private void OnScaleTime(float time)
{
Matrix4x4 transform;
bool flipX;
if (CalculateScaleTimeMatrix(m_Previous.x, time, m_MouseOffset.x, m_Pivot.x, frameRate, out transform, out flipX))
TransformKeys(transform, flipX, false);
}
private void OnScaleValue(float val)
{
Matrix4x4 transform;
bool flipY;
if (CalculateScaleValueMatrix(m_Previous.y, val, m_MouseOffset.y, m_Pivot.y, out transform, out flipY))
TransformKeys(transform, false, flipY);
}
private void OnEndScale()
{
m_CurveEditor.EndLiveEdit();
m_DragMode = DragMode.None;
GUI.changed = true;
}
internal void OnStartMove(Vector2 position, bool rippleTime)
{
OnStartMove(position, DragMode.None, rippleTime);
}
private void OnStartMove(Vector2 position, DragMode dragMode, bool rippleTime)
{
Bounds bounds = selectionBounds;
m_DragMode = dragMode;
m_Previous = position;
m_RippleTime = rippleTime;
m_RippleTimeStart = bounds.min.x;
m_RippleTimeEnd = bounds.max.x;
m_CurveEditor.StartLiveEdit();
}
internal void OnMove(Vector2 position)
{
Vector2 dv = position - m_Previous;
Matrix4x4 transform = Matrix4x4.identity;
transform.SetTRS(new Vector3(dv.x, dv.y, 0f), Quaternion.identity, Vector3.one);
TransformKeys(transform, false, false);
}
internal void OnEndMove()
{
m_CurveEditor.EndLiveEdit();
m_DragMode = DragMode.None;
GUI.changed = true;
}
private void TransformKeys(Matrix4x4 matrix, bool flipX, bool flipY)
{
if (m_RippleTime)
{
m_CurveEditor.TransformRippleKeys(matrix, m_RippleTimeStart, m_RippleTimeEnd, flipX, flipY);
GUI.changed = true;
}
else
{
m_CurveEditor.TransformSelectedKeys(matrix, flipX, flipY);
GUI.changed = true;
}
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveEditorRectangleTool.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveEditorRectangleTool.cs",
"repo_id": "UnityCsReference",
"token_count": 19939
} | 286 |
// 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 UnityEditorInternal;
using System.Collections.Generic;
namespace UnityEditor
{
internal class DopeSheetEditorRectangleTool : RectangleTool
{
const int kScaleLeftWidth = 17;
const int kScaleLeftMarginHorizontal = 0;
const float kScaleLeftMarginVertical = 4;
const int kScaleRightWidth = 17;
const int kScaleRightMarginHorizontal = 0;
const float kScaleRightMarginVertical = 4;
const int kHLabelMarginHorizontal = 8;
const int kHLabelMarginVertical = 1;
static Rect g_EmptyRect = new Rect(0f, 0f, 0f, 0f);
struct ToolLayout
{
public Rect summaryRect;
public Rect selectionRect;
public Rect scaleLeftRect;
public Rect scaleRightRect;
public Vector2 leftLabelAnchor;
public Vector2 rightLabelAnchor;
}
private DopeSheetEditor m_DopeSheetEditor;
private AnimationWindowState m_State;
private ToolLayout m_Layout;
private Vector2 m_Pivot;
private Vector2 m_Previous;
private Vector2 m_MouseOffset;
private bool m_IsDragging;
private bool m_RippleTime;
private float m_RippleTimeStart;
private float m_RippleTimeEnd;
private AreaManipulator[] m_SelectionBoxes;
private AreaManipulator m_SelectionScaleLeft;
private AreaManipulator m_SelectionScaleRight;
private AreaManipulator m_SelectionRippleLeft;
private AreaManipulator m_SelectionRippleRight;
private bool hasSelection { get { return (m_State.selectedKeys.Count > 0); } }
private Bounds selectionBounds { get { return m_State.selectionBounds; } }
private float frameRate { get { return m_State.frameRate; } }
private bool rippleTime { get { return m_State.rippleTime; } }
private bool isDragging { get { return m_IsDragging || m_DopeSheetEditor.isDragging; } }
public override void Initialize(TimeArea timeArea)
{
base.Initialize(timeArea);
m_DopeSheetEditor = timeArea as DopeSheetEditor;
m_State = m_DopeSheetEditor.state;
if (m_SelectionBoxes == null)
{
m_SelectionBoxes = new AreaManipulator[2];
for (int i = 0; i < 2; ++i)
{
m_SelectionBoxes[i] = new AreaManipulator(styles.rectangleToolSelection, MouseCursor.MoveArrow);
m_SelectionBoxes[i].onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
bool curveEditorOverride = evt.shift || EditorGUI.actionKey;
if (!curveEditorOverride && hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartMove(new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0.0f), rippleTime);
return true;
}
return false;
};
m_SelectionBoxes[i].onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnMove(new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0.0f));
return true;
};
m_SelectionBoxes[i].onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndMove();
return true;
};
}
}
if (m_SelectionScaleLeft == null)
{
m_SelectionScaleLeft = new AreaManipulator(styles.dopesheetScaleLeft, MouseCursor.ResizeHorizontal);
m_SelectionScaleLeft.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Right, ToolCoord.Left, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), false);
return true;
}
return false;
};
m_SelectionScaleLeft.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_SelectionScaleLeft.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_SelectionScaleRight == null)
{
m_SelectionScaleRight = new AreaManipulator(styles.dopesheetScaleRight, MouseCursor.ResizeHorizontal);
m_SelectionScaleRight.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Left, ToolCoord.Right, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), false);
return true;
}
return false;
};
m_SelectionScaleRight.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_SelectionScaleRight.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_SelectionRippleLeft == null)
{
m_SelectionRippleLeft = new AreaManipulator(styles.dopesheetRippleLeft, MouseCursor.ResizeHorizontal);
m_SelectionRippleLeft.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Right, ToolCoord.Left, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), true);
return true;
}
return false;
};
m_SelectionRippleLeft.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_SelectionRippleLeft.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
if (m_SelectionRippleRight == null)
{
m_SelectionRippleRight = new AreaManipulator(styles.dopesheetRippleRight, MouseCursor.ResizeHorizontal);
m_SelectionRippleRight.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (hasSelection && manipulator.rect.Contains(evt.mousePosition))
{
OnStartScale(ToolCoord.Left, ToolCoord.Right, new Vector2(PixelToTime(evt.mousePosition.x, frameRate), 0f), true);
return true;
}
return false;
};
m_SelectionRippleRight.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnScaleTime(PixelToTime(evt.mousePosition.x, frameRate));
return true;
};
m_SelectionRippleRight.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
OnEndScale();
return true;
};
}
}
public void OnGUI()
{
if (!hasSelection)
return;
if (Event.current.type != EventType.Repaint)
return;
m_Layout = CalculateLayout();
m_SelectionBoxes[0].OnGUI(m_Layout.summaryRect);
m_SelectionBoxes[1].OnGUI(m_Layout.selectionRect);
bool showRippleHandles = (rippleTime && !isDragging) || (m_RippleTime && isDragging);
if (showRippleHandles)
{
m_SelectionRippleLeft.OnGUI(m_Layout.scaleLeftRect);
m_SelectionRippleRight.OnGUI(m_Layout.scaleRightRect);
}
else
{
m_SelectionScaleLeft.OnGUI(m_Layout.scaleLeftRect);
m_SelectionScaleRight.OnGUI(m_Layout.scaleRightRect);
}
DrawLabels();
}
public void HandleEvents()
{
if (rippleTime)
{
m_SelectionRippleLeft.HandleEvents();
m_SelectionRippleRight.HandleEvents();
}
else
{
m_SelectionScaleLeft.HandleEvents();
m_SelectionScaleRight.HandleEvents();
}
m_SelectionBoxes[0].HandleEvents();
m_SelectionBoxes[1].HandleEvents();
}
private ToolLayout CalculateLayout()
{
ToolLayout layout = new ToolLayout();
Bounds bounds = selectionBounds;
bool canScaleX = !Mathf.Approximately(bounds.size.x, 0f);
float xMin = TimeToPixel(bounds.min.x);
float xMax = TimeToPixel(bounds.max.x);
float yMin = 0f, yMax = 0f;
bool firstKey = true;
float heightCumul = 0f;
List<DopeLine> dopelines = m_State.dopelines;
for (int i = 0; i < dopelines.Count; ++i)
{
DopeLine dopeline = dopelines[i];
float dopelineHeight = (dopeline.tallMode ? AnimationWindowHierarchyGUI.k_DopeSheetRowHeightTall : AnimationWindowHierarchyGUI.k_DopeSheetRowHeight);
if (!dopeline.isMasterDopeline)
{
int length = dopeline.keys.Count;
for (int j = 0; j < length; j++)
{
AnimationWindowKeyframe keyframe = dopeline.keys[j];
if (m_State.KeyIsSelected(keyframe))
{
if (firstKey)
{
yMin = heightCumul;
firstKey = false;
}
yMax = heightCumul + dopelineHeight;
break;
}
}
}
heightCumul += dopelineHeight;
}
layout.summaryRect = new Rect(xMin, 0f, xMax - xMin, AnimationWindowHierarchyGUI.k_DopeSheetRowHeight);
layout.selectionRect = new Rect(xMin, yMin, xMax - xMin, yMax - yMin);
// Scale handles.
if (canScaleX)
{
layout.scaleLeftRect = new Rect(layout.selectionRect.xMin - kScaleLeftMarginHorizontal - kScaleLeftWidth, layout.selectionRect.yMin + kScaleLeftMarginVertical, kScaleLeftWidth, layout.selectionRect.height - kScaleLeftMarginVertical * 2);
layout.scaleRightRect = new Rect(layout.selectionRect.xMax + kScaleRightMarginHorizontal, layout.selectionRect.yMin + kScaleRightMarginVertical, kScaleRightWidth, layout.selectionRect.height - kScaleRightMarginVertical * 2);
}
else
{
layout.scaleLeftRect = g_EmptyRect;
layout.scaleRightRect = g_EmptyRect;
}
if (canScaleX)
{
layout.leftLabelAnchor = new Vector2(layout.summaryRect.xMin - kHLabelMarginHorizontal, contentRect.yMin + kHLabelMarginVertical);
layout.rightLabelAnchor = new Vector2(layout.summaryRect.xMax + kHLabelMarginHorizontal, contentRect.yMin + kHLabelMarginVertical);
}
else
{
layout.leftLabelAnchor = layout.rightLabelAnchor = new Vector2(layout.summaryRect.center.x + kHLabelMarginHorizontal, contentRect.yMin + kHLabelMarginVertical);
}
return layout;
}
private void DrawLabels()
{
if (isDragging == false)
return;
bool canScaleX = !Mathf.Approximately(selectionBounds.size.x, 0f);
if (canScaleX)
{
GUIContent leftLabelContent = new GUIContent(string.Format("{0}", m_DopeSheetEditor.FormatTime(selectionBounds.min.x, m_State.frameRate, m_State.timeFormat)));
GUIContent rightLabelContent = new GUIContent(string.Format("{0}", m_DopeSheetEditor.FormatTime(selectionBounds.max.x, m_State.frameRate, m_State.timeFormat)));
Vector2 leftLabelSize = styles.dragLabel.CalcSize(leftLabelContent);
Vector2 rightLabelSize = styles.dragLabel.CalcSize(rightLabelContent);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.leftLabelAnchor.x - leftLabelSize.x, m_Layout.leftLabelAnchor.y, leftLabelSize.x, leftLabelSize.y), leftLabelContent, styles.dragLabel, 0.3f);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.rightLabelAnchor.x, m_Layout.rightLabelAnchor.y, rightLabelSize.x, rightLabelSize.y), rightLabelContent, styles.dragLabel, 0.3f);
}
else
{
GUIContent labelContent = new GUIContent(string.Format("{0}", m_DopeSheetEditor.FormatTime(selectionBounds.center.x, m_State.frameRate, m_State.timeFormat)));
Vector2 labelSize = styles.dragLabel.CalcSize(labelContent);
EditorGUI.DoDropShadowLabel(new Rect(m_Layout.leftLabelAnchor.x, m_Layout.leftLabelAnchor.y, labelSize.x, labelSize.y), labelContent, styles.dragLabel, 0.3f);
}
}
private void OnStartScale(ToolCoord pivotCoord, ToolCoord pickedCoord, Vector2 mousePos, bool rippleTime)
{
Bounds bounds = selectionBounds;
m_IsDragging = true;
m_Pivot = ToolCoordToPosition(pivotCoord, bounds);
m_Previous = ToolCoordToPosition(pickedCoord, bounds);
m_MouseOffset = mousePos - m_Previous;
m_RippleTime = rippleTime;
m_RippleTimeStart = bounds.min.x;
m_RippleTimeEnd = bounds.max.x;
m_State.StartLiveEdit();
}
private void OnScaleTime(float time)
{
Matrix4x4 transform;
bool flipX;
if (CalculateScaleTimeMatrix(m_Previous.x, time, m_MouseOffset.x, m_Pivot.x, frameRate, out transform, out flipX))
TransformKeys(transform, flipX, false);
}
private void OnEndScale()
{
m_State.EndLiveEdit();
m_IsDragging = false;
}
internal void OnStartMove(Vector2 position, bool rippleTime)
{
Bounds bounds = selectionBounds;
m_IsDragging = true;
m_Previous = position;
m_RippleTime = rippleTime;
m_RippleTimeStart = bounds.min.x;
m_RippleTimeEnd = bounds.max.x;
m_State.StartLiveEdit();
}
internal void OnMove(Vector2 position)
{
Vector2 dv = position - m_Previous;
Matrix4x4 transform = Matrix4x4.identity;
transform.SetTRS(new Vector3(dv.x, dv.y, 0f), Quaternion.identity, Vector3.one);
TransformKeys(transform, false, false);
}
internal void OnEndMove()
{
m_State.EndLiveEdit();
m_IsDragging = false;
}
private void TransformKeys(Matrix4x4 matrix, bool flipX, bool flipY)
{
if (m_RippleTime)
m_State.TransformRippleKeys(matrix, m_RippleTimeStart, m_RippleTimeEnd, flipX, true);
else
m_State.TransformSelectedKeys(matrix, flipX, flipY, true);
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/DopeSheetEditorRectangleTool.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/DopeSheetEditorRectangleTool.cs",
"repo_id": "UnityCsReference",
"token_count": 8496
} | 287 |
// 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 UnityEditor;
using System.Linq;
namespace UnityEditor.Animations
{
internal struct PushUndoIfNeeded
{
public bool pushUndo
{
get { return impl.m_PushUndo; }
set { impl.m_PushUndo = value; }
}
public PushUndoIfNeeded(bool pushUndo)
{
m_Impl = new PushUndoIfNeededImpl(pushUndo);
}
public void DoUndo(Object target, string undoOperation)
{
impl.DoUndo(target, undoOperation);
}
public void DoUndoCreated(Object target, string undoOperation)
{
impl.DoUndoCreated(target, undoOperation);
}
PushUndoIfNeededImpl impl
{
get
{
if (m_Impl == null)
m_Impl = new PushUndoIfNeededImpl(true);
return m_Impl;
}
}
PushUndoIfNeededImpl m_Impl;
private class PushUndoIfNeededImpl
{
public PushUndoIfNeededImpl(bool pushUndo)
{
m_PushUndo = pushUndo;
}
public void DoUndo(Object target, string undoOperation)
{
if (m_PushUndo)
{
Undo.RegisterCompleteObjectUndo(target, undoOperation);
}
}
public void DoUndoCreated(Object target, string undoOperation)
{
if (m_PushUndo)
{
Undo.RegisterCreatedObjectUndo(target, undoOperation);
}
}
public bool m_PushUndo;
}
}
public partial class AnimatorTransitionBase : Object
{
private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true);
internal bool pushUndo { set { undoHandler.pushUndo = value; } }
public void AddCondition(AnimatorConditionMode mode, float threshold, string parameter)
{
undoHandler.DoUndo(this, "Condition added");
AnimatorCondition[] conditionVector = conditions;
AnimatorCondition newCondition = new AnimatorCondition();
newCondition.mode = mode;
newCondition.parameter = parameter;
newCondition.threshold = threshold;
ArrayUtility.Add(ref conditionVector, newCondition);
conditions = conditionVector;
}
public void RemoveCondition(AnimatorCondition condition)
{
undoHandler.DoUndo(this, "Condition removed");
AnimatorCondition[] conditionVector = conditions;
ArrayUtility.Remove(ref conditionVector, condition);
conditions = conditionVector;
}
}
internal class AnimatorDefaultTransition : ScriptableObject
{
}
public partial class AnimatorState : Object
{
private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true);
internal bool pushUndo { set { undoHandler.pushUndo = value; } }
public void AddTransition(AnimatorStateTransition transition)
{
undoHandler.DoUndo(this, "Transition added");
AnimatorStateTransition[] transitionsVector = transitions;
ArrayUtility.Add(ref transitionsVector, transition);
transitions = transitionsVector;
}
public void RemoveTransition(AnimatorStateTransition transition)
{
undoHandler.DoUndo(this, "Transition removed");
AnimatorStateTransition[] transitionsVector = transitions;
ArrayUtility.Remove(ref transitionsVector, transition);
transitions = transitionsVector;
if (MecanimUtilities.AreSameAsset(this, transition))
Undo.DestroyObjectImmediate(transition);
}
private AnimatorStateTransition CreateTransition(bool setDefaultExitTime)
{
AnimatorStateTransition newTransition = new AnimatorStateTransition();
newTransition.hasExitTime = false;
newTransition.hasFixedDuration = true;
if (AssetDatabase.GetAssetPath(this) != "")
AssetDatabase.AddObjectToAsset(newTransition, AssetDatabase.GetAssetPath(this));
newTransition.hideFlags = HideFlags.HideInHierarchy;
undoHandler.DoUndoCreated(newTransition, "Transition Created");
if (setDefaultExitTime)
SetDefaultTransitionExitTime(ref newTransition);
return newTransition;
}
private void SetDefaultTransitionExitTime(ref AnimatorStateTransition newTransition)
{
newTransition.hasExitTime = true;
if (motion != null && motion.averageDuration > 0.0f)
{
const float transitionDefaultDuration = 0.25f;
float transitionDurationNormalized = transitionDefaultDuration / motion.averageDuration;
newTransition.duration = transitionDefaultDuration;
newTransition.exitTime = 1.0f - transitionDurationNormalized;
}
else
{
newTransition.duration = 0.25f;
newTransition.exitTime = 0.75f;
}
}
public AnimatorStateTransition AddTransition(AnimatorState destinationState)
{
AnimatorStateTransition newTransition = CreateTransition(false);
newTransition.destinationState = destinationState;
AddTransition(newTransition);
return newTransition;
}
public AnimatorStateTransition AddTransition(AnimatorStateMachine destinationStateMachine)
{
AnimatorStateTransition newTransition = CreateTransition(false);
newTransition.destinationStateMachine = destinationStateMachine;
AddTransition(newTransition);
return newTransition;
}
public AnimatorStateTransition AddTransition(AnimatorState destinationState, bool defaultExitTime)
{
AnimatorStateTransition newTransition = CreateTransition(defaultExitTime);
newTransition.destinationState = destinationState;
AddTransition(newTransition);
return newTransition;
}
public AnimatorStateTransition AddTransition(AnimatorStateMachine destinationStateMachine, bool defaultExitTime)
{
AnimatorStateTransition newTransition = CreateTransition(defaultExitTime);
newTransition.destinationStateMachine = destinationStateMachine;
AddTransition(newTransition);
return newTransition;
}
public AnimatorStateTransition AddExitTransition()
{
return AddExitTransition(false);
}
public AnimatorStateTransition AddExitTransition(bool defaultExitTime)
{
AnimatorStateTransition newTransition = CreateTransition(defaultExitTime);
newTransition.isExit = true;
AddTransition(newTransition);
return newTransition;
}
internal AnimatorStateMachine FindParent(AnimatorStateMachine root)
{
if (root.HasState(this, false)) return root;
else return root.stateMachinesRecursive.Find(sm => sm.stateMachine.HasState(this, false)).stateMachine;
}
internal AnimatorStateTransition FindTransition(AnimatorState destinationState) // pp todo return a list?
{
return (new List<AnimatorStateTransition>(transitions)).Find(t => t.destinationState == destinationState);
}
[System.Obsolete("uniqueName does not exist anymore. Consider using .name instead.", true)]
public string uniqueName
{
get { return ""; }
}
[System.Obsolete("GetMotion() is obsolete. Use motion", true)]
public Motion GetMotion()
{
return null;
}
[System.Obsolete("uniqueNameHash does not exist anymore.", true)]
public int uniqueNameHash
{
get { return -1; }
}
}
public partial class AnimatorStateMachine : Object
{
private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true);
internal bool pushUndo { set { undoHandler.pushUndo = value; } }
internal class StateMachineCache
{
static Dictionary<AnimatorStateMachine, ChildAnimatorStateMachine[]> m_ChildStateMachines;
static bool m_Initialized;
static void Init()
{
if (!m_Initialized)
{
m_ChildStateMachines = new Dictionary<AnimatorStateMachine, ChildAnimatorStateMachine[]>();
m_Initialized = true;
}
}
static public void Clear()
{
Init();
m_ChildStateMachines.Clear();
}
static public ChildAnimatorStateMachine[] GetChildStateMachines(AnimatorStateMachine parent)
{
Init();
ChildAnimatorStateMachine[] children;
if (m_ChildStateMachines.TryGetValue(parent, out children) == false)
{
children = parent.stateMachines;
m_ChildStateMachines.Add(parent, children);
}
return children;
}
}
internal List<ChildAnimatorState> statesRecursive
{
get
{
List<ChildAnimatorState> ret = new List<ChildAnimatorState>();
ret.AddRange(states);
for (int j = 0; j < stateMachines.Length; j++)
{
ret.AddRange(stateMachines[j].stateMachine.statesRecursive);
}
return ret;
}
}
internal List<ChildAnimatorStateMachine> stateMachinesRecursive
{
get
{
List<ChildAnimatorStateMachine> ret = new List<ChildAnimatorStateMachine>();
var childStateMachines = AnimatorStateMachine.StateMachineCache.GetChildStateMachines(this);
ret.AddRange(childStateMachines);
for (int j = 0; j < childStateMachines.Length; j++)
{
ret.AddRange(childStateMachines[j].stateMachine.stateMachinesRecursive);
}
return ret;
}
}
internal List<AnimatorStateTransition> anyStateTransitionsRecursive
{
get
{
List<AnimatorStateTransition> childTransitions = new List<AnimatorStateTransition>();
childTransitions.AddRange(anyStateTransitions);
foreach (ChildAnimatorStateMachine stateMachine in stateMachines)
{
childTransitions.AddRange(stateMachine.stateMachine.anyStateTransitionsRecursive);
}
return childTransitions;
}
}
internal Vector3 GetStatePosition(AnimatorState state)
{
ChildAnimatorState[] animatorStates = states;
for (int i = 0; i < animatorStates.Length; i++)
if (state == animatorStates[i].state)
return animatorStates[i].position;
System.Diagnostics.Debug.Fail("Can't find state (" + state.name + ") in parent state machine (" + name + ").");
return Vector3.zero;
}
internal void SetStatePosition(AnimatorState state, Vector3 position)
{
ChildAnimatorState[] childStates = states;
for (int i = 0; i < childStates.Length; i++)
if (state == childStates[i].state)
{
childStates[i].position = position;
states = childStates;
return;
}
System.Diagnostics.Debug.Fail("Can't find state (" + state.name + ") in parent state machine (" + name + ").");
}
internal Vector3 GetStateMachinePosition(AnimatorStateMachine stateMachine)
{
ChildAnimatorStateMachine[] childSM = stateMachines;
for (int i = 0; i < childSM.Length; i++)
if (stateMachine == childSM[i].stateMachine)
return childSM[i].position;
System.Diagnostics.Debug.Fail("Can't find state machine (" + stateMachine.name + ") in parent state machine (" + name + ").");
return Vector3.zero;
}
internal void SetStateMachinePosition(AnimatorStateMachine stateMachine, Vector3 position)
{
ChildAnimatorStateMachine[] childSM = stateMachines;
for (int i = 0; i < childSM.Length; i++)
if (stateMachine == childSM[i].stateMachine)
{
childSM[i].position = position;
stateMachines = childSM;
return;
}
System.Diagnostics.Debug.Fail("Can't find state machine (" + stateMachine.name + ") in parent state machine (" + name + ").");
}
public AnimatorState AddState(string name)
{
return AddState(name, states.Length > 0 ? states[states.Length - 1].position + new Vector3(35, 65) : new Vector3(200, 0, 0));
}
public AnimatorState AddState(string name, Vector3 position)
{
AnimatorState state = new AnimatorState();
state.hideFlags = HideFlags.HideInHierarchy;
state.name = MakeUniqueStateName(name);
if (AssetDatabase.GetAssetPath(this) != "")
AssetDatabase.AddObjectToAsset(state, AssetDatabase.GetAssetPath(this));
undoHandler.DoUndoCreated(state, "State Created");
AddState(state, position);
return state;
}
public void AddState(AnimatorState state, Vector3 position)
{
ChildAnimatorState[] childStates = states;
if (System.Array.Exists(childStates, childState => childState.state == state))
{
Debug.LogWarning(System.String.Format("State '{0}' already exists in state machine '{1}', discarding new state.", state.name, name));
return;
}
undoHandler.DoUndo(this, "State added");
ChildAnimatorState newState = new ChildAnimatorState();
newState.state = state;
newState.position = position;
ArrayUtility.Add(ref childStates, newState);
states = childStates;
}
public void RemoveState(AnimatorState state)
{
undoHandler.DoUndo(this, "State removed");
undoHandler.DoUndo(state, "State removed");
RemoveStateInternal(state);
}
public AnimatorStateMachine AddStateMachine(string name)
{
return AddStateMachine(name, Vector3.zero);
}
public AnimatorStateMachine AddStateMachine(string name, Vector3 position)
{
AnimatorStateMachine stateMachine = new AnimatorStateMachine();
stateMachine.hideFlags = HideFlags.HideInHierarchy;
stateMachine.name = MakeUniqueStateMachineName(name);
AddStateMachine(stateMachine, position);
if (AssetDatabase.GetAssetPath(this) != "")
AssetDatabase.AddObjectToAsset(stateMachine, AssetDatabase.GetAssetPath(this));
undoHandler.DoUndoCreated(stateMachine, "StateMachine Created");
return stateMachine;
}
public void AddStateMachine(AnimatorStateMachine stateMachine, Vector3 position)
{
ChildAnimatorStateMachine[] childStateMachines = stateMachines;
if (System.Array.Exists(childStateMachines, childStateMachine => childStateMachine.stateMachine == stateMachine))
{
Debug.LogWarning(System.String.Format("Sub state machine '{0}' already exists in state machine '{1}', discarding new state machine.", stateMachine.name, name));
return;
}
undoHandler.DoUndo(this, "StateMachine " + stateMachine.name + " added");
ChildAnimatorStateMachine newStateMachine = new ChildAnimatorStateMachine();
newStateMachine.stateMachine = stateMachine;
newStateMachine.position = position;
ArrayUtility.Add(ref childStateMachines, newStateMachine);
stateMachines = childStateMachines;
}
public void RemoveStateMachine(AnimatorStateMachine stateMachine)
{
undoHandler.DoUndo(this, "StateMachine removed");
undoHandler.DoUndo(stateMachine, "StateMachine removed");
RemoveStateMachineInternal(stateMachine);
}
private AnimatorStateTransition AddAnyStateTransition()
{
AnimatorStateTransition newTransition = new AnimatorStateTransition();
newTransition.hasExitTime = false;
newTransition.hasFixedDuration = true;
newTransition.duration = 0.25f;
newTransition.exitTime = 0.75f;
newTransition.hideFlags = HideFlags.HideInHierarchy;
if (AssetDatabase.GetAssetPath(this) != "")
AssetDatabase.AddObjectToAsset(newTransition, AssetDatabase.GetAssetPath(this));
undoHandler.DoUndoCreated(newTransition, "AnyState Transition Created");
undoHandler.DoUndo(this, "AnyState Transition Added");
AnimatorStateTransition[] transitionsVector = anyStateTransitions;
ArrayUtility.Add(ref transitionsVector, newTransition);
anyStateTransitions = transitionsVector;
return newTransition;
}
public AnimatorStateTransition AddAnyStateTransition(AnimatorState destinationState)
{
AnimatorStateTransition newTransition = AddAnyStateTransition();
newTransition.destinationState = destinationState;
return newTransition;
}
public AnimatorStateTransition AddAnyStateTransition(AnimatorStateMachine destinationStateMachine)
{
AnimatorStateTransition newTransition = AddAnyStateTransition();
newTransition.destinationStateMachine = destinationStateMachine;
return newTransition;
}
public bool RemoveAnyStateTransition(AnimatorStateTransition transition)
{
if ((new List<AnimatorStateTransition>(anyStateTransitions)).Any(t => t == transition))
{
undoHandler.DoUndo(this, "AnyState Transition Removed");
AnimatorStateTransition[] transitionsVector = anyStateTransitions;
ArrayUtility.Remove(ref transitionsVector, transition);
anyStateTransitions = transitionsVector;
if (MecanimUtilities.AreSameAsset(this, transition))
Undo.DestroyObjectImmediate(transition);
return true;
}
return false;
}
internal void RemoveAnyStateTransitionRecursive(AnimatorStateTransition transition)
{
if (RemoveAnyStateTransition(transition))
return;
List<ChildAnimatorStateMachine> childStateMachines = stateMachinesRecursive;
foreach (ChildAnimatorStateMachine sm in childStateMachines)
{
if (sm.stateMachine.RemoveAnyStateTransition(transition))
return;
}
}
public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine)
{
AnimatorTransition newTransition = new AnimatorTransition();
AddStateMachineTransition(sourceStateMachine, newTransition);
return newTransition;
}
public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorStateMachine destinationStateMachine)
{
var newTransition = new AnimatorTransition();
newTransition.destinationStateMachine = destinationStateMachine;
AddStateMachineTransition(sourceStateMachine, newTransition);
return newTransition;
}
public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorState destinationState)
{
var newTransition = new AnimatorTransition();
newTransition.destinationState = destinationState;
AddStateMachineTransition(sourceStateMachine, newTransition);
return newTransition;
}
internal void AddStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorTransition transition)
{
transition.hideFlags = HideFlags.HideInHierarchy;
if (AssetDatabase.GetAssetPath(this) != "")
AssetDatabase.AddObjectToAsset(transition, AssetDatabase.GetAssetPath(this));
undoHandler.DoUndoCreated(transition, "StateMachine Transition Created");
undoHandler.DoUndo(this, "StateMachine Transition Added");
AnimatorTransition[] transitionsVector = GetStateMachineTransitions(sourceStateMachine);
ArrayUtility.Add(ref transitionsVector, transition);
SetStateMachineTransitions(sourceStateMachine, transitionsVector);
}
public AnimatorTransition AddStateMachineExitTransition(AnimatorStateMachine sourceStateMachine)
{
var newTransition = new AnimatorTransition();
newTransition.isExit = true;
AddStateMachineTransition(sourceStateMachine, newTransition);
return newTransition;
}
public bool RemoveStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorTransition transition)
{
undoHandler.DoUndo(this, "StateMachine Transition Removed");
AnimatorTransition[] transitionsVector = GetStateMachineTransitions(sourceStateMachine);
int baseSize = transitionsVector.Length;
ArrayUtility.Remove(ref transitionsVector, transition);
SetStateMachineTransitions(sourceStateMachine, transitionsVector);
if (MecanimUtilities.AreSameAsset(this, transition))
Undo.DestroyObjectImmediate(transition);
return baseSize != transitionsVector.Length;
}
private AnimatorTransition AddEntryTransition()
{
AnimatorTransition newTransition = new AnimatorTransition();
newTransition.hideFlags = HideFlags.HideInHierarchy;
if (AssetDatabase.GetAssetPath(this) != "")
AssetDatabase.AddObjectToAsset(newTransition, AssetDatabase.GetAssetPath(this));
undoHandler.DoUndoCreated(newTransition, "Entry Transition Created");
undoHandler.DoUndo(this, "Entry Transition Added");
AnimatorTransition[] transitionsVector = entryTransitions;
ArrayUtility.Add(ref transitionsVector, newTransition);
entryTransitions = transitionsVector;
return newTransition;
}
public AnimatorTransition AddEntryTransition(AnimatorState destinationState)
{
AnimatorTransition newTransition = AddEntryTransition();
newTransition.destinationState = destinationState;
return newTransition;
}
public AnimatorTransition AddEntryTransition(AnimatorStateMachine destinationStateMachine)
{
AnimatorTransition newTransition = AddEntryTransition();
newTransition.destinationStateMachine = destinationStateMachine;
return newTransition;
}
public bool RemoveEntryTransition(AnimatorTransition transition)
{
if ((new List<AnimatorTransition>(entryTransitions)).Any(t => t == transition))
{
undoHandler.DoUndo(this, "Entry Transition Removed");
AnimatorTransition[] transitionsVector = entryTransitions;
ArrayUtility.Remove(ref transitionsVector, transition);
entryTransitions = transitionsVector;
if (MecanimUtilities.AreSameAsset(this, transition))
Undo.DestroyObjectImmediate(transition);
return true;
}
return false;
}
internal ChildAnimatorState FindState(int nameHash)
{
return (new List<ChildAnimatorState>(states)).Find(s => s.state.nameHash == nameHash);
}
internal ChildAnimatorState FindState(string name)
{
return (new List<ChildAnimatorState>(states)).Find(s => s.state.name == name);
}
internal bool HasState(AnimatorState state)
{
return statesRecursive.Any(s => s.state == state);
}
internal bool IsDirectParent(AnimatorStateMachine stateMachine)
{
return stateMachines.Any(sm => sm.stateMachine == stateMachine);
}
internal bool HasStateMachine(AnimatorStateMachine child)
{
return stateMachinesRecursive.Any(sm => sm.stateMachine == child);
}
internal bool HasTransition(AnimatorState stateA, AnimatorState stateB)
{
return stateA.transitions.Any(t => t.destinationState == stateB) ||
stateB.transitions.Any(t => t.destinationState == stateA);
}
internal AnimatorStateMachine FindParent(AnimatorStateMachine stateMachine)
{
if (stateMachines.Any(childSM => childSM.stateMachine == stateMachine))
return this;
else
return stateMachinesRecursive.Find(sm => sm.stateMachine.stateMachines.Any(childSM => childSM.stateMachine == stateMachine)).stateMachine;
}
internal AnimatorStateMachine FindStateMachine(string path)
{
string[] smNames = path.Split('.');
// first element is always Root statemachine 'this'
AnimatorStateMachine currentSM = this;
// last element is state name, we don't care
for (int i = 1; i < smNames.Length - 1 && currentSM != null; ++i)
{
var childStateMachines = AnimatorStateMachine.StateMachineCache.GetChildStateMachines(currentSM);
int index = System.Array.FindIndex(childStateMachines, t => t.stateMachine.name == smNames[i]);
currentSM = index >= 0 ? childStateMachines[index].stateMachine : null;
}
return (currentSM == null) ? this : currentSM;
}
internal AnimatorStateMachine FindStateMachine(AnimatorState state)
{
if (HasState(state, false))
return this;
List<ChildAnimatorStateMachine> childStateMachines = stateMachinesRecursive;
int index = childStateMachines.FindIndex(sm => sm.stateMachine.HasState(state, false));
return index >= 0 ? childStateMachines[index].stateMachine : null;
}
internal AnimatorStateTransition FindTransition(AnimatorState destinationState)
{
return (new List<AnimatorStateTransition>(anyStateTransitions)).Find(t => t.destinationState == destinationState);
}
[System.Obsolete("stateCount is obsolete. Use .states.Length instead.", true)]
int stateCount
{
get { return 0; }
}
[System.Obsolete("stateMachineCount is obsolete. Use .stateMachines.Length instead.", true)]
int stateMachineCount
{
get { return 0; }
}
[System.Obsolete("GetTransitionsFromState is obsolete. Use AnimatorState.transitions instead.", true)]
AnimatorState GetTransitionsFromState(AnimatorState state)
{
return null;
}
[System.Obsolete("uniqueNameHash does not exist anymore.", true)]
int uniqueNameHash
{
get { return -1; }
}
}
}
| UnityCsReference/Editor/Mono/Animation/StateMachine.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/StateMachine.cs",
"repo_id": "UnityCsReference",
"token_count": 12153
} | 288 |
// 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.ShortcutManagement;
using UnityEngine;
namespace UnityEditor
{
public class SceneViewCameraWindow : PopupWindowContent
{
static class Styles
{
public static readonly GUIContent copyPlacementLabel = EditorGUIUtility.TrTextContent("Copy Placement");
public static readonly GUIContent pastePlacementLabel = EditorGUIUtility.TrTextContent("Paste Placement");
public static readonly GUIContent copySettingsLabel = EditorGUIUtility.TrTextContent("Copy Settings");
public static readonly GUIContent pasteSettingsLabel = EditorGUIUtility.TrTextContent("Paste Settings");
public static readonly GUIContent resetSettingsLabel = EditorGUIUtility.TrTextContent("Reset Settings");
public static readonly GUIContent cameraSpeedRange = EditorGUIUtility.TrTextContent(" ");
public static readonly GUIStyle settingsArea;
static Styles()
{
settingsArea = new GUIStyle
{
border = new RectOffset(4, 4, 4, 4),
};
}
}
readonly SceneView m_SceneView;
GUIContent m_CameraSpeedSliderContent;
GUIContent m_AccelerationEnabled;
GUIContent[] m_MinMaxContent;
GUIContent m_FieldOfView;
GUIContent m_DynamicClip;
GUIContent m_OcclusionCulling;
GUIContent m_EasingEnabled;
GUIContent m_SceneCameraLabel = EditorGUIUtility.TrTextContent("Scene Camera");
GUIContent m_NavigationLabel = EditorGUIUtility.TrTextContent("Navigation");
readonly string k_ClippingPlaneWarning = L10n.Tr("Using extreme values between the near and far planes may cause rendering issues. In general, to get better precision move the Near plane as far as possible.");
const int kFieldCount = 13;
const int kWindowWidth = 290;
const int kContentPadding = 4;
const int k_HeaderSpacing = 2;
const int kWindowHeight = ((int)EditorGUI.kSingleLineHeight) * kFieldCount + kContentPadding * 2 + k_HeaderSpacing * 2;
const float kPrefixLabelWidth = 120f;
// FOV values chosen to be the smallest and largest before extreme visual corruption
const float k_MinFieldOfView = 4f;
const float k_MaxFieldOfView = 120f;
Vector2 m_WindowSize;
Vector2 m_Scroll;
public static event Action<SceneView> additionalSettingsGui;
public override Vector2 GetWindowSize()
{
return m_WindowSize;
}
public SceneViewCameraWindow(SceneView sceneView)
{
m_SceneView = sceneView;
m_CameraSpeedSliderContent = EditorGUIUtility.TrTextContent("Camera Speed", "The current speed of the camera in the Scene view.");
m_AccelerationEnabled = EditorGUIUtility.TrTextContent("Camera Acceleration", "Check this to enable acceleration when moving the camera. When enabled, camera speed is evaluated as a modifier. With acceleration disabled, the camera is accelerated to the Camera Speed.");
m_FieldOfView = EditorGUIUtility.TrTextContent("Field of View", "The height of the camera's view angle. Measured in degrees vertically, or along the local Y axis.");
m_DynamicClip = EditorGUIUtility.TrTextContent("Dynamic Clipping", "Check this to enable camera's near and far clipping planes to be calculated relative to the viewport size of the Scene.");
m_OcclusionCulling = EditorGUIUtility.TrTextContent("Occlusion Culling", "Check this to enable occlusion culling in the Scene view. Occlusion culling disables rendering of objects when they\'re not currently seen by the camera because they\'re hidden (occluded) by other objects.");
m_EasingEnabled = EditorGUIUtility.TrTextContent("Camera Easing", "Check this to enable camera movement easing. This makes the camera ease in when it starts moving and ease out when it stops.");
m_WindowSize = new Vector2(kWindowWidth, kWindowHeight);
m_MinMaxContent = new[]
{
EditorGUIUtility.TrTextContent("Min", $"The minimum speed of the camera in the Scene view. Valid values are between [{SceneView.CameraSettings.kAbsoluteSpeedMin}, {SceneView.CameraSettings.kAbsoluteSpeedMax - 1}]."),
EditorGUIUtility.TrTextContent("Max", $"The maximum speed of the camera in the Scene view. Valid values are between [{SceneView.CameraSettings.kAbsoluteSpeedMin + .0001f}, {SceneView.CameraSettings.kAbsoluteSpeedMax}].")
};
}
public override void OnGUI(Rect rect)
{
if (m_SceneView == null || m_SceneView.sceneViewState == null)
return;
Draw();
// Escape closes the window
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
{
editorWindow.Close();
GUIUtility.ExitGUI();
}
}
void Draw()
{
var settings = m_SceneView.cameraSettings;
m_Scroll = GUILayout.BeginScrollView(m_Scroll);
GUILayout.BeginVertical(Styles.settingsArea);
EditorGUI.BeginChangeCheck();
GUILayout.Space(k_HeaderSpacing);
GUILayout.BeginHorizontal();
GUILayout.Label(m_SceneCameraLabel, EditorStyles.boldLabel);
GUILayout.FlexibleSpace();
if (GUILayout.Button(EditorGUI.GUIContents.titleSettingsIcon, EditorStyles.iconButton))
ShowContextMenu(m_SceneView);
GUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = kPrefixLabelWidth;
// fov isn't applicable in orthographic mode, and orthographic size is controlled by the user zoom
using (new EditorGUI.DisabledScope(m_SceneView.orthographic))
{
settings.fieldOfView = EditorGUILayout.Slider(m_FieldOfView, settings.fieldOfView, k_MinFieldOfView, k_MaxFieldOfView);
}
settings.dynamicClip = EditorGUILayout.Toggle(m_DynamicClip, settings.dynamicClip);
using (new EditorGUI.DisabledScope(settings.dynamicClip))
{
float near = settings.nearClip, far = settings.farClip;
DrawStackedFloatField(EditorGUI.s_ClipingPlanesLabel,
EditorGUI.s_NearAndFarLabels[0],
EditorGUI.s_NearAndFarLabels[1], ref near, ref far,
EditorGUI.kNearFarLabelsWidth);
settings.SetClipPlanes(near, far);
if(far/near > 10000000 || near < 0.0001f)
EditorGUILayout.HelpBox(k_ClippingPlaneWarning,MessageType.Warning);
}
settings.occlusionCulling = EditorGUILayout.Toggle(m_OcclusionCulling, settings.occlusionCulling);
if (EditorGUI.EndChangeCheck())
m_SceneView.Repaint();
EditorGUILayout.Space(k_HeaderSpacing);
GUILayout.Label(m_NavigationLabel, EditorStyles.boldLabel);
settings.easingEnabled = EditorGUILayout.Toggle(m_EasingEnabled, settings.easingEnabled);
settings.accelerationEnabled = EditorGUILayout.Toggle(m_AccelerationEnabled, settings.accelerationEnabled);
EditorGUI.BeginChangeCheck();
float min = settings.speedMin, max = settings.speedMax, speed = settings.RoundSpeedToNearestSignificantDecimal(settings.speed);
speed = EditorGUILayout.Slider(m_CameraSpeedSliderContent, speed, min, max);
if (EditorGUI.EndChangeCheck())
settings.speed = settings.RoundSpeedToNearestSignificantDecimal(speed);
EditorGUI.BeginChangeCheck();
DrawStackedFloatField(Styles.cameraSpeedRange,
m_MinMaxContent[0],
m_MinMaxContent[1],
ref min, ref max,
EditorGUI.kNearFarLabelsWidth);
if (EditorGUI.EndChangeCheck())
settings.SetSpeedMinMax(min, max);
EditorGUIUtility.labelWidth = 0f;
if (additionalSettingsGui != null)
{
EditorGUILayout.Space(k_HeaderSpacing);
additionalSettingsGui(m_SceneView);
if (Event.current.type == EventType.Repaint)
m_WindowSize.y = Math.Min(GUILayoutUtility.GetLastRect().yMax + kContentPadding * 2, kWindowHeight * 3);
}
GUILayout.EndVertical();
GUILayout.EndScrollView();
}
static void DrawStackedFloatField(GUIContent label, GUIContent firstFieldLabel, GUIContent secondFieldLabel, ref float near, ref float far, float propertyLabelsWidth, params GUILayoutOption[] options)
{
bool hasLabel = EditorGUI.LabelHasContent(label);
float height = EditorGUI.kSingleLineHeight * 2 + EditorGUI.kVerticalSpacingMultiField;
Rect r = EditorGUILayout.GetControlRect(hasLabel, height, EditorStyles.numberField, options);
Rect fieldPosition = EditorGUI.PrefixLabel(r, label);
fieldPosition.height = EditorGUI.kSingleLineHeight;
float oldLabelWidth = EditorGUIUtility.labelWidth;
int oldIndentLevel = EditorGUI.indentLevel;
EditorGUIUtility.labelWidth = propertyLabelsWidth;
EditorGUI.indentLevel = 0;
near = EditorGUI.FloatField(fieldPosition, firstFieldLabel, near);
fieldPosition.y += EditorGUI.kSingleLineHeight + EditorGUI.kVerticalSpacingMultiField;
far = EditorGUI.FloatField(fieldPosition, secondFieldLabel, far);
EditorGUI.indentLevel = oldIndentLevel;
EditorGUIUtility.labelWidth = oldLabelWidth;
}
internal static void ShowContextMenu(SceneView view)
{
var menu = new GenericMenu();
menu.AddItem(Styles.copyPlacementLabel, false, () => CopyPlacement(view));
if (CanPastePlacement())
menu.AddItem(Styles.pastePlacementLabel, false, () => PastePlacement(view));
else
menu.AddDisabledItem(Styles.pastePlacementLabel);
menu.AddItem(Styles.copySettingsLabel, false, () => CopySettings(view));
if (Clipboard.HasCustomValue<SceneView.CameraSettings>())
menu.AddItem(Styles.pasteSettingsLabel, false, () => PasteSettings(view));
else
menu.AddDisabledItem(Styles.pasteSettingsLabel);
menu.AddItem(Styles.resetSettingsLabel, false, () => ResetSettings(view));
menu.ShowAsContext();
}
// ReSharper disable once UnusedMember.Local - called by a shortcut
[Shortcut("Camera/Copy Placement")]
static void CopyPlacementShortcut()
{
// if we are interacting with a game view, copy the main camera placement
var playView = PlayModeView.GetLastFocusedPlayModeView();
if (playView != null && (EditorWindow.focusedWindow == playView || EditorWindow.mouseOverWindow == playView))
{
var cam = Camera.main;
if (cam != null)
Clipboard.SetCustomValue(new TransformWorldPlacement(cam.transform));
}
// otherwise copy the last active scene view placement
else
{
var sceneView = SceneView.lastActiveSceneView;
if (sceneView != null)
CopyPlacement(sceneView);
}
}
static void CopyPlacement(SceneView view)
{
Clipboard.SetCustomValue(new TransformWorldPlacement(view.camera.transform));
}
// ReSharper disable once UnusedMember.Local - called by a shortcut
[Shortcut("Camera/Paste Placement")]
static void PastePlacementShortcut()
{
var sceneView = SceneView.lastActiveSceneView;
if (sceneView == null) return;
if (CanPastePlacement())
PastePlacement(sceneView);
}
static bool CanPastePlacement()
{
return Clipboard.HasCustomValue<TransformWorldPlacement>();
}
static void PastePlacement(SceneView view)
{
var tr = view.camera.transform;
var placement = Clipboard.GetCustomValue<TransformWorldPlacement>();
tr.position = placement.position;
tr.rotation = placement.rotation;
tr.localScale = placement.scale;
// Similar to what AlignViewToObject does, except we need to do that instantly
// in case the shortcut key was pressed while FPS camera controls (right click drag)
// were active.
view.size = 10;
view.LookAt(tr.position + tr.forward * view.cameraDistance, tr.rotation, view.size, view.orthographic, true);
view.Repaint();
}
static void CopySettings(SceneView view)
{
Clipboard.SetCustomValue(view.cameraSettings);
}
static void PasteSettings(SceneView view)
{
view.cameraSettings = Clipboard.GetCustomValue<SceneView.CameraSettings>();
view.Repaint();
}
static void ResetSettings(SceneView view)
{
view.ResetCameraSettings();
view.Repaint();
}
}
}
| UnityCsReference/Editor/Mono/Annotation/SceneViewCameraWindow.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Annotation/SceneViewCameraWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 5692
} | 289 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor;
using UnityEngine;
namespace UnityEditorInternal
{
[ExcludeFromPreset]
public sealed partial class AssemblyDefinitionImporter : AssetImporter
{
}
public sealed partial class AssemblyDefinitionAsset : TextAsset
{
private AssemblyDefinitionAsset() {}
private AssemblyDefinitionAsset(string text) {}
}
}
| UnityCsReference/Editor/Mono/AssetPipeline/AssemblyDefinitionImporter.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetPipeline/AssemblyDefinitionImporter.cs",
"repo_id": "UnityCsReference",
"token_count": 158
} | 290 |
// 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.AssetImporters;
using UnityEngine;
namespace UnityEditor.SpeedTree.Importer
{
class SpeedTree9ImporterMaterialEditor : BaseSpeedTree9ImporterTabUI
{
private static class Styles
{
public static GUIContent RemapOptions = EditorGUIUtility.TrTextContent("On Demand Remap");
public static GUIContent RemapMaterialsInProject = EditorGUIUtility.TrTextContent("Search and Remap...", "Click on this button to search and remap the materials from the project.");
public static GUIContent ExternalMaterialMappings = EditorGUIUtility.TrTextContent("Remapped Materials", "External materials to use for each embedded material.");
public static GUIContent Materials = EditorGUIUtility.TrTextContent("Materials");
public static GUIContent ExtractEmbeddedMaterials = EditorGUIUtility.TrTextContent("Extract Materials...", "Click on this button to extract the embedded materials.");
public static GUIContent InternalMaterialHelp = EditorGUIUtility.TrTextContent("Materials are embedded inside the imported asset.");
public static GUIContent MaterialAssignmentsHelp = EditorGUIUtility.TrTextContent("Material assignments can be remapped below.");
public static GUIContent ExternalMaterialSearchHelp = EditorGUIUtility.TrTextContent("Searches the user provided directory and matches the materials that share the same name and LOD with the originally imported material.");
public static GUIContent SelectMaterialFolder = EditorGUIUtility.TrTextContent("Select Materials Folder");
}
private SpeedTree9Importer m_STImporter;
private SerializedProperty m_ExternalObjects;
private bool m_ShowMaterialRemapOptions;
private bool m_HasEmbeddedMaterials;
private bool ImporterHasEmbeddedMaterials
{
get
{
bool materialsValid = m_OutputImporterData.lodMaterials.materials.Count > 0
&& m_OutputImporterData.lodMaterials.materials.TrueForAll(p => p.material != null);
return m_OutputImporterData.hasEmbeddedMaterials && materialsValid;
}
}
public SpeedTree9ImporterMaterialEditor(AssetImporterEditor panelContainer)
: base(panelContainer)
{ }
internal override void OnEnable()
{
base.OnEnable();
m_STImporter = target as SpeedTree9Importer;
m_ExternalObjects = serializedObject.FindProperty("m_ExternalObjects");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
ShowMaterialGUI();
serializedObject.ApplyModifiedProperties();
}
private bool HasEmbeddedMaterials()
{
if (m_OutputImporterData.materialsIdentifiers.Count == 0 || !ImporterHasEmbeddedMaterials)
return false;
// if the m_ExternalObjecs map has any unapplied changes, keep the state of the button as is
if (m_ExternalObjects.serializedObject.hasModifiedProperties)
return m_HasEmbeddedMaterials;
m_HasEmbeddedMaterials = true;
foreach (var t in m_ExternalObjects.serializedObject.targetObjects)
{
var externalObjectMap = m_STImporter.GetExternalObjectMap();
var materialsList = m_OutputImporterData.materialsIdentifiers.ToArray();// m_STImporter.m_Materials.ToArray();
int remappedMaterialCount = 0;
foreach (var entry in externalObjectMap)
{
bool isMatValid = Array.Exists(materialsList, x => x.name == entry.Key.name && entry.Value != null);
if (entry.Key.type == typeof(Material) && isMatValid)
++remappedMaterialCount;
}
m_HasEmbeddedMaterials = m_HasEmbeddedMaterials && remappedMaterialCount != materialsList.Length;
}
return m_HasEmbeddedMaterials;
}
private void ShowMaterialGUI()
{
serializedObject.UpdateIfRequiredOrScript();
string materialHelp = string.Empty;
int arraySize = m_OutputImporterData.materialsIdentifiers.Count;
if (arraySize > 0 && HasEmbeddedMaterials())
{
// we're generating materials inside the prefab
materialHelp = Styles.InternalMaterialHelp.text;
}
if (targets.Length == 1 && arraySize > 0)
{
materialHelp += " " + Styles.MaterialAssignmentsHelp.text;
}
if (ExtractMaterialsGUI())
{
// Necessary to avoid the error "BeginLayoutGroup must be called first".
GUIUtility.ExitGUI();
return;
}
if (!string.IsNullOrEmpty(materialHelp))
{
EditorGUILayout.HelpBox(materialHelp, MessageType.Info);
}
// The material remap list
if (targets.Length == 1 && arraySize > 0)
{
GUILayout.Label(Styles.ExternalMaterialMappings, EditorStyles.boldLabel);
if (MaterialRemapOptions())
return;
// The list of material names is immutable, whereas the map of external objects can change based on user actions.
// For each material name, map the external object associated with it.
// The complexity comes from the fact that we may not have an external object in the map, so we can't make a property out of it
for (int materialIdx = 0; materialIdx < arraySize; ++materialIdx)
{
string name = m_OutputImporterData.materialsIdentifiers[materialIdx].name;
string type = m_OutputImporterData.materialsIdentifiers[materialIdx].type;
SerializedProperty materialProp = null;
Material material = null;
int propertyIdx = 0;
for (int externalObjectIdx = 0, count = m_ExternalObjects.arraySize; externalObjectIdx < count; ++externalObjectIdx)
{
SerializedProperty pair = m_ExternalObjects.GetArrayElementAtIndex(externalObjectIdx);
string externalName = pair.FindPropertyRelative("first.name").stringValue;
string externalType = pair.FindPropertyRelative("first.type").stringValue;
// Cannot do a strict comparison, since externalType is set to "UnityEngine:Material" (C++)
// and type "UnityEngine.Material" (C#).
bool typeMatching = externalType.Contains("Material") && type.Contains("Material");
if (externalName == name && typeMatching)
{
materialProp = pair.FindPropertyRelative("second");
material = materialProp != null ? materialProp.objectReferenceValue as Material : null;
// If 'material' is null, it's likely because it was deleted. So we assign null to 'materialProp'
// to avoid the 'missing material' reference error in the UI.
materialProp = (material != null) ? pair.FindPropertyRelative("second") : null;
propertyIdx = externalObjectIdx;
break;
}
}
GUIContent nameLabel = EditorGUIUtility.TextContent(name);
nameLabel.tooltip = name;
if (materialProp != null)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.ObjectField(materialProp, typeof(Material), nameLabel);
if (EditorGUI.EndChangeCheck())
{
if (materialProp.objectReferenceValue == null)
{
m_ExternalObjects.DeleteArrayElementAtIndex(propertyIdx);
}
}
}
else
{
EditorGUI.BeginChangeCheck();
material = EditorGUILayout.ObjectField(nameLabel, material, typeof(Material), false) as Material;
if (EditorGUI.EndChangeCheck())
{
if (material != null)
{
int newIndex = m_ExternalObjects.arraySize++;
SerializedProperty pair = m_ExternalObjects.GetArrayElementAtIndex(newIndex);
pair.FindPropertyRelative("first.name").stringValue = name;
pair.FindPropertyRelative("first.type").stringValue = type;
pair.FindPropertyRelative("second").objectReferenceValue = material;
}
}
}
}
}
}
private bool ExtractMaterialsGUI()
{
bool buttonPressed = false;
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel(Styles.Materials);
using (new EditorGUI.DisabledScope(!HasEmbeddedMaterials()))
{
buttonPressed = GUILayout.Button(Styles.ExtractEmbeddedMaterials);
if (buttonPressed)
{
// use the first target for selecting the destination folder, but apply that path for all targets
string destinationPath = m_STImporter.assetPath;
destinationPath = EditorUtility.SaveFolderPanel(Styles.SelectMaterialFolder.text,
FileUtil.DeleteLastPathNameComponent(destinationPath), "");
if (string.IsNullOrEmpty(destinationPath))
{
// Cancel the extraction if the user did not select a folder.
EditorGUILayout.EndHorizontal();
return buttonPressed;
}
destinationPath = FileUtil.GetProjectRelativePath(destinationPath);
try
{
// batch the extraction of the materials
AssetDatabase.StartAssetEditing();
PrefabUtility.ExtractMaterialsFromAsset(targets, destinationPath);
}
finally
{
AssetDatabase.StopAssetEditing();
}
}
}
}
EditorGUILayout.EndHorizontal();
// AssetDatabase.StopAssetEditing() invokes OnEnable(), which invalidates all the serialized properties, so we must return.
return buttonPressed;
}
private bool MaterialRemapOptions()
{
bool buttonPressed = false;
m_ShowMaterialRemapOptions = EditorGUILayout.Foldout(m_ShowMaterialRemapOptions, Styles.RemapOptions);
if (m_ShowMaterialRemapOptions)
{
EditorGUI.indentLevel++;
EditorGUILayout.HelpBox(Styles.ExternalMaterialSearchHelp.text, MessageType.Info);
EditorGUI.indentLevel--;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
using (new EditorGUI.DisabledScope(assetTarget == null))
{
buttonPressed = GUILayout.Button(Styles.RemapMaterialsInProject);
if (buttonPressed)
{
bool bStartedAssetEditing = false;
try
{
foreach (var t in targets)
{
string folderToSearch = m_STImporter.GetMaterialFolderPath();
folderToSearch = EditorUtility.OpenFolderPanel(Styles.SelectMaterialFolder.text, folderToSearch, "");
bool bUserSelectedAFolder = folderToSearch != ""; // folderToSearch is empty if the user cancels the window
if (bUserSelectedAFolder)
{
string projectRelativePath = FileUtil.GetProjectRelativePath(folderToSearch);
bool bRelativePathIsNotEmpty = projectRelativePath != "";
if (bRelativePathIsNotEmpty)
{
AssetDatabase.StartAssetEditing();
bStartedAssetEditing = true;
m_STImporter.SearchAndRemapMaterials(projectRelativePath);
AssetDatabase.WriteImportSettingsIfDirty(m_STImporter.assetPath);
AssetDatabase.ImportAsset(m_STImporter.assetPath, ImportAssetOptions.ForceUpdate);
}
else
{
Debug.LogWarning("Selected folder is outside of the project's folder hierarchy, please provide a folder from the project.\n");
}
}
}
}
finally
{
if (bStartedAssetEditing)
{
AssetDatabase.StopAssetEditing();
}
}
}
}
}
EditorGUILayout.Space();
}
return buttonPressed;
}
}
}
| UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTree9ImporterMaterialEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTree9ImporterMaterialEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 7560
} | 291 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditorInternal;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace UnityEditor
{
/**
* An asset store asset.
*/
public sealed class AssetStoreAsset
{
/* Search result data
*
* This is returned when searching for assets
*/
public int id;
public string name;
public string displayName; // name without extension, we cache it to prevent string operations when rendering
public string staticPreviewURL;
public string dynamicPreviewURL;
public string className;
public string price;
public int packageID;
/* Preview data
*
* This is returned when clicking on an assets for preview
*/
internal class PreviewInfo
{
public string packageName;
public string packageShortUrl;
public int packageSize;
public string packageVersion;
public int packageRating;
public int packageAssetCount;
public bool isPurchased;
public bool isDownloadable;
public string publisherName;
public string encryptionKey;
public string packageUrl;
public float buildProgress; // -1 when not building
public float downloadProgress; // -1 when not downloading
public string categoryName;
}
internal PreviewInfo previewInfo;
//
public Texture2D previewImage;
internal AssetBundleCreateRequest previewBundleRequest;
internal AssetBundle previewBundle;
internal Object previewAsset;
internal bool disposed;
// public AssetStoreAssetsInfo assetsInfo;
public AssetStoreAsset()
{
disposed = false;
}
public void Dispose()
{
if (previewImage != null)
{
Object.DestroyImmediate(previewImage);
previewImage = null;
}
if (previewBundle != null)
{
previewBundle.Unload(true);
previewBundle = null;
previewAsset = null;
}
disposed = true;
}
public Object Preview
{
get
{
if (previewAsset != null)
return previewAsset;
return previewImage;
}
}
public bool HasLivePreview
{
get
{
return previewAsset != null;
}
}
internal string DebugString
{
get
{
string r = string.Format("id: {0}\nname: {1}\nstaticPreviewURL: {2}\ndynamicPreviewURL: {3}\n" +
"className: {4}\nprice: {5}\npackageID: {6}",
id, name ?? "N/A", staticPreviewURL ?? "N/A", dynamicPreviewURL ?? "N/A", className ?? "N/A", price, packageID);
if (previewInfo != null)
{
r += string.Format("previewInfo {{\n" +
" packageName: {0}\n" +
" packageShortUrl: {1}\n" +
" packageSize: {2}\n" +
" packageVersion: {3}\n" +
" packageRating: {4}\n" +
" packageAssetCount: {5}\n" +
" isPurchased: {6}\n" +
" isDownloadable: {7}\n" +
" publisherName: {8}\n" +
" encryptionKey: {9}\n" +
" packageUrl: {10}\n" +
" buildProgress: {11}\n" +
" downloadProgress: {12}\n" +
" categoryName: {13}\n" +
"}}",
previewInfo.packageName ?? "N/A",
previewInfo.packageShortUrl ?? "N/A",
previewInfo.packageSize,
previewInfo.packageVersion ?? "N/A",
previewInfo.packageRating,
previewInfo.packageAssetCount,
previewInfo.isPurchased,
previewInfo.isDownloadable,
previewInfo.publisherName ?? "N/A",
previewInfo.encryptionKey ?? "N/A",
previewInfo.packageUrl ?? "N/A",
previewInfo.buildProgress,
previewInfo.downloadProgress,
previewInfo.categoryName ?? "N/A");
}
return r;
}
}
}
/**
* An asset store asset selection.
*
* This class works as a singleton for keeping the list of selected
* asset store assets. This is not handled by the normal select framework
* because an asset store asset does not have an instanceID since it is not
* actually an asset in the local project.
*
* Currently there is only support for handling a single selected asset store
* asset at a time. This class is somewhat prepared for multiple asset store asset
* selections though.
*/
internal static class AssetStoreAssetSelection
{
public delegate void AssetsRefreshed();
static internal Dictionary<int, AssetStoreAsset> s_SelectedAssets;
public static void AddAsset(AssetStoreAsset searchResult, Texture2D placeholderPreviewImage)
{
if (placeholderPreviewImage != null)
searchResult.previewImage = ScaleImage(placeholderPreviewImage, 256, 256);
searchResult.previewInfo = null;
searchResult.previewBundleRequest = null;
// Dynamic previews is asset bundles to be displayed in
// the inspector. Static previews are images.
if (!string.IsNullOrEmpty(searchResult.dynamicPreviewURL) && searchResult.previewBundle == null)
{
// Debug.Log("dyn url " + searchResult.disposed.ToString() + " " + searchResult.dynamicPreviewURL);
searchResult.disposed = false;
// searchResult.previewBundle = AssetBundle.CreateFromFile("/users/jonasd/test.unity3d");
// searchResult.previewAsset = searchResult.previewBundle.mainAsset;
// Request the asset bundle data from the url and register a callback
AsyncHTTPClient client = new AsyncHTTPClient(searchResult.dynamicPreviewURL);
client.doneCallback = delegate(IAsyncHTTPClient c) {
if (!client.IsSuccess())
{
System.Console.WriteLine("Error downloading dynamic preview: " + client.text);
// Try the static preview instead
searchResult.dynamicPreviewURL = null;
DownloadStaticPreview(searchResult);
return;
}
// We only suppport one asset so grab the first one
AssetStoreAsset sel = GetFirstAsset();
// Make sure that the selection hasn't changed meanwhile
if (searchResult.disposed || sel == null || searchResult.id != sel.id)
{
//Debug.Log("dyn disposed " + searchResult.disposed.ToString() + " " + (sel == null ? "null" : sel.id.ToString()) + " " + searchResult.id.ToString());
return;
}
// Go create the asset bundle in memory from the binary blob asynchronously
try
{
AssetBundleCreateRequest cr = AssetBundle.LoadFromMemoryAsync(c.bytes);
// Workaround: Don't subject the bundle to the usual compatibility checks. We want
// to stay compatible with previews created in prior versions of Unity and with the
// stuff we put into previews, we should generally be able to still load the content
// in the editor.
cr.DisableCompatibilityChecks();
searchResult.previewBundleRequest = cr;
EditorApplication.CallbackFunction callback = null;
// The callback will be called each tick and check if the asset bundle is ready
double startTime = EditorApplication.timeSinceStartup;
callback = () => {
AssetStoreUtils.UpdatePreloading();
if (!cr.isDone)
{
double nowTime = EditorApplication.timeSinceStartup;
if (nowTime - startTime > 10.0)
{
// Timeout. Stop polling
EditorApplication.update -= callback;
System.Console.WriteLine("Timed out fetch live preview bundle " +
(searchResult.dynamicPreviewURL ?? "<n/a>"));
// Debug.Log("Not done Timed out" + cr.progress.ToString() );
}
else
{
// Debug.Log("Not done " + cr.progress.ToString() );
}
return;
}
// Done cooking. Stop polling.
EditorApplication.update -= callback;
// Make sure that the selection hasn't changed meanwhile
AssetStoreAsset sel2 = GetFirstAsset();
if (searchResult.disposed || sel2 == null || searchResult.id != sel2.id)
{
// No problem. Just ignore.
// Debug.Log("dyn late disposed " + searchResult.disposed.ToString() + " " + (sel2 == null ? "null" : sel2.id.ToString()) + " " + searchResult.id.ToString());
}
else
{
searchResult.previewBundle = cr.assetBundle;
#pragma warning disable 618
if (cr.assetBundle == null || cr.assetBundle.mainAsset == null)
{
// Failed downloading live preview. Fallback to static
searchResult.dynamicPreviewURL = null;
DownloadStaticPreview(searchResult);
}
else
searchResult.previewAsset = searchResult.previewBundle.mainAsset;
#pragma warning restore 618
}
};
EditorApplication.update += callback;
}
catch (System.Exception e)
{
System.Console.Write(e.Message);
Debug.Log(e.Message);
}
};
client.Begin();
}
else if (!string.IsNullOrEmpty(searchResult.staticPreviewURL))
{
DownloadStaticPreview(searchResult);
}
// searchResult.previewBundle = null;
AddAssetInternal(searchResult);
RefreshFromServer(null);
}
// Also used by AssetStoreToolUtils
internal static void AddAssetInternal(AssetStoreAsset searchResult)
{
if (s_SelectedAssets == null)
s_SelectedAssets = new Dictionary<int, AssetStoreAsset>();
s_SelectedAssets[searchResult.id] = searchResult;
}
static void DownloadStaticPreview(AssetStoreAsset searchResult)
{
AsyncHTTPClient client = new AsyncHTTPClient(searchResult.staticPreviewURL);
client.doneCallback = delegate(IAsyncHTTPClient c) {
if (!client.IsSuccess())
{
System.Console.WriteLine("Error downloading static preview: " + client.text);
// Debug.LogError("Error downloading static preview: " + client.text);
return;
}
// Need to put the texture through some scaling magic in order for the
// TextureInspector to be able to show it.
// TODO: This is a workaround and should be fixed.
Texture2D srcTex = c.texture;
Texture2D tex = new Texture2D(srcTex.width, srcTex.height, TextureFormat.RGB24, false, true);
AssetStorePreviewManager.ScaleImage(tex.width, tex.height, srcTex, tex, null);
// tex.Compress(true);
searchResult.previewImage = tex;
Object.DestroyImmediate(srcTex);
AssetStoreAssetInspector.Instance.Repaint();
};
client.Begin();
}
// Refresh information about displayed asset by quering the
// asset store server. This is typically after the user has
// logged in because we need to know if he already owns the
// displayed asset.
public static void RefreshFromServer(AssetsRefreshed callback)
{
if (s_SelectedAssets.Count == 0)
return;
// Refetch assetInfo
// Query the asset store for more info
List<AssetStoreAsset> queryAssets = new List<AssetStoreAsset>();
foreach (KeyValuePair<int, AssetStoreAsset> qasset in s_SelectedAssets)
queryAssets.Add(qasset.Value);
// This will fill the queryAssets with extra preview data
AssetStoreClient.AssetsInfo(queryAssets,
delegate(AssetStoreAssetsInfo results) {
AssetStoreAssetInspector.paymentAvailability = AssetStoreAssetInspector.PaymentAvailability.ServiceDisabled;
if (!string.IsNullOrEmpty(results.error))
{
System.Console.WriteLine("Error performing Asset Store Info search: " + results.error);
AssetStoreAssetInspector.OfflineNoticeEnabled = true;
//Debug.LogError("Error performing Asset Store Info search: " + results.error);
if (callback != null) callback();
return;
}
AssetStoreAssetInspector.OfflineNoticeEnabled = false;
if (results.status == AssetStoreAssetsInfo.Status.Ok)
AssetStoreAssetInspector.paymentAvailability = AssetStoreAssetInspector.PaymentAvailability.Ok;
else if (results.status == AssetStoreAssetsInfo.Status.BasketNotEmpty)
AssetStoreAssetInspector.paymentAvailability = AssetStoreAssetInspector.PaymentAvailability.BasketNotEmpty;
else if (results.status == AssetStoreAssetsInfo.Status.AnonymousUser)
AssetStoreAssetInspector.paymentAvailability = AssetStoreAssetInspector.PaymentAvailability.AnonymousUser;
AssetStoreAssetInspector.s_PurchaseMessage = results.message;
AssetStoreAssetInspector.s_PaymentMethodCard = results.paymentMethodCard;
AssetStoreAssetInspector.s_PaymentMethodExpire = results.paymentMethodExpire;
AssetStoreAssetInspector.s_PriceText = results.priceText;
AssetStoreAssetInspector.Instance.Repaint();
if (callback != null) callback();
});
}
private static Texture2D ScaleImage(Texture2D source, int w, int h)
{
// Bug: When scaling down things look weird unless the source size is
// == 0 when mod 4. Therefore we just return null if that's the case.
if (source.width % 4 != 0)
return null;
Texture2D result = new Texture2D(w, h, TextureFormat.RGB24, false, true);
Color[] rpixels = result.GetPixels(0);
double dx = 1.0 / (double)w;
double dy = 1.0 / (double)h;
double x = 0;
double y = 0;
int idx = 0;
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++, idx++)
{
rpixels[idx] = source.GetPixelBilinear((float)x, (float)y);
x += dx;
}
x = 0;
y += dy;
}
result.SetPixels(rpixels, 0);
result.Apply();
return result;
}
public static bool ContainsAsset(int id)
{
return s_SelectedAssets != null && s_SelectedAssets.ContainsKey(id);
}
public static void Clear()
{
if (s_SelectedAssets == null)
return;
foreach (var kv in s_SelectedAssets)
kv.Value.Dispose();
s_SelectedAssets.Clear();
}
public static int Count
{
get { return s_SelectedAssets == null ? 0 : s_SelectedAssets.Count; }
}
public static bool Empty
{
get { return s_SelectedAssets == null ? true : s_SelectedAssets.Count == 0; }
}
public static AssetStoreAsset GetFirstAsset()
{
if (s_SelectedAssets == null)
return null;
var i = s_SelectedAssets.GetEnumerator();
if (!i.MoveNext())
return null;
return i.Current.Value;
}
}
/**
* In addition to being an inspector for AssetStoreAssets this
* inspector works as the object that is selected when an
* asset store asset is selected ie.
* Selection.object == AssetStoreAssetInspector.Instance
* when asset store assets are selected.
*/
[CustomEditor(typeof(AssetStoreAssetInspector))]
internal class AssetStoreAssetInspector : Editor
{
static AssetStoreAssetInspector s_SharedAssetStoreAssetInspector;
public static AssetStoreAssetInspector Instance
{
get
{
if (s_SharedAssetStoreAssetInspector == null)
{
s_SharedAssetStoreAssetInspector = ScriptableObject.CreateInstance<AssetStoreAssetInspector>();
s_SharedAssetStoreAssetInspector.hideFlags = HideFlags.HideAndDontSave;
}
return s_SharedAssetStoreAssetInspector;
}
}
class Styles
{
public GUIStyle link = new GUIStyle(EditorStyles.label);
public Styles()
{
link.normal.textColor = new Color(.26f, .51f, .75f, 1f);
}
}
static Styles styles;
bool packageInfoShown = true;
// Payment info for all selected assets
internal static string s_PurchaseMessage = "";
internal static string s_PaymentMethodCard = "";
internal static string s_PaymentMethodExpire = "";
internal static string s_PriceText = "";
static GUIContent[] sStatusWheel;
public static bool OfflineNoticeEnabled { get; set; }
// Asset store payment availability
internal enum PaymentAvailability
{
BasketNotEmpty,
ServiceDisabled,
AnonymousUser,
Ok
}
internal static PaymentAvailability m_PaymentAvailability;
internal static PaymentAvailability paymentAvailability
{
get
{
if (AssetStoreClient.LoggedOut())
m_PaymentAvailability = PaymentAvailability.AnonymousUser;
return m_PaymentAvailability;
}
set
{
if (AssetStoreClient.LoggedOut())
m_PaymentAvailability = PaymentAvailability.AnonymousUser;
else
m_PaymentAvailability = value;
}
}
int lastAssetID;
// Callback for curl to call
public void OnDownloadProgress(string id, string message, int bytes, int total)
{
AssetStoreAsset activeAsset = AssetStoreAssetSelection.GetFirstAsset();
if (activeAsset == null) return;
AssetStoreAsset.PreviewInfo info = activeAsset.previewInfo;
if (info == null) return;
if (activeAsset.packageID.ToString() != id)
return;
if ((message == "downloading" || message == "connecting") && !OfflineNoticeEnabled)
{
info.downloadProgress = (float)bytes / (float)total;
}
else
{
info.downloadProgress = -1f;
}
Repaint();
}
public void Update()
{
// Repaint if asset has changed.
// This has to be done here because the .target is always set to
// this inspector when inspecting asset store assets.
AssetStoreAsset a = AssetStoreAssetSelection.GetFirstAsset();
bool hasProgress = a != null && a.previewInfo != null && (a.previewInfo.buildProgress >= 0f || a.previewInfo.downloadProgress >= 0f);
if ((a == null && lastAssetID != 0) ||
(a != null && lastAssetID != a.id) ||
hasProgress)
{
lastAssetID = a == null ? 0 : a.id;
Repaint();
}
// Repaint when the main asset of a possibly downloaded bundle is ready for preview
if (a != null && a.previewBundle != null)
{
a.previewBundle.Unload(false);
a.previewBundle = null;
Repaint();
}
}
public override void OnInspectorGUI()
{
if (styles == null)
{
// Set the singleton in case the DrawEditors() has created this window
s_SharedAssetStoreAssetInspector = this;
styles = new Styles();
}
AssetStoreAsset activeAsset = AssetStoreAssetSelection.GetFirstAsset();
AssetStoreAsset.PreviewInfo info = null;
if (activeAsset != null)
info = activeAsset.previewInfo;
if (activeAsset != null)
target.name = string.Format("Asset Store: {0}", activeAsset.name);
else
target.name = "Asset Store";
EditorGUILayout.BeginVertical();
bool guiEnabled = GUI.enabled;
GUI.enabled = activeAsset != null && activeAsset.packageID != 0;
if (OfflineNoticeEnabled)
{
Color col = GUI.color;
GUI.color = Color.yellow;
GUILayout.Label("Network is offline");
GUI.color = col;
}
if (activeAsset != null)
{
string typeName = activeAsset.className == null ? "" : activeAsset.className.Split(new char[] {' '}, 2)[0];
bool isPackage = activeAsset.id == -activeAsset.packageID;
if (isPackage)
typeName = "Package";
if (activeAsset.HasLivePreview)
typeName = activeAsset.Preview.GetType().Name;
EditorGUILayout.LabelField("Type", typeName);
if (isPackage)
{
packageInfoShown = true;
}
else
{
EditorGUILayout.Separator();
packageInfoShown = EditorGUILayout.Foldout(packageInfoShown , "Part of package", true);
}
if (packageInfoShown)
{
EditorGUILayout.LabelField("Name", info == null ? "-" : info.packageName);
EditorGUILayout.LabelField("Version", info == null ? "-" : info.packageVersion);
string price = info == null ? "-" : (!string.IsNullOrEmpty(activeAsset.price) ? activeAsset.price : "free");
EditorGUILayout.LabelField("Price", price);
string rating = info != null && info.packageRating >= 0 ? info.packageRating + " of 5" : "-";
EditorGUILayout.LabelField("Rating", rating);
EditorGUILayout.LabelField("Size", info == null ? "-" : intToSizeString(info.packageSize));
string assetCount = info != null && info.packageAssetCount >= 0 ? info.packageAssetCount.ToString() : "-";
EditorGUILayout.LabelField("Asset count", assetCount);
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Web page");
bool hasPageUrl = info != null && info.packageShortUrl != null && info.packageShortUrl != "";
bool guiBefore = GUI.enabled;
GUI.enabled = hasPageUrl;
if (GUILayout.Button(hasPageUrl ? new GUIContent(info.packageShortUrl, "View in browser") : EditorGUIUtility.TempContent("-"), styles.link))
{
Application.OpenURL(info.packageShortUrl);
}
if (GUI.enabled)
EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
GUI.enabled = guiBefore;
GUILayout.EndHorizontal();
EditorGUILayout.LabelField("Publisher", info == null ? "-" : info.publisherName);
}
if (activeAsset.id != 0)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Open Asset Store", GUILayout.Height(40), GUILayout.Width(120)))
{
OpenItemInAssetStore(activeAsset);
GUIUtility.ExitGUI();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
GUILayout.FlexibleSpace();
}
EditorWrapper editor = previewEditor;
if (editor != null && activeAsset != null && activeAsset.HasLivePreview)
editor.OnAssetStoreInspectorGUI();
GUI.enabled = guiEnabled;
EditorGUILayout.EndVertical();
}
public static void OpenItemInAssetStore(AssetStoreAsset activeAsset)
{
if (activeAsset.id != 0)
{
AssetStore.Open(string.Format("content/{0}?assetID={1}", activeAsset.packageID, activeAsset.id));
}
}
private static string intToSizeString(int inValue)
{
if (inValue < 0)
return "unknown";
float val = (float)inValue;
string[] scale = new string[] { "TB", "GB", "MB", "KB", "Bytes" };
int idx = scale.Length - 1;
while (val > 1000.0f && idx >= 0)
{
val /= 1000f;
idx--;
}
if (idx < 0)
return "<error>";
return UnityString.Format("{0:#.##} {1}", val, scale[idx]);
}
public override bool HasPreviewGUI()
{
return (target != null && AssetStoreAssetSelection.Count != 0);
}
EditorWrapper m_PreviewEditor;
Object m_PreviewObject;
public void OnEnable()
{
EditorApplication.update += Update;
AssetStoreUtils.RegisterDownloadDelegate(this);
}
public void OnDisable()
{
EditorApplication.update -= Update;
if (m_PreviewEditor != null)
{
m_PreviewEditor.Dispose();
m_PreviewEditor = null;
}
if (m_PreviewObject != null)
m_PreviewObject = null;
AssetStoreUtils.UnRegisterDownloadDelegate(this);
}
private EditorWrapper previewEditor
{
get
{
AssetStoreAsset asset = AssetStoreAssetSelection.GetFirstAsset();
if (asset == null) return null;
Object preview = asset.Preview;
if (preview == null) return null;
if (preview != m_PreviewObject)
{
m_PreviewObject = preview;
if (m_PreviewEditor != null)
m_PreviewEditor.Dispose();
m_PreviewEditor = EditorWrapper.Make(m_PreviewObject, EditorFeatures.PreviewGUI);
}
return m_PreviewEditor;
}
}
public override void OnPreviewSettings()
{
AssetStoreAsset asset = AssetStoreAssetSelection.GetFirstAsset();
if (asset == null) return;
EditorWrapper editor = previewEditor;
if (editor != null && asset.HasLivePreview)
editor.OnPreviewSettings();
}
public override string GetInfoString()
{
EditorWrapper editor = previewEditor;
AssetStoreAsset a = AssetStoreAssetSelection.GetFirstAsset();
if (a == null)
return "No item selected";
if (editor != null && a.HasLivePreview)
return editor.GetInfoString();
return "";
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
if (m_PreviewObject == null) return;
EditorWrapper editor = previewEditor;
// Special handling for animation clips because they only have
// an interactive preview available which shows play button etc.
// The OnPreviewGUI is also used for the small icons in the top
// of the inspectors where buttons should not be rendered.
if (editor != null && m_PreviewObject is AnimationClip)
editor.OnPreviewGUI(r, background); // currently renders nothing for animation clips
else
OnInteractivePreviewGUI(r, background);
}
public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
EditorWrapper editor = previewEditor;
if (editor != null)
{
editor.OnInteractivePreviewGUI(r, background);
}
// If the live preview is not available yes the show a spinner
AssetStoreAsset a = AssetStoreAssetSelection.GetFirstAsset();
if (a != null && !a.HasLivePreview && !string.IsNullOrEmpty(a.dynamicPreviewURL))
{
GUIContent c = StatusWheel;
r.y += (r.height - c.image.height) / 2f;
r.x += (r.width - c.image.width) / 2f;
GUI.Label(r, StatusWheel);
Repaint();
}
}
static GUIContent StatusWheel
{
get
{
if (sStatusWheel == null)
{
sStatusWheel = new GUIContent[12];
for (int i = 0; i < 12; i++)
{
GUIContent gc = new GUIContent();
gc.image = EditorGUIUtility.LoadIcon("WaitSpin" + i.ToString("00")) as Texture2D;
sStatusWheel[i] = gc;
}
}
int frame = (int)Mathf.Repeat(Time.realtimeSinceStartup * 10, 11.99f);
return sStatusWheel[frame];
}
}
public override GUIContent GetPreviewTitle()
{
return GUIContent.Temp("Asset Store Preview");
}
} // Inspector class
}
| UnityCsReference/Editor/Mono/AssetStore/AssetStoreAsset.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetStore/AssetStoreAsset.cs",
"repo_id": "UnityCsReference",
"token_count": 16462
} | 292 |
// 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.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Analytics;
namespace UnityEditor.Audio.Analytics;
class AudioRandomContainerBuildAnalyticsEvent : IPostprocessBuildWithReport
{
[AnalyticInfo(eventName: "audioRandomContainerBuild", vendorKey: "unity.audio", maxEventsPerHour: 60, maxNumberOfElements: 2)]
internal class AudioRandomAnalytic : IAnalytic
{
public AudioRandomAnalytic(string build_guid, int count)
{
this.build_guid = build_guid;
this.count = count;
}
[Serializable]
struct Payload : IAnalytic.IData
{
public string build_guid;
public int count;
}
public bool TryGatherData(out IAnalytic.IData data, out Exception error)
{
error = null;
data = new Payload
{
build_guid = build_guid,
count = count
};
return data != null;
}
private string build_guid;
private int count;
}
public int callbackOrder { get; }
public void OnPostprocessBuild(BuildReport report)
{
SendEvent(report);
}
static void SendEvent(BuildReport report)
{
if (!EditorAnalytics.enabled
|| AudioSettings.unityAudioDisabled
|| report == null
|| report.packedAssets.Length == 0)
{
return;
}
var count = 0;
for (var i = 0; i < report.packedAssets.Length; ++i)
{
var infos = report.packedAssets[i].GetContents();
for (var j = 0; j < infos.Length; ++j)
{
if (infos[j].type == typeof(AudioRandomContainer))
{
++count;
}
}
}
EditorAnalytics.SendAnalytic(new AudioRandomAnalytic(report.summary.guid.ToString(), count));
}
}
| UnityCsReference/Editor/Mono/Audio/Analytics/AudioRandomContainerBuildAnalyticsEvent.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/Analytics/AudioRandomContainerBuildAnalyticsEvent.cs",
"repo_id": "UnityCsReference",
"token_count": 995
} | 293 |
// 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.Linq;
using System;
using UnityEditorInternal;
using UnityEditor.Audio;
using System.Globalization;
using UnityEngine.Audio;
using Object = UnityEngine.Object;
namespace UnityEditor
{
internal class AudioMixerChannelStripView
{
[Serializable]
public class State
{
public Vector2 m_ScrollPos = new Vector2(0, 0);
}
public static float kVolumeScaleMouseDrag = 1.0f;
public static float kEffectScaleMouseDrag = 0.3f; // higher precision for effect slot editing
private static Color kMoveColorHighlight = new Color(0.3f, 0.6f, 1.0f, 0.4f);
private static Color kMoveSlotColHiAllowed = new Color(1f, 1f, 1f, 0.7f); //new Color(59 / 255f, 162 / 255f, 216 / 255f, 0.7f);
private static Color kMoveSlotColLoAllowed = new Color(1f, 1f, 1f, 0.0f);
private static Color kMoveSlotColBorderAllowed = new Color(1f, 1f, 1f, 1.0f);
private static Color kMoveSlotColHiDisallowed = new Color(1.0f, 0.0f, 0.0f, 0.7f);
private static Color kMoveSlotColLoDisallowed = new Color(0.8f, 0.0f, 0.0f, 0.0f);
private static Color kMoveSlotColBorderDisallowed = new Color(1.0f, 0.0f, 0.0f, 1.0f);
private static int kRectSelectionHashCode = "RectSelection".GetHashCode();
private static int kEffectDraggingHashCode = "EffectDragging".GetHashCode();
private static int kVerticalFaderHash = "VerticalFader".GetHashCode();
public int m_FocusIndex = -1;
public int m_IndexCounter = 0;
public int m_EffectInteractionControlID;
public int m_RectSelectionControlID;
public float m_MouseDragStartX = 0.0f;
public float m_MouseDragStartY = 0.0f;
public float m_MouseDragStartValue = 0.0f;
public Vector2 m_RectSelectionStartPos = new Vector2(0, 0);
public Rect m_RectSelectionRect = new Rect(0, 0, 0, 0);
State m_State;
private AudioMixerController m_Controller;
private MixerGroupControllerCompareByName m_GroupComparer = new MixerGroupControllerCompareByName();
private bool m_WaitingForDragEvent = false;
private int m_ChangingWetMixIndex = -1;
private int m_MovingEffectSrcIndex = -1;
private int m_MovingEffectDstIndex = -1;
private Rect m_MovingSrcRect = new Rect(-1, -1, 0, 0);
private Rect m_MovingDstRect = new Rect(-1, -1, 0, 0);
private bool m_MovingEffectAllowed = false;
private AudioMixerGroupController m_MovingSrcGroup = null;
private AudioMixerGroupController m_MovingDstGroup = null;
private const float k_MinVULevel = -80f;
private List<int> m_LastNumChannels = new List<int>();
private bool m_RequiresRepaint = false;
public bool requiresRepaint
{
get
{
if (m_RequiresRepaint)
{
m_RequiresRepaint = false;
return true;
}
return false;
}
}
const float headerHeight = 22f;
const float vuHeight = 170f;
const float dbHeight = 17f;
const float soloMuteBypassHeight = 30f;
const float effectHeight = 16f;
const float spaceBetween = 0;
const int channelStripSpacing = 4;
const float channelStripBaseWidth = 90f;
const float spaceBetweenMainGroupsAndReferenced = 50f;
readonly Vector2 channelStripsOffset = new Vector2(15, 10);
// For background ui
static Texture2D m_GridTexture;
private const float kGridTileWidth = 12.0f;
private static readonly Color kGridColorDark = new Color(0f, 0f, 0f, 0.18f);
private static readonly Color kGridColorLight = new Color(0f, 0f, 0f, 0.10f);
private static Color gridColor
{
get
{
if (EditorGUIUtility.isProSkin)
return kGridColorDark;
else
return kGridColorLight;
}
}
private AudioMixerDrawUtils.Styles styles
{
get { return AudioMixerDrawUtils.styles; }
}
public AudioMixerChannelStripView(AudioMixerChannelStripView.State state)
{
m_State = state;
}
static Texture2D CreateTilableGridTexture(int width, int height, Color backgroundColor, Color lineColor)
{
Color[] pixels = new Color[width * height];
// background
for (int i = 0; i < height * width; i++)
pixels[i] = backgroundColor;
// right edge
for (int i = 0; i < height; i++)
pixels[i * width + (width - 1)] = lineColor;
// bottom edge
for (int i = 0; i < width; i++)
pixels[(height - 1) * width + i] = lineColor;
Texture2D texture = new Texture2D(width, height, TextureFormat.RGBA32, false);
texture.hideFlags = HideFlags.HideAndDontSave;
texture.SetPixels(pixels);
texture.Apply();
return texture;
}
Texture2D gridTextureTilable
{
get
{
if (m_GridTexture == null)
m_GridTexture = CreateTilableGridTexture((int)kGridTileWidth, (int)kGridTileWidth, new Color(0, 0, 0, 0), gridColor);
return m_GridTexture;
}
}
void DrawAreaBackground(Rect rect)
{
if (Event.current.type == EventType.Repaint)
{
// Draw background
Color prevColor = GUI.color;
GUI.color = new Color(1, 1, 1, EditorGUIUtility.isProSkin ? 0.6f : 0.2f);
AudioMixerDrawUtils.styles.channelStripAreaBackground.Draw(rect, false, false, false, false);
GUI.color = prevColor;
// Draw grid
//GUI.DrawTextureWithTexCoords (rect, gridTextureTilable, new Rect(0, 0, rect.width / gridTextureTilable.width, rect.height / gridTextureTilable.height), true);
}
}
private void SetFocus() { m_FocusIndex = m_IndexCounter; }
private void ClearFocus() { m_FocusIndex = -1; }
private bool HasFocus() { return m_FocusIndex == m_IndexCounter; }
private bool IsFocusActive() { return m_FocusIndex != -1; }
public class EffectContext
{
public EffectContext(AudioMixerController controller, AudioMixerGroupController[] groups, int index, string name)
{
this.controller = controller;
this.groups = groups;
this.index = index;
this.name = name;
}
public AudioMixerController controller;
public AudioMixerGroupController[] groups;
public int index;
public string name;
}
public static void InsertEffectPopupCallback(object obj)
{
EffectContext context = (EffectContext)obj;
foreach (AudioMixerGroupController group in context.groups)
{
Undo.RecordObject(group, "Add effect");
AudioMixerEffectController newEffect = new AudioMixerEffectController(context.name);
int index = (context.index == -1 || context.index > group.effects.Length) ? group.effects.Length : context.index;
group.InsertEffect(newEffect, index);
AssetDatabase.AddObjectToAsset(newEffect, context.controller);
newEffect.PreallocateGUIDs();
}
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
public void RemoveEffectPopupCallback(object obj)
{
EffectContext context = (EffectContext)obj;
foreach (AudioMixerGroupController group in context.groups)
{
if (context.index >= group.effects.Length)
continue;
AudioMixerEffectController effect = group.effects[context.index];
context.controller.RemoveEffect(effect, group);
}
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
public class ConnectSendContext
{
public ConnectSendContext(AudioMixerController controller, AudioMixerEffectController sendEffect, AudioMixerEffectController targetEffect)
{
this.controller = controller;
this.sendEffect = sendEffect;
this.targetEffect = targetEffect;
}
public AudioMixerController controller;
public AudioMixerEffectController sendEffect;
public AudioMixerEffectController targetEffect;
}
public static void ConnectSendPopupCallback(object obj)
{
var context = (ConnectSendContext)obj;
if (context.targetEffect == null)
{
var guid = context.sendEffect.GetGUIDForMixLevel();
if (context.controller.ContainsExposedParameter(guid))
{
Undo.RecordObjects(new Object[] {context.controller, context.sendEffect}, "Remove Send Target");
context.controller.RemoveExposedParameter(guid);
}
}
else
{
Undo.RecordObject(context.sendEffect, "Change Send Target");
}
context.sendEffect.sendTarget = context.targetEffect;
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
private bool ClipRect(Rect r, Rect clipRect, ref Rect overlap)
{
overlap.x = Mathf.Max(r.x, clipRect.x);
overlap.y = Mathf.Max(r.y, clipRect.y);
overlap.width = Mathf.Min(r.x + r.width, clipRect.x + clipRect.width) - overlap.x;
overlap.height = Mathf.Min(r.y + r.height, clipRect.y + clipRect.height) - overlap.y;
return overlap.width > 0.0f && overlap.height > 0.0f;
}
public float VerticalFader(Rect r, float value, int direction, float dragScale, bool drawScaleValues, bool drawMarkerValue, string tooltip, float maxValue, GUIStyle style)
{
Event evt = Event.current;
int handleHeight = (int)style.fixedHeight;
int faderScreenRange = (int)r.height - handleHeight;
float valueScreenPos = AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(value, AudioMixerController.kMinVolume, maxValue), faderScreenRange, true);
Rect handleRect = new Rect(r.x, r.y + (int)valueScreenPos, r.width, handleHeight);
int controlID = GUIUtility.GetControlID(kVerticalFaderHash, FocusType.Passive);
switch (evt.GetTypeForControl(controlID))
{
case EventType.MouseDown:
if (r.Contains(evt.mousePosition) && GUIUtility.hotControl == 0)
{
m_MouseDragStartY = evt.mousePosition.y;
m_MouseDragStartValue = valueScreenPos;
GUIUtility.hotControl = controlID;
evt.Use();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == controlID)
{
GUIUtility.hotControl = 0;
evt.Use();
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == controlID)
{
valueScreenPos = Mathf.Clamp(m_MouseDragStartValue + dragScale * (evt.mousePosition.y - m_MouseDragStartY), 0.0f, faderScreenRange);
value = Mathf.Clamp(AudioMixerController.VolumeToScreenMapping(valueScreenPos, faderScreenRange, false), AudioMixerController.kMinVolume, maxValue);
evt.Use();
}
break;
case EventType.Repaint:
// Ticks and Numbers
if (drawScaleValues)
{
float tickStartY = r.y + handleHeight / 2f;
float level = maxValue;
using (new EditorGUI.DisabledScope(true))
{
while (level >= AudioMixerController.kMinVolume)
{
float y = AudioMixerController.VolumeToScreenMapping(level, faderScreenRange, true);
if (level / 10 % 2 == 0)
GUI.Label(new Rect(r.x, tickStartY + y - 7, r.width, 14), GUIContent.Temp(Mathf.RoundToInt(level).ToString()), styles.vuValue);
EditorGUI.DrawRect(new Rect(r.x, tickStartY + y - 1, 5f, 1), new Color(0, 0, 0, 0.5f));
level -= 10.0f;
}
}
}
// Drag handle
if (drawMarkerValue)
style.Draw(handleRect, GUIContent.Temp(Mathf.RoundToInt(value).ToString()), false, false, false, false);
else
style.Draw(handleRect, false, false, false, false);
AudioMixerDrawUtils.AddTooltipOverlay(handleRect, tooltip);
break;
}
return value;
}
private static Color hfaderCol1 = new Color(0.2f, 0.2f, 0.2f, 1.0f);
private static Color hfaderCol2 = new Color(0.4f, 0.4f, 0.4f, 1.0f);
public float HorizontalFader(Rect r, float value, float minValue, float maxValue, int direction, float dragScale)
{
m_IndexCounter++;
Rect r2 = new Rect(r);
float handleWidth = r.width * 0.2f, faderScreenRange = r2.width - handleWidth;
AudioMixerDrawUtils.DrawGradientRect(r2, hfaderCol1, hfaderCol2);
Event evt = Event.current;
if (evt.type == EventType.MouseDown && r2.Contains(evt.mousePosition))
{
m_MouseDragStartX = evt.mousePosition.x;
m_MouseDragStartValue = value;
SetFocus();
}
if (HasFocus())
{
if (evt.type == EventType.MouseDrag)
{
value = m_MouseDragStartValue + (dragScale * (maxValue - minValue) * (evt.mousePosition.x - m_MouseDragStartX) / faderScreenRange);
Event.current.Use();
}
else if (evt.type == EventType.MouseUp)
{
ClearFocus();
Event.current.Use();
}
}
value = Mathf.Clamp(value, minValue, maxValue);
r2.x = r.x;
r2.width = r.width;
r2.x = r.x + faderScreenRange * ((value - minValue) / (maxValue - minValue));
r2.width = handleWidth;
AudioMixerDrawUtils.DrawGradientRect(r2, hfaderCol2, hfaderCol1);
return value;
}
public GUIStyle GetEffectBarStyle(AudioMixerEffectController effect)
{
if (effect.IsSend() || effect.IsReceive() || effect.IsDuckVolume())
return styles.sendReturnBar;
if (effect.IsAttenuation())
return styles.attenuationBar;
return styles.effectBar;
}
class PatchSlot
{
public AudioMixerGroupController group;
public float x, y;
}
GUIContent bypassButtonContent = EditorGUIUtility.TrTextContent("", "Toggle bypass on this effect");
void EffectSlot(Rect effectRect, AudioMixerSnapshotController snapshot, AudioMixerEffectController effect, int effectIndex, ref int highlightEffectIndex, ChannelStripParams p, ref Dictionary<AudioMixerEffectController, PatchSlot> patchslots)
{
if (effect == null)
return;
Rect r = effectRect;
Event evt = Event.current;
if (evt.type == EventType.Repaint && patchslots != null && (effect.IsSend() || MixerEffectDefinitions.EffectCanBeSidechainTarget(effect)))
{
var c = new PatchSlot();
c.group = p.group;
c.x = r.xMax - (r.yMax - r.yMin) * 0.5f;
c.y = (r.yMin + r.yMax) * 0.5f;
patchslots[effect] = c;
}
// Bypass button
const float bypassWidth = 10.0f;
bool isBypassable = !effect.DisallowsBypass();
Rect bypassRect = r; bypassRect.width = bypassWidth;
r.xMin += bypassWidth;
if (isBypassable)
{
// Handle mouse input is first, rendering is further down (to render on top).
if (GUI.Button(bypassRect, bypassButtonContent, GUIStyle.none))
{
Undo.RecordObject(effect, "Bypass Effect");
effect.bypass = !effect.bypass;
m_Controller.UpdateBypass();
InspectorWindow.RepaintAllInspectors();
}
}
// Effect
m_IndexCounter++;
// Repaint
// We are using the following GUIStyle backgrounds for:
// Normal: Disabled by bypass or group bypass
// Hover: Enabled, not draggable
// Active: Enabled, background for draggable bar
// Focused: Enabled, foreground for draggable bar
float level = Mathf.Clamp(effect.GetValueForMixLevel(m_Controller, snapshot), AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect);
bool showLevel = (effect.IsSend() && effect.sendTarget != null) || effect.enableWetMix;
if (evt.type == EventType.Repaint)
{
GUIStyle style = GetEffectBarStyle(effect);
float drawLevel = (showLevel) ? ((level - AudioMixerController.kMinVolume) / (AudioMixerController.kMaxEffect - AudioMixerController.kMinVolume)) : 1.0f;
bool enabled = (!p.group.bypassEffects && !effect.bypass) || effect.DisallowsBypass();
Color col1 = AudioMixerDrawUtils.GetEffectColor(effect);
if (!enabled)
col1 = new Color(col1.r * 0.5f, col1.g * 0.5f, col1.b * 0.5f);
if (enabled)
{
if (drawLevel < 1.0f)
{
// Bar forground (we need special for small widths because style rendering with borders have a min width to work)
float forgroundWidth = r.width * drawLevel;
const float minimumWidthForBorderSetup = 4f;
if (forgroundWidth < minimumWidthForBorderSetup)
{
// Forground less than minimumWidthForBorderSetup (Always show marker to indicate the slot is draggable)
const float markerWidth = 2f;
forgroundWidth = Mathf.Max(forgroundWidth, markerWidth);
float frac = 1f - forgroundWidth / minimumWidthForBorderSetup;
Color orgColor = GUI.color;
if (!GUI.enabled)
GUI.color = new Color(1, 1, 1, 0.5f);
GUI.DrawTextureWithTexCoords(new Rect(r.x, r.y, forgroundWidth, r.height), style.focused.background, new Rect(frac, 0f, 1f - frac, 1f));
GUI.color = orgColor;
}
else
{
// Forground larger than minimumWidthForBorderSetup (uses border setup)
style.Draw(new Rect(r.x, r.y, forgroundWidth, r.height), false, false, false, true);
}
// Bar background
GUI.DrawTexture(new Rect(r.x + forgroundWidth, r.y, r.width - forgroundWidth, r.height), style.onFocused.background, ScaleMode.StretchToFill);
}
else
{
//GUI.DrawTexture(r, showLevel ? style.focused.background : style.hover.background, ScaleMode.StretchToFill);
style.Draw(r, !showLevel, false, false, showLevel);
}
// Cursor icon needs to proper work with dragging: TODO use hotcontrol
//if (showLevel)
// EditorGUIUtility.AddCursorRect(r, MouseCursor.SlideArrow);
}
else
{
// Disabled
style.Draw(r, false, false, false, false);
}
// Bypass toggle
if (isBypassable)
styles.circularToggle.Draw(new Rect(bypassRect.x + 2, bypassRect.y + 5f, bypassRect.width - 2, bypassRect.width - 2f), false, false, !effect.bypass, false);
if (effect.IsSend() && effect.sendTarget != null)
{
bypassRect.y -= 1;
GUI.Label(bypassRect, styles.sendString, EditorStyles.miniLabel);
}
using (new EditorGUI.DisabledScope(!enabled))
{
string name = GetEffectSlotName(effect, showLevel, snapshot, p);
string tooltip = GetEffectSlotTooltip(effect, r, p);
GUI.Label(new Rect(r.x, r.y, r.width - bypassWidth, r.height), GUIContent.Temp(name, tooltip), styles.effectName);
}
}
else
{
EffectSlotDragging(effectRect, snapshot, effect, showLevel, level, effectIndex, ref highlightEffectIndex, p);
}
}
string GetEffectSlotName(AudioMixerEffectController effect, bool showLevel, AudioMixerSnapshotController snapshot, ChannelStripParams p)
{
if (m_ChangingWetMixIndex == m_IndexCounter && showLevel)
{
return UnityString.Format("{0:F1} dB", effect.GetValueForMixLevel(m_Controller, snapshot));
}
if (effect.IsSend() && effect.sendTarget != null)
{
return effect.GetSendTargetDisplayString(p.effectMap);
}
return effect.effectName;
}
string GetEffectSlotTooltip(AudioMixerEffectController effect, Rect effectRect, ChannelStripParams p)
{
// Only fetch a tooltip if the cursor is inside the rect
if (!effectRect.Contains(Event.current.mousePosition))
return string.Empty;
if (effect.IsSend())
{
if (effect.sendTarget != null)
{
string sendTarget = effect.GetSendTargetDisplayString(p.effectMap);
return "Send to: " + sendTarget; // We add the tooltip here because we rarely
}
else
{
return styles.emptySendSlotGUIContent.tooltip;
}
}
if (effect.IsReceive())
{
return styles.returnSlotGUIContent.tooltip;
}
if (effect.IsDuckVolume())
{
return styles.duckVolumeSlotGUIContent.tooltip;
}
if (effect.IsAttenuation())
{
return styles.attenuationSlotGUIContent.tooltip;
}
// Tooltip for all other effects
return styles.effectSlotGUIContent.tooltip;
}
private void EffectSlotDragging(Rect r, AudioMixerSnapshotController snapshot, AudioMixerEffectController effect, bool showLevel, float level, int effectIndex, ref int highlightEffectIndex, ChannelStripParams p)
{
Event evt = Event.current;
switch (evt.GetTypeForControl(m_EffectInteractionControlID))
{
case EventType.MouseDown:
if (r.Contains(evt.mousePosition) && evt.button == 0 && GUIUtility.hotControl == 0)
{
GUIUtility.hotControl = m_EffectInteractionControlID;
m_MouseDragStartX = evt.mousePosition.x;
m_MouseDragStartValue = level;
highlightEffectIndex = effectIndex;
m_MovingEffectSrcIndex = -1;
m_MovingEffectDstIndex = -1;
m_WaitingForDragEvent = true;
m_MovingSrcRect = r;
m_MovingDstRect = r;
m_MovingSrcGroup = p.group;
m_MovingDstGroup = p.group;
m_MovingEffectAllowed = true;
SetFocus();
Event.current.Use();
EditorGUIUtility.SetWantsMouseJumping(1);
InspectorWindow.RepaintAllInspectors();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == m_EffectInteractionControlID && evt.button == 0 && p.stripRect.Contains(evt.mousePosition))
{
if (m_MovingEffectDstIndex != -1 && m_MovingEffectAllowed)
{
if (IsDuplicateKeyPressed() && CanDuplicateDraggedEffect())
{
// Duplicate effect
AudioMixerEffectController sourceEffect = m_MovingSrcGroup.effects[m_MovingEffectSrcIndex];
AudioMixerEffectController copiedEffect = m_MovingSrcGroup.controller.CopyEffect(sourceEffect);
var targetEffects = m_MovingDstGroup.effects.ToList();
if (AudioMixerController.InsertEffect(copiedEffect, ref targetEffects, m_MovingEffectDstIndex))
{
m_MovingDstGroup.effects = targetEffects.ToArray();
}
}
else
{
// Move effect
if (m_MovingSrcGroup == m_MovingDstGroup)
{
var effects = m_MovingSrcGroup.effects.ToList();
if (AudioMixerController.MoveEffect(ref effects, m_MovingEffectSrcIndex, ref effects, m_MovingEffectDstIndex))
{
m_MovingSrcGroup.effects = effects.ToArray();
}
}
else if (!m_MovingSrcGroup.effects[m_MovingEffectSrcIndex].IsAttenuation())
{
var sourceEffects = m_MovingSrcGroup.effects.ToList();
var targetEffects = m_MovingDstGroup.effects.ToList();
if (AudioMixerController.MoveEffect(ref sourceEffects, m_MovingEffectSrcIndex, ref targetEffects, m_MovingEffectDstIndex))
{
m_MovingSrcGroup.effects = sourceEffects.ToArray();
m_MovingDstGroup.effects = targetEffects.ToArray();
}
}
}
}
ClearEffectDragging(ref highlightEffectIndex);
evt.Use();
EditorGUIUtility.SetWantsMouseJumping(0);
GUIUtility.ExitGUI(); // We changed order of effects so stop iterating effects
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == m_EffectInteractionControlID)
{
// Detect direction of drag to decide if we want to adjust value or move effect
if (HasFocus() && m_WaitingForDragEvent && (evt.delta.x != 0 || evt.delta.y != 0))
{
m_ChangingWetMixIndex = -1;
if (effectIndex < p.group.effects.Length)
{
if (Mathf.Abs(evt.delta.y) > Mathf.Abs(evt.delta.x))
{
// Move effect
m_MovingEffectSrcIndex = effectIndex;
ClearFocus();
}
else
{
// Change wet mix value
m_ChangingWetMixIndex = m_IndexCounter;
}
}
m_WaitingForDragEvent = false;
}
// Moving effect so detect effect insertion on this strip
if (IsMovingEffect() && p.stripRect.Contains(evt.mousePosition))
{
float h2 = r.height * 0.5f;
float min = effectIndex == 0 ? -h2 : 0;
float max = effectIndex == p.group.effects.Length - 1 ? r.height + h2 : r.height;
float dy = evt.mousePosition.y - r.y;
if (dy >= min && dy <= max && effectIndex < p.group.effects.Length)
{
int newMovingEffectDstIndex = (dy < h2) ? effectIndex : (effectIndex + 1);
if (newMovingEffectDstIndex != m_MovingEffectDstIndex || m_MovingDstGroup != p.group)
{
m_MovingDstRect.x = r.x;
m_MovingDstRect.width = r.width;
m_MovingDstRect.y = ((dy < h2) ? r.y : (r.y + r.height)) - 1;
m_MovingEffectDstIndex = newMovingEffectDstIndex;
m_MovingDstGroup = p.group;
m_MovingEffectAllowed =
!(m_MovingSrcGroup.effects[m_MovingEffectSrcIndex].IsAttenuation() && m_MovingSrcGroup != m_MovingDstGroup) &&
!AudioMixerController.WillMovingEffectCauseFeedback(p.allGroups, m_MovingSrcGroup, m_MovingEffectSrcIndex, m_MovingDstGroup, newMovingEffectDstIndex, null) &&
(!IsDuplicateKeyPressed() || CanDuplicateDraggedEffect());
}
evt.Use(); // We use when having valid pos so because if drag event is not used after all strips we clear drag destination to remove insert hightlight for invalid positions
}
}
// Changing wetmix level
if (IsAdjustingWetMix() && HasFocus())
{
if (showLevel)
{
m_WaitingForDragEvent = false;
float tmp = kEffectScaleMouseDrag * HandleUtility.niceMouseDelta + level;
float deltaLevel = Mathf.Clamp(tmp, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect) - level;
if (deltaLevel != 0.0f)
{
Undo.RecordObject(m_Controller.TargetSnapshot, "Change effect level");
if (effect.IsSend() && m_Controller.CachedSelection.Count > 1 && m_Controller.CachedSelection.Contains(p.group))
{
List<AudioMixerEffectController> changeEffects = new List<AudioMixerEffectController>();
foreach (var g in m_Controller.CachedSelection)
foreach (var e in g.effects)
if (e.effectName == effect.effectName && e.sendTarget == effect.sendTarget)
changeEffects.Add(e);
foreach (var e in changeEffects)
if (!e.IsSend() || e.sendTarget != null)
e.SetValueForMixLevel(
m_Controller,
snapshot,
Mathf.Clamp(e.GetValueForMixLevel(m_Controller, snapshot) + deltaLevel, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect));
}
else
{
if (!effect.IsSend() || effect.sendTarget != null)
effect.SetValueForMixLevel(
m_Controller,
snapshot,
Mathf.Clamp(level + deltaLevel, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect));
}
InspectorWindow.RepaintAllInspectors();
}
evt.Use();
}
}
}
break;
}
}
void ClearEffectDragging(ref int highlightEffectIndex)
{
if (GUIUtility.hotControl == m_EffectInteractionControlID)
GUIUtility.hotControl = 0;
m_MovingEffectSrcIndex = -1;
m_MovingEffectDstIndex = -1;
m_MovingSrcRect = new Rect(-1, -1, 0, 0);
m_MovingDstRect = new Rect(-1, -1, 0, 0);
m_MovingSrcGroup = null;
m_MovingDstGroup = null;
m_ChangingWetMixIndex = -1;
highlightEffectIndex = -1;
ClearFocus();
InspectorWindow.RepaintAllInspectors();
}
void UnhandledEffectDraggingEvents(ref int highlightEffectIndex)
{
Event evt = Event.current;
switch (evt.GetTypeForControl(m_EffectInteractionControlID))
{
case EventType.MouseUp:
if (GUIUtility.hotControl == m_EffectInteractionControlID && evt.button == 0)
{
ClearEffectDragging(ref highlightEffectIndex);
evt.Use();
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == m_EffectInteractionControlID)
{
// Clear dst group when dragging outside the strips
m_MovingEffectDstIndex = -1;
m_MovingDstRect = new Rect(-1, -1, 0, 0);
m_MovingDstGroup = null;
evt.Use();
}
break;
case EventType.Repaint:
if (IsMovingEffect())
{
// Mark the effect being dragged
if (evt.type == EventType.Repaint)
{
EditorGUI.DrawRect(m_MovingSrcRect, kMoveColorHighlight);
// Set + cursor when duplicating dragged effect
var cursor = (IsDuplicateKeyPressed() && m_MovingEffectAllowed) ? MouseCursor.ArrowPlus : MouseCursor.ResizeVertical;
EditorGUIUtility.AddCursorRect(new Rect(evt.mousePosition.x - 10, evt.mousePosition.y - 10, 20, 20), cursor, m_EffectInteractionControlID);
}
}
if (m_MovingEffectDstIndex != -1 && m_MovingDstRect.y >= 0.0f)// && m_MovingEffectDstIndex != m_MovingEffectSrcIndex && m_MovingEffectDstIndex != m_MovingEffectSrcIndex +1)
{
float kMoveRange = 2;
Color moveSlotColLo = (m_MovingEffectAllowed) ? kMoveSlotColLoAllowed : kMoveSlotColLoDisallowed;
Color moveSlotColHi = (m_MovingEffectAllowed) ? kMoveSlotColHiAllowed : kMoveSlotColHiDisallowed;
Color moveSlotColBorder = (m_MovingEffectAllowed) ? kMoveSlotColBorderAllowed : kMoveSlotColBorderDisallowed;
AudioMixerDrawUtils.DrawGradientRect(new Rect(m_MovingDstRect.x, m_MovingDstRect.y - kMoveRange, m_MovingDstRect.width, kMoveRange), moveSlotColLo, moveSlotColHi);
AudioMixerDrawUtils.DrawGradientRect(new Rect(m_MovingDstRect.x, m_MovingDstRect.y, m_MovingDstRect.width, kMoveRange), moveSlotColHi, moveSlotColLo);
AudioMixerDrawUtils.DrawGradientRect(new Rect(m_MovingDstRect.x, m_MovingDstRect.y - 1, m_MovingDstRect.width, 1), moveSlotColBorder, moveSlotColBorder);
}
break;
}
}
bool IsDuplicateKeyPressed()
{
return Event.current.alt;
}
bool CanDuplicateDraggedEffect()
{
if (IsMovingEffect() && m_MovingSrcGroup != null)
return !m_MovingSrcGroup.effects[m_MovingEffectSrcIndex].IsAttenuation();
return false;
}
private class BusConnection
{
public BusConnection(float srcX, float srcY, AudioMixerEffectController targetEffect, float mixLevel, Color col, bool isSend, bool isSelected)
{
this.srcX = srcX;
this.srcY = srcY;
this.targetEffect = targetEffect;
this.mixLevel = mixLevel;
this.color = col;
this.isSend = isSend;
this.isSelected = isSelected;
}
public AudioMixerEffectController targetEffect;
public float srcX;
public float srcY;
public float mixLevel;
public Color color;
public bool isSend;
public bool isSelected;
}
private void RecordSelectedGroupUndoState(List<AudioMixerGroupController> selection, string text)
{
foreach (var g in selection)
{
Undo.RecordObject(g, text);
}
}
private bool DoSoloButton(Rect r, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups, List<AudioMixerGroupController> selection)
{
Event evt = Event.current;
// Right click toggle
if (evt.type == EventType.MouseUp && evt.button == 1 && r.Contains(evt.mousePosition) && allGroups.Any(g => g.solo))
{
RecordSelectedGroupUndoState(selection, "Change solo state");
foreach (var g in allGroups)
g.solo = false;
evt.Use();
return true;
}
bool newState = GUI.Toggle(r, group.solo, styles.soloGUIContent, AudioMixerDrawUtils.styles.soloToggle);
if (newState != group.solo)
{
RecordSelectedGroupUndoState(selection, "Change solo state");
group.solo = !group.solo;
foreach (var g in selection)
g.solo = group.solo;
return true;
}
return false;
}
private bool DoMuteButton(Rect r, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups, bool anySoloActive, List<AudioMixerGroupController> selection)
{
Event evt = Event.current;
// Right click toggle
if (evt.type == EventType.MouseUp && evt.button == 1 && r.Contains(evt.mousePosition) && allGroups.Any(g => g.mute))
{
RecordSelectedGroupUndoState(selection, "Change mute state");
if (allGroups.Any(g => g.solo))
return false;
foreach (var g in allGroups)
g.mute = false;
evt.Use();
return true;
}
Color orgColor = GUI.color;
bool dimColor = anySoloActive && group.mute;
if (dimColor)
GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, 0.5f);
bool newState = GUI.Toggle(r, group.mute, styles.muteGUIContent, AudioMixerDrawUtils.styles.muteToggle);
if (dimColor)
GUI.color = orgColor;
if (newState != group.mute)
{
RecordSelectedGroupUndoState(selection, "Change mute state");
group.mute = !group.mute;
foreach (var g in selection)
g.mute = group.mute;
return true;
}
return false;
}
private bool DoBypassEffectsButton(Rect r, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups, List<AudioMixerGroupController> selection)
{
Event evt = Event.current;
// Right click toggle
if (evt.type == EventType.MouseUp && evt.button == 1 && r.Contains(evt.mousePosition) && allGroups.Any(g => g.bypassEffects))
{
RecordSelectedGroupUndoState(selection, "Change bypass state");
foreach (var g in allGroups)
g.bypassEffects = false;
evt.Use();
return true;
}
bool newState = GUI.Toggle(r, group.bypassEffects, styles.bypassGUIContent, AudioMixerDrawUtils.styles.bypassToggle);
if (newState != group.bypassEffects)
{
RecordSelectedGroupUndoState(selection, "Change bypass state");
group.bypassEffects = !group.bypassEffects;
foreach (var g in selection)
g.bypassEffects = group.bypassEffects;
return true;
}
return false;
}
private static bool RectOverlaps(Rect r1, Rect r2)
{
Rect overlap = new Rect();
overlap.x = Mathf.Max(r1.x, r2.x);
overlap.y = Mathf.Max(r1.y, r2.y);
overlap.width = Mathf.Min(r1.x + r1.width, r2.x + r2.width) - overlap.x;
overlap.height = Mathf.Min(r1.y + r1.height, r2.y + r2.height) - overlap.y;
return overlap.width > 0.0f && overlap.height > 0.0f;
}
bool IsRectSelectionActive()
{
return GUIUtility.hotControl == m_RectSelectionControlID;
}
// Handles multiselection (using shift + ctrl/cmd)
void GroupClicked(AudioMixerGroupController clickedGroup, ChannelStripParams p, bool clickedControlInGroup)
{
// Get ids from items
List<int> allIDs = new List<int>();
foreach (var group in p.shownGroups)
allIDs.Add(group.GetInstanceID());
List<int> selectedIDs = new List<int>();
foreach (var group in m_Controller.CachedSelection)
selectedIDs.Add(group.GetInstanceID());
int lastClickedID = selectedIDs.Count > 0 ? selectedIDs.Last() : 0;
bool allowMultiselection = true;
bool keepMultiSelection = Event.current.shift || clickedControlInGroup;
bool useShiftAsActionKey = false;
List<int> newSelection = InternalEditorUtility.GetNewSelection(clickedGroup.GetInstanceID(), allIDs, selectedIDs, lastClickedID, keepMultiSelection, useShiftAsActionKey, allowMultiselection);
List<AudioMixerGroupController> groups = (from x in p.allGroups where newSelection.Contains(x.GetInstanceID()) select x).ToList();
Selection.objects = groups.ToArray();
m_Controller.OnUnitySelectionChanged();
InspectorWindow.RepaintAllInspectors();
}
private void DoAttenuationFader(Rect r, AudioMixerGroupController group, List<AudioMixerGroupController> selection, GUIStyle style)
{
float volume = Mathf.Clamp(group.GetValueForVolume(m_Controller, m_Controller.TargetSnapshot), AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume());
float newVolume = VerticalFader(r, volume, 1, kVolumeScaleMouseDrag, true, true, styles.attenuationFader.tooltip, AudioMixerController.GetMaxVolume(), style);
if (volume != newVolume)
{
float deltaVolume = newVolume - volume;
Undo.RecordObject(m_Controller.TargetSnapshot, "Change volume fader");
foreach (var g in selection)
{
float vol = Mathf.Clamp(g.GetValueForVolume(m_Controller, m_Controller.TargetSnapshot), AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume());
g.SetValueForVolume(
m_Controller,
m_Controller.TargetSnapshot,
Mathf.Clamp(vol + deltaVolume, AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()));
}
InspectorWindow.RepaintAllInspectors();
}
}
static internal void AddEffectItemsToMenu(AudioMixerController controller, AudioMixerGroupController[] groups, int insertIndex, string prefix, GenericMenu pm)
{
string[] effectNames = MixerEffectDefinitions.GetEffectList();
for (int t = 0; t < effectNames.Length; t++)
{
if (effectNames[t] != "Attenuation")
pm.AddItem(new GUIContent(prefix + effectNames[t]),
false,
InsertEffectPopupCallback,
new EffectContext(controller, groups, insertIndex, effectNames[t]));
}
}
private void DoEffectSlotInsertEffectPopup(Rect buttonRect, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups,
int effectSlotIndex, ref Dictionary<AudioMixerEffectController, AudioMixerGroupController> effectMap)
{
GenericMenu pm = new GenericMenu();
AudioMixerGroupController[] groups = new AudioMixerGroupController[] { group };
if (effectSlotIndex < group.effects.Length)
{
var effect = group.effects[effectSlotIndex];
if (!effect.IsAttenuation() && !effect.IsSend() && !effect.IsReceive() && !effect.IsDuckVolume())
{
pm.AddItem(EditorGUIUtility.TrTextContent("Allow Wet Mixing (causes higher memory usage)"), effect.enableWetMix, delegate { AudioMixerUtility.ToggleEffectWetMix(effect); });
pm.AddItem(EditorGUIUtility.TrTextContent("Bypass"), effect.bypass, delegate { effect.bypass = !effect.bypass; m_Controller.UpdateBypass(); InspectorWindow.RepaintAllInspectors(); });
pm.AddSeparator("");
}
AddEffectItemsToMenu(group.controller, groups, effectSlotIndex, "Add effect before/", pm);
AddEffectItemsToMenu(group.controller, groups, effectSlotIndex + 1, "Add effect after/", pm);
}
else
{
// Add effect at the end of the list
AddEffectItemsToMenu(group.controller, groups, effectSlotIndex, "", pm);
}
if (effectSlotIndex < group.effects.Length)
{
var effect = group.effects[effectSlotIndex];
if (!effect.IsAttenuation())
{
pm.AddSeparator("");
pm.AddItem(EditorGUIUtility.TrTextContent("Remove"), false, RemoveEffectPopupCallback, new EffectContext(m_Controller, groups, effectSlotIndex, ""));
bool insertedSeparator = false;
if (effect.IsSend())
{
if (effect.sendTarget != null)
{
if (!insertedSeparator)
{
insertedSeparator = true;
pm.AddSeparator("");
}
var sendContext = new ConnectSendContext(group.controller, effect, null);
pm.AddItem(EditorGUIUtility.TrTextContent("Disconnect from '" + effect.GetSendTargetDisplayString(effectMap) + "'") , false, ConnectSendPopupCallback, sendContext);
}
if (!insertedSeparator)
AddSeperatorIfAnyReturns(pm, allGroups);
AddMenuItemsForReturns(pm, "Connect to ", effectSlotIndex, group, allGroups, effectMap, effect, false);
}
}
}
pm.DropDown(buttonRect);
Event.current.Use();
}
void AddSeperatorIfAnyReturns(GenericMenu pm, List<AudioMixerGroupController> allGroups)
{
foreach (var g in allGroups)
{
foreach (var ge in g.effects)
{
if (ge.IsReceive() || ge.IsDuckVolume())
{
pm.AddSeparator("");
return;
}
}
}
}
public static void AddMenuItemsForReturns(GenericMenu pm, string prefix, int effectIndex, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups,
Dictionary<AudioMixerEffectController, AudioMixerGroupController> effectMap, AudioMixerEffectController effect, bool showCurrent)
{
foreach (var g in allGroups)
{
foreach (var ge in g.effects)
{
if (MixerEffectDefinitions.EffectCanBeSidechainTarget(ge))
{
var identifiedLoop = new List<AudioMixerController.ConnectionNode>();
//TODO: In the future, consider allowing feedback loops, as the send code now allows for this, though give a warning to the user
// that they may be doing something stupid
if (!AudioMixerController.WillChangeOfEffectTargetCauseFeedback(allGroups, group, effectIndex, ge, identifiedLoop))
{
if (showCurrent || effect.sendTarget != ge)
{
var sendContext = new ConnectSendContext(group.controller, effect, ge);
pm.AddItem(new GUIContent(prefix + "'" + ge.GetDisplayString(effectMap) + "'"), effect.sendTarget == ge, ConnectSendPopupCallback, sendContext);
}
}
else
{
string baseString = "A connection to '" + ge.GetDisplayString(effectMap) + "' would result in a feedback loop/";
pm.AddDisabledItem(new GUIContent(baseString + "Loop: "));
int loopIndex = 1;
foreach (var s in identifiedLoop)
{
pm.AddDisabledItem(new GUIContent(baseString + loopIndex + ": " + s.GetDisplayString() + "->"));
loopIndex++;
}
pm.AddDisabledItem(new GUIContent(baseString + loopIndex + ": ..."));
}
}
}
}
}
public void VUMeter(AudioMixerGroupController group, Rect r, float level, float peak)
{
EditorGUI.VUMeter.VerticalMeter(r, level, peak, EditorGUI.VUMeter.verticalVUTexture, Color.grey);
}
private GUIContent headerGUIContent = new GUIContent();
class ChannelStripParams
{
public int index;
public Rect stripRect;
public Rect visibleRect;
public bool visible;
public AudioMixerGroupController group;
public int maxEffects;
public bool drawingBuses;
public bool anySoloActive;
public List<BusConnection> busConnections = new List<BusConnection>();
public List<AudioMixerGroupController> rectSelectionGroups = new List<AudioMixerGroupController>();
public List<AudioMixerGroupController> allGroups;
public List<AudioMixerGroupController> shownGroups;
public int numChannels = 0;
public float[] vuinfo_level = new float[9];
public float[] vuinfo_peak = new float[9];
//public int highlightEffectIndex;
public Dictionary<AudioMixerEffectController, AudioMixerGroupController> effectMap;
const float kAddEffectButtonHeight = 16f;
public List<Rect> bgRects;
public readonly int kHeaderIndex = 0;
public readonly int kVUMeterFaderIndex = 1;
public readonly int kTotalVULevelIndex = 2;
public readonly int kSoloMuteBypassIndex = 3;
public readonly int kEffectStartIndex = 4;
public void Init(AudioMixerController controller, Rect channelStripRect, int maxNumEffects)
{
numChannels = controller.GetGroupVUInfo(group.groupID, false, vuinfo_level, vuinfo_peak);
//numChannels = 8; // debugging
maxEffects = maxNumEffects;
bgRects = GetBackgroundRects(channelStripRect, group, maxEffects);
stripRect = channelStripRect;
stripRect.yMax = bgRects[bgRects.Count - 1].yMax; // Ensure full height
}
List<Rect> GetBackgroundRects(Rect r, AudioMixerGroupController group, int maxNumGroups)
{
List<float> heights = new List<float>();
heights.AddRange(Enumerable.Repeat(0f, kEffectStartIndex));
heights[kHeaderIndex] = headerHeight;
heights[kVUMeterFaderIndex] = vuHeight;
heights[kTotalVULevelIndex] = dbHeight;
heights[kSoloMuteBypassIndex] = soloMuteBypassHeight;
int maxNumEffectSlots = maxNumGroups; // maxNumGroups includes an empty slot used as button for adding new effect
for (int i = 0; i < maxNumEffectSlots; ++i)
heights.Add(effectHeight);
heights.Add(10f);
List<Rect> rects = new List<Rect>();
float curY = r.y;
foreach (int height in heights)
{
if (rects.Count > 0)
curY += spaceBetween;
rects.Add(new Rect(r.x, curY, r.width, height));
curY += height;
}
curY += 10f; // space between last effect and add button
rects.Add(new Rect(r.x, curY, r.width, kAddEffectButtonHeight));
return rects;
}
}
void DrawBackgrounds(ChannelStripParams p, bool selected)
{
if (Event.current.type == EventType.Repaint)
{
// Bg
styles.channelStripBg.Draw(p.stripRect, false, false, selected, false);
// Line over effects (todo: move to texture)
float lightColor = 119f / 255f;
float darkColor = 58f / 255f;
Color lineColor = EditorGUIUtility.isProSkin ? new Color(darkColor, darkColor, darkColor) : new Color(lightColor, lightColor, lightColor);
Rect lineRect = p.bgRects[p.kEffectStartIndex];
lineRect.y -= 1;
lineRect.height = 1;
EditorGUI.DrawRect(lineRect, lineColor);
// Optimize by rendering vu numbers and lines in one texture
//Rect vuNumbersRect = p.bgRects[1];
//vuNumbersRect.x = p.stripRect.xMax - 90f;
//vuNumbersRect.x = vuNumbersRect.xMax - AudioMixerDrawUtils.styles.channelStripVUMeterBg.normal.background.width; // right align
//AudioMixerDrawUtils.styles.channelStripVUMeterBg.Draw(vuNumbersRect, false, false, false, false); // 0 -80 dB numbers overlay
}
// User color
Rect colorRect = p.bgRects[p.kVUMeterFaderIndex];
colorRect.height = EditorGUIUtility.isProSkin ? 1 : 2;
colorRect.y -= colorRect.height;
int colorIndex = p.group.userColorIndex;
if (colorIndex != 0)
EditorGUI.DrawRect(colorRect, AudioMixerColorCodes.GetColor(colorIndex));
}
void OpenGroupContextMenu(AudioMixerGroupController[] groups)
{
GenericMenu pm = new GenericMenu();
AddEffectItemsToMenu(groups[0].controller, groups, 0, "Add effect at top/", pm);
AddEffectItemsToMenu(groups[0].controller, groups, -1, "Add effect at bottom/", pm);
pm.AddSeparator(string.Empty);
AudioMixerColorCodes.AddColorItemsToGenericMenu(pm, groups);
pm.AddSeparator(string.Empty);
pm.ShowAsContext();
}
private void DrawChannelStrip(ChannelStripParams p, ref int highlightEffectIndex, ref Dictionary<AudioMixerEffectController, PatchSlot> patchslots, bool showBusConnectionsOfSelection)
{
Event evt = Event.current;
bool mouseDownInsideStrip = evt.type == EventType.MouseDown && p.stripRect.Contains(evt.mousePosition);
// Selection rendering state
bool selected = m_Controller.CachedSelection.Contains(p.group);
if (IsRectSelectionActive())
{
if (RectOverlaps(p.stripRect, m_RectSelectionRect))
{
p.rectSelectionGroups.Add(p.group);
selected = true;
}
}
// Draw all background rects
DrawBackgrounds(p, selected);
// Header area
headerGUIContent.text = headerGUIContent.tooltip = p.group.GetDisplayString();
GUI.Label(p.bgRects[p.kHeaderIndex], headerGUIContent, AudioMixerDrawUtils.styles.channelStripHeaderStyle);
// VU Meter and attenuation area
Rect innerRect = new RectOffset(-6, 0, 0, -4).Add(p.bgRects[p.kVUMeterFaderIndex]);
float spaceBetweenColumns = 1f;
float column1Width = 54f;
float column2Width = innerRect.width - column1Width - spaceBetweenColumns;
Rect column1Rect = new Rect(innerRect.x, innerRect.y, column1Width, innerRect.height);
Rect column2Rect = new Rect(column1Rect.xMax + spaceBetweenColumns, innerRect.y, column2Width, innerRect.height);
float faderWidth = 29f;
Rect faderRect = new Rect(column2Rect.x, column2Rect.y, faderWidth, column2Rect.height);
Rect tripleButtonRect = p.bgRects[p.kSoloMuteBypassIndex];
GUIStyle attenuationMarkerStyle = AudioMixerDrawUtils.styles.channelStripAttenuationMarkerSquare;
using (new EditorGUI.DisabledScope(!AudioMixerController.EditingTargetSnapshot()))
{
DoVUMeters(column1Rect, attenuationMarkerStyle.fixedHeight, p);
DoAttenuationFader(faderRect, p.group, m_Controller.CachedSelection, attenuationMarkerStyle);
DoTotaldB(p);
DoEffectList(p, selected, ref highlightEffectIndex, ref patchslots, showBusConnectionsOfSelection);
}
// We want to be able to set mute, solo and bypass even when EditingTargetSnapshot is false for testing during gameplay
DoSoloMuteBypassButtons(tripleButtonRect, p.group, p.allGroups, m_Controller.CachedSelection, p.anySoloActive);
// Handle group click after all controls so we can detect if a control was clicked by checking if the event was used here
if (mouseDownInsideStrip && evt.button == 0)
GroupClicked(p.group, p, evt.type == EventType.Used);
// Check context click after all UI controls (only show if we did not interact with any controls)
if (evt.type == EventType.ContextClick && p.stripRect.Contains(evt.mousePosition))
{
evt.Use();
//If its part of an existing selection, then pass all, otherwise pretend its a new selection
if (selected)
OpenGroupContextMenu(m_Controller.CachedSelection.ToArray());
else
OpenGroupContextMenu(new AudioMixerGroupController[] { p.group });
}
}
void DoTotaldB(ChannelStripParams p)
{
// Right align db but shown centered (prevents 'db' from jumping around)
float textWidth = 50f;
styles.totalVULevel.padding.right = (int)((p.stripRect.width - textWidth) * 0.5f);
float vu_level = Mathf.Max(p.vuinfo_level[8], k_MinVULevel);
Rect rect = p.bgRects[p.kTotalVULevelIndex];
GUI.Label(rect, string.Format(CultureInfo.InvariantCulture.NumberFormat, "{0:F1} dB", vu_level), styles.totalVULevel);
}
GUIContent addText = EditorGUIUtility.TrTextContent("Add...");
void DoEffectList(ChannelStripParams p, bool selected, ref int highlightEffectIndex, ref Dictionary<AudioMixerEffectController, PatchSlot> patchslots, bool showBusConnectionsOfSelection)
{
Event evt = Event.current;
for (int i = 0; i < p.maxEffects; i++)
{
Rect effectRect = p.bgRects[p.kEffectStartIndex + i];
if (i < p.group.effects.Length)
{
AudioMixerEffectController effect = p.group.effects[i];
if (p.visible)
{
// Use right click event first
if (evt.type == EventType.ContextClick && effectRect.Contains(Event.current.mousePosition))
{
ClearFocus();
DoEffectSlotInsertEffectPopup(effectRect, p.group, p.allGroups, i, ref p.effectMap);
evt.Use();
}
// Then do effect button
EffectSlot(effectRect, m_Controller.TargetSnapshot, effect, i, ref highlightEffectIndex, p, ref patchslots);
}
}
}
// Empty slot below effects
if (p.visible)
{
Rect effectRect = p.bgRects[p.bgRects.Count - 1];
if (evt.type == EventType.Repaint)
{
GUI.DrawTextureWithTexCoords(new Rect(effectRect.x, effectRect.y, effectRect.width, effectRect.height - 1), styles.effectBar.hover.background, new Rect(0, 0.5f, 0.1f, 0.1f));
GUI.Label(effectRect, addText, styles.effectName);
}
if (evt.type == EventType.MouseDown && effectRect.Contains(Event.current.mousePosition))
{
ClearFocus();
int insertEffectAtIndex = p.group.effects.Length;
DoEffectSlotInsertEffectPopup(effectRect, p.group, p.allGroups, insertEffectAtIndex, ref p.effectMap);
evt.Use();
}
}
}
float DoVUMeters(Rect vuRect, float attenuationMarkerHeight, ChannelStripParams p)
{
float spaceBetweenMeters = 1f;
// When the audiomixer has been rebuild we might have some frames where numChannels is not initialized.
// To prevent flickering we use last valid num channels used at current index
int numChannels = p.numChannels;
if (numChannels == 0)
{
if (p.index >= 0 && p.index < m_LastNumChannels.Count)
numChannels = m_LastNumChannels[p.index];
}
else
{
// Cache valid numChannels for current index
while (p.index >= m_LastNumChannels.Count)
m_LastNumChannels.Add(0);
m_LastNumChannels[p.index] = numChannels;
}
// Adjust rect based on how many channels we have
if (numChannels <= 2)
{
const float twoChannelWidth = 25f;
vuRect.x = vuRect.xMax - twoChannelWidth; // right align
vuRect.width = twoChannelWidth;
}
// This can happen when simulating player builds, i.e. not calculating VU-info for most of the channels.
if (numChannels == 0)
return vuRect.x;
float vuOffsetY = Mathf.Floor(attenuationMarkerHeight / 2);
vuRect.y += vuOffsetY;
vuRect.height -= 2 * vuOffsetY;
float vuWidth = Mathf.Round((vuRect.width - numChannels * spaceBetweenMeters) / numChannels);
Rect vuSubRect = new Rect(vuRect.xMax - vuWidth, vuRect.y, vuWidth, vuRect.height);
// Draw from right to left to ensure perfect right side pixel position (we are rounding widths above)
for (int i = numChannels - 1; i >= 0; i--)
{
if (i != numChannels - 1)
vuSubRect.x -= vuSubRect.width + spaceBetweenMeters;
float warpedLevel = 1f - AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(p.vuinfo_level[i], AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()), 1f, true);
float warpedPeak = 1f - AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(p.vuinfo_peak[i], AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()), 1f, true);
VUMeter(p.group, vuSubRect, warpedLevel, warpedPeak);
}
AudioMixerDrawUtils.AddTooltipOverlay(vuRect, styles.vuMeterGUIContent.tooltip);
return vuSubRect.x;
}
void DoSoloMuteBypassButtons(Rect rect, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups, List<AudioMixerGroupController> selection, bool anySoloActive)
{
float buttonSize = 21f;
float spaceBetween = 2f;
float startX = rect.x + (rect.width - (buttonSize * 3 + spaceBetween * 2)) * 0.5f;
Rect buttonRect = new Rect(startX, rect.y, buttonSize, buttonSize);
bool needMixerUpdate = false;
needMixerUpdate |= DoSoloButton(buttonRect, group, allGroups, selection);
buttonRect.x += buttonSize + spaceBetween;
needMixerUpdate |= DoMuteButton(buttonRect, group, allGroups, anySoloActive, selection);
if (needMixerUpdate)
m_Controller.UpdateMuteSolo();
buttonRect.x += buttonSize + spaceBetween;
if (DoBypassEffectsButton(buttonRect, group, allGroups, selection))
m_Controller.UpdateBypass();
}
public void OnMixerControllerChanged(AudioMixerController controller)
{
m_Controller = controller;
}
[System.NonSerialized]
private int FrameCounter = 0;
[System.NonSerialized]
private GUIStyle developerInfoStyle = AudioMixerDrawUtils.BuildGUIStyleForLabel(new Color(1.0f, 0.0f, 0.0f, 0.5f), 20, false, FontStyle.Bold, TextAnchor.MiddleLeft);
public void ShowDeveloperOverlays(Rect rect, Event evt, bool show)
{
if (show && Unsupported.IsDeveloperMode() && evt.type == EventType.Repaint)
{
AudioMixerDrawUtils.ReadOnlyLabel(new Rect(rect.x + 5, rect.y + 5, rect.width - 10, 20), "Current snapshot: " + m_Controller.TargetSnapshot.name, developerInfoStyle);
AudioMixerDrawUtils.ReadOnlyLabel(new Rect(rect.x + 5, rect.y + 25, rect.width - 10, 20), "Frame count: " + FrameCounter++, developerInfoStyle);
}
}
public static float Lerp(float x1, float x2, float t)
{
return x1 + (x2 - x1) * t;
}
public static void GetCableVertex(float x1, float y1, float x2, float y2, float x3, float y3, float t, out float x, out float y)
{
x = Lerp(Lerp(x1, x2, t), Lerp(x2, x3, t), t);
y = Lerp(Lerp(y1, y2, t), Lerp(y2, y3, t), t);
}
[System.NonSerialized]
private Vector3[] cablepoints = new Vector3[20];
public void OnGUI(Rect rect, bool showReferencedBuses, bool showBusConnections, bool showBusConnectionsOfSelection, List<AudioMixerGroupController> allGroups, Dictionary<AudioMixerEffectController, AudioMixerGroupController> effectMap, bool sortGroupsAlphabetically, bool showDeveloperOverlays, AudioMixerGroupController scrollToItem)
{
if (m_Controller == null)
{
DrawAreaBackground(rect);
return;
}
if (Event.current.type == EventType.Layout)
return;
m_RectSelectionControlID = GUIUtility.GetControlID(kRectSelectionHashCode, FocusType.Passive);
m_EffectInteractionControlID = GUIUtility.GetControlID(kEffectDraggingHashCode, FocusType.Passive);
m_IndexCounter = 0;
Event evt = Event.current;
var sortedGroups = m_Controller.GetCurrentViewGroupList().ToList();
if (sortGroupsAlphabetically)
sortedGroups.Sort(m_GroupComparer);
Rect baseChannelStripRect = new Rect(channelStripsOffset.x, channelStripsOffset.y, channelStripBaseWidth, 300);
if (scrollToItem != null)
{
int index = sortedGroups.IndexOf(scrollToItem);
if (index >= 0)
{
float x = (baseChannelStripRect.width + channelStripSpacing) * index - m_State.m_ScrollPos.x;
if (x < -20 || x > rect.width)
m_State.m_ScrollPos.x += x;
}
}
var unsortedBuses = new List<AudioMixerGroupController>();
foreach (var c in sortedGroups)
{
foreach (var e in c.effects)
{
if (e.sendTarget != null)
{
var targetGroup = effectMap[e.sendTarget];
if (!unsortedBuses.Contains(targetGroup) && !sortedGroups.Contains(targetGroup))
unsortedBuses.Add(targetGroup);
}
}
}
List<AudioMixerGroupController> buses = unsortedBuses.ToList();
buses.Sort(m_GroupComparer);
// Show referenced buses after all sorted groups
int numMainGroups = sortedGroups.Count;
if (showReferencedBuses && buses.Count > 0)
sortedGroups.AddRange(buses);
int maxEffects = 1;
foreach (var c in sortedGroups)
maxEffects = Mathf.Max(maxEffects, c.effects.Length);
bool isShowingReferencedGroups = sortedGroups.Count != numMainGroups;
Rect contentRect = GetContentRect(sortedGroups, isShowingReferencedGroups, maxEffects);
m_State.m_ScrollPos = GUI.BeginScrollView(rect, m_State.m_ScrollPos, contentRect);
DrawAreaBackground(new Rect(0, 0, 10000, 10000));
// Setup shared AudioGroup data
var channelStripParams = new ChannelStripParams
{
effectMap = effectMap,
allGroups = allGroups,
shownGroups = sortedGroups,
anySoloActive = allGroups.Any(g => g.solo),
visibleRect = new Rect(m_State.m_ScrollPos.x, m_State.m_ScrollPos.y, rect.width, rect.height)
};
var patchslots = showBusConnections ? new Dictionary<AudioMixerEffectController, PatchSlot>() : null;
for (int i = 0; i < sortedGroups.Count; ++i)
{
var group = sortedGroups[i];
// Specific parameter data for current AudioGroup
channelStripParams.index = i;
channelStripParams.group = group;
channelStripParams.drawingBuses = false;
channelStripParams.visible = RectOverlaps(channelStripParams.visibleRect, baseChannelStripRect);
channelStripParams.Init(m_Controller, baseChannelStripRect, maxEffects);
DrawChannelStrip(channelStripParams, ref m_Controller.m_HighlightEffectIndex, ref patchslots, showBusConnectionsOfSelection);
// If we click inside the the strip rect we use the event to ensure the mousedown is not caught by rectangle selection
if (evt.type == EventType.MouseDown && evt.button == 0 && channelStripParams.stripRect.Contains(evt.mousePosition))
evt.Use();
// If we are dragging effects we reset destination index when dragging outside effects
if (IsMovingEffect() && evt.type == EventType.MouseDrag && channelStripParams.stripRect.Contains(evt.mousePosition) && GUIUtility.hotControl == m_EffectInteractionControlID)
{
m_MovingEffectDstIndex = -1;
evt.Use();
}
baseChannelStripRect.x += channelStripParams.stripRect.width + channelStripSpacing;
// Add extra space to referenced groups
if (showReferencedBuses && i == numMainGroups - 1 && sortedGroups.Count > numMainGroups)
{
baseChannelStripRect.x += 50f;
using (new EditorGUI.DisabledScope(true))
{
GUI.Label(new Rect(baseChannelStripRect.x, channelStripParams.stripRect.yMax, 130, 22), styles.referencedGroups, styles.channelStripHeaderStyle);
}
}
}
UnhandledEffectDraggingEvents(ref m_Controller.m_HighlightEffectIndex);
if (evt.type == EventType.Repaint && patchslots != null)
{
foreach (var c in patchslots)
{
var slot = c.Value;
bool active = !showBusConnectionsOfSelection || m_Controller.CachedSelection.Contains(slot.group);
if (active)
styles.circularToggle.Draw(new Rect(slot.x - 3, slot.y - 3, 6, 6), false, false, active, false);
}
float moveamp = Mathf.Exp(-0.03f * Time.time * Time.time) * 0.1f;
var trCol1 = new Color(0.0f, 0.0f, 0.0f, AudioMixerController.EditingTargetSnapshot() ? 0.1f : 0.05f);
var trCol2 = new Color(0.0f, 0.0f, 0.0f, AudioMixerController.EditingTargetSnapshot() ? 1.0f : 0.5f);
foreach (var c in patchslots)
{
var sourceEffect = c.Key;
var targetEffect = sourceEffect.sendTarget;
if (targetEffect == null)
continue;
var sourceSlot = c.Value;
if (!patchslots.ContainsKey(targetEffect))
continue;
var targetSlot = patchslots[targetEffect];
int color = sourceEffect.GetInstanceID() ^ targetEffect.GetInstanceID();
float phase = (color & 63) * 0.1f;
float mx1 = Mathf.Abs(targetSlot.x - sourceSlot.x) * Mathf.Sin(Time.time * 5.0f + phase) * moveamp + (sourceSlot.x + targetSlot.x) * 0.5f;
float my1 = Mathf.Abs(targetSlot.y - sourceSlot.y) * Mathf.Cos(Time.time * 5.0f + phase) * moveamp + Math.Max(sourceSlot.y, targetSlot.y) + Mathf.Max(Mathf.Min(0.5f * Math.Abs(targetSlot.y - sourceSlot.y), 50.0f), 50.0f);
for (int i = 0; i < cablepoints.Length; i++)
GetCableVertex(
sourceSlot.x, sourceSlot.y,
mx1, my1,
targetSlot.x, targetSlot.y,
(float)i / (float)(cablepoints.Length - 1),
out cablepoints[i].x, out cablepoints[i].y);
bool skip = showBusConnectionsOfSelection && !m_Controller.CachedSelection.Contains(sourceSlot.group) && !m_Controller.CachedSelection.Contains(targetSlot.group);
Handles.color = skip ? trCol1 : trCol2;
Handles.DrawAAPolyLine(7.0f, cablepoints.Length, cablepoints);
if (skip)
continue;
color ^= (color >> 6) ^ (color >> 12) ^ (color >> 18);
Handles.color =
new Color(
(color & 3) * 0.15f + 0.55f,
((color >> 2) & 3) * 0.15f + 0.55f,
((color >> 4) & 3) * 0.15f + 0.55f,
AudioMixerController.EditingTargetSnapshot() ? 1.0f : 0.5f);
Handles.DrawAAPolyLine(4.0f, cablepoints.Length, cablepoints);
Handles.color = new Color(1.0f, 1.0f, 1.0f, AudioMixerController.EditingTargetSnapshot() ? 0.5f : 0.25f);
Handles.DrawAAPolyLine(3.0f, cablepoints.Length, cablepoints);
}
}
RectSelection(channelStripParams);
GUI.EndScrollView(true);
AudioMixerDrawUtils.DrawScrollDropShadow(rect, m_State.m_ScrollPos.y, contentRect.height);
WarningOverlay(allGroups, rect, contentRect);
ShowDeveloperOverlays(rect, evt, showDeveloperOverlays);
if (!EditorApplication.isPlaying && !m_Controller.isSuspended)
m_RequiresRepaint = true;
}
bool IsMovingEffect()
{
return m_MovingEffectSrcIndex != -1;
}
bool IsAdjustingWetMix()
{
return m_ChangingWetMixIndex != -1;
}
void RectSelection(ChannelStripParams channelStripParams)
{
Event evt = Event.current;
if (evt.type == EventType.MouseDown && evt.button == 0 && GUIUtility.hotControl == 0)
{
if (!evt.shift)
{
Selection.objects = new UnityEngine.Object[0];
m_Controller.OnUnitySelectionChanged();
}
GUIUtility.hotControl = m_RectSelectionControlID;
m_RectSelectionStartPos = evt.mousePosition;
m_RectSelectionRect = new Rect(m_RectSelectionStartPos.x, m_RectSelectionStartPos.y, 0, 0);
Event.current.Use();
InspectorWindow.RepaintAllInspectors();
}
if (evt.type == EventType.MouseDrag)
{
if (IsRectSelectionActive())
{
m_RectSelectionRect.x = Mathf.Min(m_RectSelectionStartPos.x, evt.mousePosition.x);
m_RectSelectionRect.y = Mathf.Min(m_RectSelectionStartPos.y, evt.mousePosition.y);
m_RectSelectionRect.width = Mathf.Max(m_RectSelectionStartPos.x, evt.mousePosition.x) - m_RectSelectionRect.x;
m_RectSelectionRect.height = Mathf.Max(m_RectSelectionStartPos.y, evt.mousePosition.y) - m_RectSelectionRect.y;
Event.current.Use();
}
if (m_MovingSrcRect.y >= 0.0f)
Event.current.Use();
}
if (IsRectSelectionActive() && evt.GetTypeForControl(m_RectSelectionControlID) == EventType.MouseUp)
{
var newChannelStripSelection = (evt.shift) ? m_Controller.CachedSelection : new List<AudioMixerGroupController>();
foreach (var g in channelStripParams.rectSelectionGroups)
if (!newChannelStripSelection.Contains(g))
newChannelStripSelection.Add(g);
Selection.objects = newChannelStripSelection.ToArray();
m_Controller.OnUnitySelectionChanged();
GUIUtility.hotControl = 0;
Event.current.Use();
//InspectorWindow.RepaintAllInspectors();
}
if (evt.type == EventType.Repaint)
{
if (IsRectSelectionActive())
{
Color rectSelCol = new Color(1, 1, 1, 0.3f);
AudioMixerDrawUtils.DrawGradientRectHorizontal(m_RectSelectionRect, rectSelCol, rectSelCol);
}
}
}
void WarningOverlay(List<AudioMixerGroupController> allGroups, Rect rect, Rect contentRect)
{
int numSoloed = 0, numMuted = 0, numBypassEffects = 0;
foreach (var g in allGroups)
{
if (g.solo)
numSoloed++;
if (g.mute)
numMuted++;
if (g.bypassEffects)
numBypassEffects += g.effects.Length - 1; // one of the effects is "Attenuation"
else
numBypassEffects += g.effects.Count(e => e.bypass);
}
Event evt = Event.current;
// Warning overlay
if (evt.type == EventType.Repaint && numSoloed > 0 || numMuted > 0 || numBypassEffects > 0)
{
string warningStr = "Warning: " + (
(numSoloed > 0) ? (numSoloed + (numSoloed > 1 ? " groups" : " group") + " currently soloed") :
(numMuted > 0) ? (numMuted + (numMuted > 1 ? " groups" : " group") + " currently muted") :
(numBypassEffects + (numBypassEffects > 1 ? " effects" : " effect") + " currently bypassed")
);
//bool verticalScrollbar = contentRect.height > rect.height;
bool horizontalScrollbar = contentRect.width > rect.width;
const float margin = 5f;
float textwidth = styles.warningOverlay.CalcSize(GUIContent.Temp(warningStr)).x;
Rect warningRect =
new Rect(rect.x + margin + Mathf.Max((rect.width - 2 * margin - textwidth) * 0.5f, 0f),
rect.yMax - styles.warningOverlay.fixedHeight - margin - (horizontalScrollbar ? 17f : 0f),
textwidth,
styles.warningOverlay.fixedHeight);
GUI.Label(warningRect, GUIContent.Temp(warningStr), styles.warningOverlay);
}
}
Rect GetContentRect(List<AudioMixerGroupController> sortedGroups, bool isShowingReferencedGroups, int maxEffects)
{
float fixedHeight = headerHeight + vuHeight + dbHeight + soloMuteBypassHeight;
float maxHeight = channelStripsOffset.y + fixedHeight + (maxEffects * effectHeight) + 10 + effectHeight + 10;
float maxWidth = channelStripsOffset.x * 2 + (channelStripBaseWidth + channelStripSpacing) * sortedGroups.Count + (isShowingReferencedGroups ? spaceBetweenMainGroupsAndReferenced : 0f);
return new Rect(0, 0, maxWidth, maxHeight);
}
}
}
| UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerChannelStripView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerChannelStripView.cs",
"repo_id": "UnityCsReference",
"token_count": 43174
} | 294 |
// 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.Reflection;
using UnityEngine;
namespace UnityEditor
{
class StreamedAudioClipPreview : WaveformPreview
{
static class AudioClipMinMaxOverview
{
static Dictionary<AudioClip, float[]> s_Data = new Dictionary<AudioClip, float[]>();
public static float[] GetOverviewFor(AudioClip clip)
{
if (!s_Data.ContainsKey(clip))
{
var path = AssetDatabase.GetAssetPath(clip);
if (path == null)
return null;
var importer = AssetImporter.GetAtPath(path);
if (importer == null)
return null;
s_Data[clip] = AudioUtil.GetMinMaxData(importer as AudioImporter);
}
return s_Data[clip];
}
}
struct ClipPreviewDetails
{
public float[] preview;
public int previewSamples;
public double normalizedDuration;
public double normalizedStart;
public double deltaStep;
public AudioClip clip;
public int previewPixelsToRender;
public double localStart;
public double localLength;
public bool looping;
public ClipPreviewDetails(AudioClip clip, bool isLooping, int size, double localStart, double localLength)
{
if (size < 2)
throw new ArgumentException("Size has to be larger than 1");
if (localLength <= 0)
throw new ArgumentException("length has to be longer than zero", "localLength");
if (localStart < 0)
throw new ArgumentException("localStart has to be positive", "localStart");
if (clip == null)
throw new ArgumentNullException("clip");
this.clip = clip;
preview = AudioClipMinMaxOverview.GetOverviewFor(clip);
if (preview == null)
throw new ArgumentException("Clip " + clip + "'s overview preview is null");
looping = isLooping;
this.localStart = localStart;
this.localLength = localLength;
if (looping)
{
previewPixelsToRender = size;
}
else
{
var clampedLength = Math.Min(clip.length - localStart, localLength);
previewPixelsToRender = (int)Math.Min(size, size * Math.Max(0, clampedLength / localLength));
}
previewSamples = preview.Length / (clip.channels * 2);
normalizedDuration = localLength / clip.length;
normalizedStart = localStart / clip.length;
deltaStep = (previewSamples * normalizedDuration) / (size - 1);
}
public bool IsCandidateForStreaming()
{
// shortcut, no need to start the stream if the start extends beyond the first clip region and the clip is "hold"
if (!looping && localStart >= clip.length)
return false;
return deltaStep < 0.5;
}
}
struct Segment
{
public WaveformStreamer streamer;
public int streamingIndexOffset;
public int textureOffset;
public int segmentLength;
}
class StreamingContext
{
public int index;
}
Dictionary<WaveformStreamer, StreamingContext> m_Contexts = new Dictionary<WaveformStreamer, StreamingContext>();
Segment[] m_StreamedSegments;
AudioClip m_Clip;
public StreamedAudioClipPreview(AudioClip clip, int initialSize)
: base(clip, initialSize, clip.channels)
{
m_ClearTexture = false;
m_Clip = clip;
m_Start = 0;
m_Length = clip.length;
}
protected override void InternalDispose()
{
base.InternalDispose();
KillAndClearStreamers();
m_StreamedSegments = null;
}
protected override void OnModifications(MessageFlags cFlags)
{
bool restartStreaming = false;
if (HasFlag(cFlags, MessageFlags.TextureChanged) || HasFlag(cFlags, MessageFlags.Size) || HasFlag(cFlags, MessageFlags.Length) || HasFlag(cFlags, MessageFlags.Looping))
{
KillAndClearStreamers();
if (length <= 0)
return;
var details = new ClipPreviewDetails(m_Clip, looping, (int)Size.x, start, length);
UploadPreview(details);
if (details.IsCandidateForStreaming())
restartStreaming = true;
}
if (!optimized)
{
KillAndClearStreamers();
restartStreaming = false;
}
else if (HasFlag(cFlags, MessageFlags.Optimization) && !restartStreaming)
{
// optimization toggled on, need to query whether we should start streaming
var details = new ClipPreviewDetails(m_Clip, looping, (int)Size.x, start, length);
if (details.IsCandidateForStreaming())
restartStreaming = true;
}
if (restartStreaming)
{
m_StreamedSegments = CalculateAndStartStreamers(start, length);
if (m_StreamedSegments != null && m_StreamedSegments.Length > 0)
{
foreach (var r in m_StreamedSegments)
{
if (!m_Contexts.ContainsKey(r.streamer))
m_Contexts.Add(r.streamer, new StreamingContext());
}
}
}
base.OnModifications(cFlags);
}
void KillAndClearStreamers()
{
foreach (var c in m_Contexts)
{
c.Key.Stop();
}
m_Contexts.Clear();
}
Segment[] CalculateAndStartStreamers(double localStart, double localLength)
{
Segment[] segments = null;
var originalStart = localStart;
// we don't care about the global position, only the locally visible offset into the clip
localStart %= m_Clip.length;
var secondsPerPixel = localLength / Size.x;
if (!looping)
{
// holding (= !looping) is a special case handled before everything
// else, because it's very simple to implement since it defines a
// section capped by length of the clip
if (originalStart > m_Clip.length)
return null;
var clampedLength = Math.Min(m_Clip.length - originalStart, localLength);
var previewPixelsToRender = (int)Math.Min(Size.x, Size.x * Math.Max(0, clampedLength / localLength));
if (previewPixelsToRender < 1)
return null;
segments = new Segment[1];
segments[0].streamer = new WaveformStreamer(m_Clip, originalStart, clampedLength, previewPixelsToRender, OnNewWaveformData);
segments[0].segmentLength = (int)Size.x;
segments[0].textureOffset = 0;
segments[0].streamingIndexOffset = 0;
return segments;
}
// epsilon added to discriminate between invisible floating point rounding errors
// and actual loops (i.e. more than a single pixel larger than then length)
if (localStart + localLength - secondsPerPixel > m_Clip.length)
{
var secondsToPixels = Size.x / localLength;
// special case, the first part is clipped but at least one full length of the clip is available
// we can then use one streamer to fill in all visible segments
if (localLength >= m_Clip.length)
{
var numberOfLoops = localLength / m_Clip.length;
var streamer = new WaveformStreamer(m_Clip, 0, m_Clip.length, (int)(Size.x / numberOfLoops), OnNewWaveformData);
var currentClipSegmentPart = m_Clip.length - localStart;
var localPosition = 0.0;
segments = new Segment[Mathf.CeilToInt((float)((localStart + localLength) / m_Clip.length))];
for (int i = 0; i < segments.Length; ++i)
{
var cappedLength = Math.Min(currentClipSegmentPart + localPosition, localLength) - localPosition;
segments[i].streamer = streamer;
segments[i].segmentLength = (int)(cappedLength * secondsToPixels);
segments[i].textureOffset = (int)(localPosition * secondsToPixels);
segments[i].streamingIndexOffset = (int)((m_Clip.length - currentClipSegmentPart) * secondsToPixels);
localPosition += currentClipSegmentPart;
currentClipSegmentPart = m_Clip.length;
}
}
else
{
// two disjoint regions, since streaming is time-continuous we have to split it up in two portions
var firstPart = m_Clip.length - localStart;
var secondPart = localLength - firstPart;
segments = new Segment[2];
segments[0].streamer = new WaveformStreamer(m_Clip, localStart, firstPart, (int)(firstPart * secondsToPixels), OnNewWaveformData);
segments[0].segmentLength = (int)(firstPart * secondsToPixels);
segments[0].textureOffset = 0;
segments[0].streamingIndexOffset = 0;
segments[1].streamer = new WaveformStreamer(m_Clip, 0, secondPart, (int)(secondPart * secondsToPixels), OnNewWaveformData);
segments[1].segmentLength = (int)(secondPart * secondsToPixels);
segments[1].textureOffset = (int)(firstPart * secondsToPixels);
segments[1].streamingIndexOffset = 0;
}
}
else
{
// handle single visible part of clip, that does not extend beyond the end
// with a length less than a clip - equaling one streamer.
segments = new Segment[1];
segments[0].streamer = new WaveformStreamer(m_Clip, localStart, localLength, (int)Size.x, OnNewWaveformData);
segments[0].segmentLength = (int)Size.x;
segments[0].textureOffset = 0;
segments[0].streamingIndexOffset = 0;
}
return segments;
}
void UploadPreview(ClipPreviewDetails details)
{
var channels = details.clip.channels;
float[] resampledPreview = new float[(int)(channels * Size.x * 2)];
if (details.localStart + details.localLength > details.clip.length)
{
ResamplePreviewLooped(details, resampledPreview);
}
else
ResamplePreviewConfined(details, resampledPreview);
SetMMWaveData(0, resampledPreview);
}
void ResamplePreviewConfined(ClipPreviewDetails details, float[] resampledPreview)
{
var channels = m_Clip.channels;
var samples = details.previewSamples;
var delta = details.deltaStep;
var position = details.normalizedStart * samples;
var preview = details.preview;
if (delta > 0.5)
{
int oldPosition = (int)position, floorPosition = oldPosition;
// for each step, there's more than one sample so we do min max on the min max data
// to avoid aliasing issues
for (int i = 0; i < details.previewPixelsToRender; ++i)
{
for (int c = 0; c < channels; ++c)
{
var x = oldPosition;
floorPosition = (int)position;
float min = preview[2 * x * channels + c * 2];
float max = preview[2 * x * channels + c * 2 + 1];
while (++x < floorPosition)
{
// yes, the data contained in the min max audio util overview is actually swapped (maxmin data)
min = Mathf.Max(min, preview[2 * x * channels + c * 2]);
max = Mathf.Min(max, preview[2 * x * channels + c * 2 + 1]);
}
resampledPreview[2 * i * channels + c * 2] = max;
resampledPreview[2 * i * channels + c * 2 + 1] = min;
}
position += delta;
oldPosition = floorPosition;
}
}
else
{
// fractionate interpolation
for (int i = 0; i < details.previewPixelsToRender; ++i)
{
var x = (int)(position - 1);
var x1 = x + 1;
float fraction = (float)((position - 1) - x);
x = Mathf.Max(0, x);
x1 = Mathf.Min(x1, samples - 1);
for (int c = 0; c < channels; ++c)
{
var minCurrent = preview[2 * x * channels + c * 2];
var maxCurrent = preview[2 * x * channels + c * 2 + 1];
var minNext = preview[2 * x1 * channels + c * 2];
var maxNext = preview[2 * x1 * channels + c * 2 + 1];
resampledPreview[2 * i * channels + c * 2] = fraction * maxNext + (1 - fraction) * maxCurrent;
resampledPreview[2 * i * channels + c * 2 + 1] = fraction * minNext + (1 - fraction) * minCurrent;
}
position += delta;
}
}
}
void ResamplePreviewLooped(ClipPreviewDetails details, float[] resampledPreview)
{
var previewSize = details.preview.Length;
var channels = m_Clip.channels;
var samples = details.previewSamples;
var delta = details.deltaStep;
var position = details.normalizedStart * samples;
var preview = details.preview;
if (delta > 0.5)
{
int oldPosition = (int)position, floorPosition = oldPosition;
// for each step, there's more than one sample so we do min max on the min max data
// to avoid aliasing issues
for (int i = 0; i < details.previewPixelsToRender; ++i)
{
for (int c = 0; c < channels; ++c)
{
var x = oldPosition;
floorPosition = (int)position;
var wrappedIndex = (2 * x * channels + c * 2) % previewSize;
float min = preview[wrappedIndex];
float max = preview[wrappedIndex + 1];
while (++x < floorPosition)
{
wrappedIndex = (2 * x * channels + c * 2) % previewSize;
// yes, the data contained in the min max audio util overview is actually swapped (maxmin data)
min = Mathf.Max(min, preview[wrappedIndex]);
max = Mathf.Min(max, preview[wrappedIndex + 1]);
}
resampledPreview[2 * i * channels + c * 2] = max;
resampledPreview[2 * i * channels + c * 2 + 1] = min;
}
position += delta;
oldPosition = floorPosition;
}
}
else
{
// fractionate interpolation
for (int i = 0; i < details.previewPixelsToRender; ++i)
{
var x = (int)(position - 1);
var x1 = x + 1;
float fraction = (float)((position - 1) - x);
for (int c = 0; c < channels; ++c)
{
var xWrapped = (2 * x * channels + c * 2) % previewSize;
var minCurrent = preview[xWrapped];
var maxCurrent = preview[xWrapped + 1];
var x1Wrapped = (2 * x1 * channels + c * 2) % previewSize;
var minNext = preview[x1Wrapped];
var maxNext = preview[x1Wrapped + 1];
resampledPreview[2 * i * channels + c * 2] = fraction * maxNext + (1 - fraction) * maxCurrent;
resampledPreview[2 * i * channels + c * 2 + 1] = fraction * minNext + (1 - fraction) * minCurrent;
}
position += delta;
}
}
}
bool OnNewWaveformData(WaveformStreamer streamer, float[] data, int remaining)
{
StreamingContext c = m_Contexts[streamer];
int pixelPos = c.index / m_Clip.channels;
for (var i = 0; i < m_StreamedSegments.Length; i++)
{
if (m_StreamedSegments[i].streamer == streamer && pixelPos >= m_StreamedSegments[i].streamingIndexOffset && m_StreamedSegments[i].segmentLength > (pixelPos - m_StreamedSegments[i].streamingIndexOffset))
{
SetMMWaveData((m_StreamedSegments[i].textureOffset - m_StreamedSegments[i].streamingIndexOffset) * m_Clip.channels + c.index, data);
}
}
c.index += data.Length / 2;
return remaining != 0;
}
}
}
| UnityCsReference/Editor/Mono/Audio/StreamedAudioClipPreview.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/StreamedAudioClipPreview.cs",
"repo_id": "UnityCsReference",
"token_count": 9451
} | 295 |
// 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 UnityEngine.Bindings;
using uei = UnityEngine.Internal;
namespace UnityEditor.BugReporting
{
// Keep in sync with "Editor/Platform/Interface/BugReportingTools.h"
internal enum BugReportMode { ManualOpen, CrashBug, FatalError, CocoaExceptionOrAssertion, ManualSimple }
[NativeHeader("Editor/Mono/BugReportingTools.bindings.h")]
internal sealed class BugReportingTools
{
[StaticAccessor("BugReportingToolsBindings", StaticAccessorType.DoubleColon)]
[NativeMethod("LaunchBugReportingTool")]
public static extern void LaunchBugReporter(BugReportMode mode, string[] additionalArguments);
}
}
| UnityCsReference/Editor/Mono/BugReportingTools.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BugReportingTools.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 251
} | 296 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Linq;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.Modules;
using UnityEditor.DeploymentTargets;
using UnityEngine.Scripting;
namespace UnityEditor
{
class MissingBuildPropertiesException : Exception {}
// Holds data needed to verify a target against a set of requirements
internal abstract class DeploymentTargetRequirements
{
}
// Holds data needed for operating (launching etc) on a build
internal abstract class BuildProperties : ScriptableObject
{
public static BuildProperties GetFromBuildReport(BuildReport report)
{
var allData = report.GetAppendices<BuildProperties>();
if (allData.Length > 0)
return allData[0];
throw new MissingBuildPropertiesException();
}
public abstract DeploymentTargetRequirements GetTargetRequirements();
}
internal static class PostprocessBuildPlayer
{
internal const string StreamingAssets = "Assets/StreamingAssets";
internal static void AddProjectBootConfigKey(string key)
{
AddProjectBootConfigKeyValue(key, null);
}
internal static void AddProjectBootConfigKeyValue(string key, string value)
{
projectBootConfigEntries[key] = value;
}
internal static bool RemoveProjectBootConfigKey(string key)
{
return projectBootConfigEntries.Remove(key);
}
internal static bool GetProjectBootConfigKeyValue(string key, out string value)
{
return projectBootConfigEntries.TryGetValue(key, out value);
}
internal static void ClearProjectBootConfigEntries()
{
projectBootConfigEntries.Clear();
}
private static Dictionary<string, string> projectBootConfigEntries = new Dictionary<string, string>();
internal static string GetStreamingAssetsBundleManifestPath()
{
string manifestPath = "";
if (Directory.Exists(StreamingAssets))
{
var tmpPath = Path.Combine(StreamingAssets, "StreamingAssets.manifest");
if (File.Exists(tmpPath))
manifestPath = tmpPath;
}
return manifestPath;
}
[RequiredByNativeCode]
static public string PrepareForBuild(BuildPlayerOptions buildOptions)
{
var postprocessor = ModuleManager.GetBuildPostProcessor(buildOptions.target);
if (postprocessor == null)
return null;
return postprocessor.PrepareForBuild(buildOptions);
}
static public string GetExtensionForBuildTarget(BuildTargetGroup targetGroup, BuildTarget target, BuildOptions options) =>
GetExtensionForBuildTarget(target, EditorUserBuildSettings.GetActiveSubtargetFor(target), options);
static public string GetExtensionForBuildTarget(BuildTarget target, int subtarget, BuildOptions options)
{
IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(target);
if (postprocessor == null)
return string.Empty;
return postprocessor.GetExtension(target, subtarget, options);
}
static public string GetExtensionForBuildTarget(BuildTarget target, BuildOptions options) =>
GetExtensionForBuildTarget(target, EditorUserBuildSettings.GetActiveSubtargetFor(target), options);
static public bool SupportsInstallInBuildFolder(BuildTarget target)
{
IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(target);
if (postprocessor != null)
{
return postprocessor.SupportsInstallInBuildFolder();
}
return false;
}
static public bool SupportsLz4Compression(BuildTargetGroup targetGroup, BuildTarget target) =>
SupportsLz4Compression(target);
static public bool SupportsLz4Compression(BuildTarget target)
{
IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(target);
if (postprocessor != null)
return postprocessor.SupportsLz4Compression();
return false;
}
static public Compression GetDefaultCompression(BuildTarget target)
{
IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(target);
if (postprocessor != null)
return postprocessor.GetDefaultCompression();
return Compression.None;
}
private class NoTargetsFoundException : Exception
{
public NoTargetsFoundException() : base() {}
public NoTargetsFoundException(string message) : base(message) {}
}
[RequiredByNativeCode]
static public void Launch(BuildTarget buildTarget, string path, string productName, BuildOptions options, BuildReport buildReport)
{
IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(buildTarget);
if (postprocessor != null)
{
BuildLaunchPlayerArgs args;
args.target = buildTarget;
args.playerPackage = BuildPipeline.GetPlaybackEngineDirectory(buildTarget, options);
args.installPath = path;
args.productName = productName;
args.options = options;
args.report = buildReport;
postprocessor.LaunchPlayer(args);
}
else
{
throw new UnityException(
$"Launching for build target {buildTarget} is not supported: There is no build post-processor available.");
}
}
static public void LaunchOnTargets(BuildTarget buildTarget, BuildReport buildReport, List<DeploymentTargetId> launchTargets)
{
try
{
// Early out so as not to show/update progressbars unnecessarily
if (buildReport == null)
throw new System.NotSupportedException();
ProgressHandler progressHandler = new ProgressHandler("Deploying Player",
delegate(string title, string message, float globalProgress)
{
if (EditorUtility.DisplayCancelableProgressBar(title, message, globalProgress))
throw new DeploymentOperationAbortedException();
}, 0.1f); // BuildPlayer.cpp starts off at 0.1f for some reason
var taskManager = new ProgressTaskManager(progressHandler);
// Launch on all selected targets
taskManager.AddTask(() =>
{
int successfulLaunches = 0;
var exceptions = new List<DeploymentOperationFailedException>();
foreach (var target in launchTargets)
{
try
{
var manager = DeploymentTargetManager.CreateInstance(buildReport.summary.platform);
var buildProperties = BuildProperties.GetFromBuildReport(buildReport);
manager.LaunchBuildOnTarget(buildProperties, target, taskManager.SpawnProgressHandlerFromCurrentTask());
successfulLaunches++;
}
catch (DeploymentOperationFailedException e)
{
exceptions.Add(e);
}
}
foreach (var e in exceptions)
UnityEngine.Debug.LogException(e);
if (successfulLaunches == 0)
{
// TODO: Maybe more specifically no compatible targets?
throw new NoTargetsFoundException("Could not launch build");
}
});
taskManager.Run();
}
catch (DeploymentOperationFailedException e)
{
UnityEngine.Debug.LogException(e);
EditorUtility.DisplayDialog(e.title, e.Message, "Ok");
}
catch (DeploymentOperationAbortedException)
{
System.Console.WriteLine("Deployment aborted");
}
catch (NoTargetsFoundException)
{
throw new UnityException(string.Format("Could not find any valid targets to launch on for {0}", buildTarget));
}
}
[RequiredByNativeCode]
static public void UpdateBootConfig(BuildTarget target, BootConfigData config, BuildOptions options)
{
IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(target);
if (postprocessor != null)
postprocessor.UpdateBootConfig(target, config, options);
foreach (var keyValue in projectBootConfigEntries)
{
if ((keyValue.Value == null) || keyValue.Value.All(char.IsWhiteSpace))
config.AddKey(keyValue.Key);
else
config.Set(keyValue.Key, keyValue.Value);
}
}
[RequiredByNativeCode]
static public void Postprocess(BuildTarget target, int subtarget, string installPath, string companyName, string productName,
BuildOptions options,
RuntimeClassRegistry usedClassRegistry, BuildReport report)
{
string stagingArea = "Temp/StagingArea";
string stagingAreaData = "Temp/StagingArea/Data";
string stagingAreaDataManaged = "Temp/StagingArea/Data/Managed";
string playerPackage = BuildPipeline.GetPlaybackEngineDirectory(target, options);
// Disallow providing an empty string as the installPath
bool willInstallInBuildFolder = (options & BuildOptions.InstallInBuildFolder) != 0 && SupportsInstallInBuildFolder(target);
if (installPath == String.Empty && !willInstallInBuildFolder)
throw new Exception(installPath + " must not be an empty string");
IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(target);
if (postprocessor == null)
// If postprocessor is not provided, build target is not supported
throw new UnityException($"Build target '{target}' not supported");
try
{
AddIconsArgs iconArgs;
iconArgs.stagingArea = stagingArea;
if (!postprocessor.AddIconsToBuild(iconArgs))
throw new BuildFailedException("Failed to add player icon");
BuildPostProcessArgs args;
args.target = target;
args.subtarget = subtarget;
args.stagingAreaData = stagingAreaData;
args.stagingArea = stagingArea;
args.stagingAreaDataManaged = stagingAreaDataManaged;
args.playerPackage = playerPackage;
args.installPath = installPath;
args.companyName = companyName;
args.productName = productName;
args.productGUID = PlayerSettings.productGUID;
args.options = options;
args.usedClassRegistry = usedClassRegistry;
args.report = report;
BuildProperties props;
postprocessor.PostProcess(args, out props);
if (props != null)
{
report.AddAppendix(props);
}
return;
}
catch (BuildFailedException)
{
throw;
}
catch (Exception e)
{
// Rethrow exceptions during build postprocessing as BuildFailedException, so we don't pretend the build was fine.
throw new BuildFailedException(e);
}
}
public static void PostProcessCompletedBuild(BuildPostProcessArgs args)
{
var postprocessor = ModuleManager.GetBuildPostProcessor(args.target);
postprocessor.PostProcessCompletedBuild(args);
}
}
}
| UnityCsReference/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs",
"repo_id": "UnityCsReference",
"token_count": 5566
} | 297 |
// 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 JetBrains.Annotations;
using UnityEditor.Modules;
using UnityEngine;
using UnityEngine.Bindings;
namespace UnityEditor.Build.Profile
{
public sealed partial class BuildProfile
{
[UsedImplicitly]
internal static event Action<BuildProfile> onBuildProfileEnable;
[VisibleToOtherModules]
internal static void AddOnBuildProfileEnable(Action<BuildProfile> action) => onBuildProfileEnable += action;
[VisibleToOtherModules]
internal static void RemoveOnBuildProfileEnable(Action<BuildProfile> action) => onBuildProfileEnable -= action;
internal static BuildProfile CreateInstance(BuildTarget buildTarget, StandaloneBuildSubtarget subtarget)
{
string moduleName = ModuleManager.GetTargetStringFrom(buildTarget);
var buildProfile = CreateInstance<BuildProfile>();
buildProfile.buildTarget = buildTarget;
buildProfile.subtarget = subtarget;
buildProfile.moduleName = moduleName;
buildProfile.OnEnable();
return buildProfile;
}
/// <summary>
/// Internal helper function for creating new build profile assets and invoking the onBuildProfileCreated
/// event after an asset is created by AssetDatabase.CreateAsset.
/// </summary>
[VisibleToOtherModules("UnityEditor.BuildProfileModule")]
internal static void CreateInstance(string moduleName, StandaloneBuildSubtarget subtarget, string assetPath)
{
var buildProfile = CreateInstance<BuildProfile>();
buildProfile.buildTarget = BuildProfileModuleUtil.GetBuildTarget(moduleName);
buildProfile.subtarget = subtarget;
buildProfile.moduleName = moduleName;
AssetDatabase.CreateAsset(
buildProfile,
AssetDatabase.GenerateUniqueAssetPath(assetPath));
buildProfile.OnEnable();
}
void TryCreatePlatformSettings()
{
if (platformBuildProfile != null)
{
Debug.LogError("[BuildProfile] Platform settings already created.");
return;
}
IBuildProfileExtension buildProfileExtension = ModuleManager.GetBuildProfileExtension(moduleName);
if (buildProfileExtension != null && ModuleManager.IsPlatformSupportLoaded(moduleName))
{
platformBuildProfile = buildProfileExtension.CreateBuildProfilePlatformSettings();
EditorUtility.SetDirty(this);
}
}
}
}
| UnityCsReference/Editor/Mono/BuildProfile/BuildProfileCreate.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildProfile/BuildProfileCreate.cs",
"repo_id": "UnityCsReference",
"token_count": 1037
} | 298 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.