text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!159 &1 EditorSettings: m_ObjectHideFlags: 0 serializedVersion: 11 m_SerializationMode: 2 m_LineEndingsForNewScripts: 1 m_DefaultBehaviorMode: 0 m_PrefabRegularEnvironment: {fileID: 0} m_PrefabUIEnvironment: {fileID: 0} m_SpritePackerMode: 5 m_SpritePackerPaddingPower: 1 m_Bc7TextureCompressor: 0 m_EtcTextureCompressorBehavior: 0 m_EtcTextureFastCompressor: 2 m_EtcTextureNormalCompressor: 2 m_EtcTextureBestCompressor: 5 m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmdef;asmref m_ProjectGenerationRootNamespace: ET m_EnableTextureStreamingInEditMode: 1 m_EnableTextureStreamingInPlayMode: 1 m_AsyncShaderCompilation: 1 m_CachingShaderPreprocessor: 1 m_PrefabModeAllowAutoSave: 1 m_EnterPlayModeOptionsEnabled: 0 m_EnterPlayModeOptions: 3 m_GameObjectNamingDigits: 1 m_GameObjectNamingScheme: 0 m_AssetNamingUsesSpace: 1 m_UseLegacyProbeSampleCount: 1 m_SerializeInlineMappingsOnOneLine: 0 m_DisableCookiesInLightmapper: 1 m_AssetPipelineMode: 1 m_RefreshImportMode: 0 m_CacheServerMode: 0 m_CacheServerEndpoint: m_CacheServerNamespacePrefix: default m_CacheServerEnableDownload: 1 m_CacheServerEnableUpload: 1 m_CacheServerEnableAuth: 0 m_CacheServerEnableTls: 0 m_CacheServerValidationMode: 2
ET/Unity/ProjectSettings/EditorSettings.asset/0
{ "file_path": "ET/Unity/ProjectSettings/EditorSettings.asset", "repo_id": "ET", "token_count": 501 }
200
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!78 &1 TagManager: serializedVersion: 2 tags: [] layers: - Default - TransparentFX - Ignore Raycast - - Water - UI - - - Map - Hidden - - - - - - - - - - - - - - - - - - - - - - m_SortingLayers: - name: Default uniqueID: 0 locked: 0
ET/Unity/ProjectSettings/TagManager.asset/0
{ "file_path": "ET/Unity/ProjectSettings/TagManager.asset", "repo_id": "ET", "token_count": 214 }
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.IO; using System.Text; using System.Xml.Linq; namespace ICSharpCode.BamlDecompiler.Xaml { internal static class XamlUtils { public static string Escape(string value) { if (value.Length == 0) return value; if (value[0] == '{') return "{}" + value; return value; } public static string ToString(this XamlContext ctx, XElement elem, XamlType type) { type.ResolveNamespace(elem, ctx); return ctx.ToString(elem, type.ToXName(ctx)); } public static string ToString(this XamlContext ctx, XElement elem, XName name) { var sb = new StringBuilder(); if (name.Namespace != elem.GetDefaultNamespace()) { var prefix = elem.GetPrefixOfNamespace(name.Namespace); if (!string.IsNullOrEmpty(prefix)) { sb.Append(prefix); sb.Append(':'); } } sb.Append(name.LocalName); return sb.ToString(); } public static double ReadXamlDouble(this BinaryReader reader, bool scaledInt = false) { if (!scaledInt) { switch (reader.ReadByte()) { case 1: return 0; case 2: return 1; case 3: return -1; case 4: break; case 5: return reader.ReadDouble(); default: throw new InvalidDataException("Unknown double type."); } } // Dividing by 1000000.0 is important to get back the original numbers, we can't // multiply by the inverse of it (0.000001). // (11700684 * 0.000001) != (11700684 / 1000000.0) => 11.700683999999999 != 11.700684 return reader.ReadInt32() / 1000000.0; } /// <summary> /// Escape characters that cannot be used in XML. /// </summary> public static StringBuilder EscapeName(StringBuilder sb, string name) { foreach (char ch in name) { if (char.IsWhiteSpace(ch) || char.IsControl(ch) || char.IsSurrogate(ch)) sb.AppendFormat("\\u{0:x4}", (int)ch); else sb.Append(ch); } return sb; } /// <summary> /// Escape characters that cannot be displayed in the UI. /// </summary> public static string EscapeName(string name) { return EscapeName(new StringBuilder(name.Length), name).ToString(); } } }
ILSpy/ICSharpCode.BamlDecompiler/Xaml/XamlUtils.cs/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/Xaml/XamlUtils.cs", "repo_id": "ILSpy", "token_count": 1189 }
202
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> </Project>
ILSpy/ICSharpCode.Decompiler.TestRunner/ICSharpCode.Decompiler.TestRunner.csproj/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.TestRunner/ICSharpCode.Decompiler.TestRunner.csproj", "repo_id": "ILSpy", "token_count": 75 }
203
// 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.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using ICSharpCode.Decompiler.Tests.Helpers; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests { [TestFixture, Parallelizable(ParallelScope.All)] public class PrettyTestRunner { static readonly string TestCasePath = Tester.TestCasePath + "/Pretty"; [Test] public void AllFilesHaveTests() { var testNames = typeof(PrettyTestRunner).GetMethods() .Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Any()) .Select(m => m.Name) .ToArray(); foreach (var file in new DirectoryInfo(TestCasePath).EnumerateFiles()) { if (file.Extension.Equals(".il", StringComparison.OrdinalIgnoreCase) || file.Extension.Equals(".cs", StringComparison.OrdinalIgnoreCase)) { var testName = file.Name.Split('.')[0]; Assert.That(testNames, Has.Member(testName)); } } } static readonly CompilerOptions[] noRoslynOptions = { CompilerOptions.None, CompilerOptions.Optimize }; static readonly CompilerOptions[] roslynOnlyWithNet40Options = { CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn1_3_2, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] roslynOnlyOptions = { CompilerOptions.UseRoslyn1_3_2, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] roslyn2OrNewerWithNet40Options = { CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] roslyn2OrNewerOptions = { CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] roslyn3OrNewerWithNet40Options = { CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] roslyn3OrNewerOptions = { CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] roslyn4OrNewerOptions = { CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] defaultOptions = { CompilerOptions.None, CompilerOptions.Optimize, CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn1_3_2, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] defaultOptionsWithMcs = { CompilerOptions.None, CompilerOptions.Optimize, CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn1_3_2, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, CompilerOptions.UseMcs2_6_4, CompilerOptions.Optimize | CompilerOptions.UseMcs2_6_4, CompilerOptions.UseMcs5_23, CompilerOptions.Optimize | CompilerOptions.UseMcs5_23 }; [Test] public async Task HelloWorld() { await RunForLibrary(); await RunForLibrary(asmOptions: AssemblerOptions.UseDebug); } [Test] public async Task IndexRangeTest([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { if (cscOptions.HasFlag(CompilerOptions.UseRoslynLatest)) { Assert.Ignore("See https://github.com/icsharpcode/ILSpy/issues/2540"); } await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task InlineAssignmentTest([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CompoundAssignmentTest([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task ShortCircuit([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CustomShortCircuitOperators([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task ExceptionHandling([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings { NullPropagation = false, // legacy csc generates a dead store in debug builds RemoveDeadStores = (cscOptions == CompilerOptions.None), FileScopedNamespaces = false, }); } [Test] public async Task Switch([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings { // legacy csc generates a dead store in debug builds RemoveDeadStores = (cscOptions == CompilerOptions.None), SwitchExpressions = false, FileScopedNamespaces = false, }); } [Test] public async Task SwitchExpressions([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task ReduceNesting([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task DelegateConstruction([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task AnonymousTypes([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Async([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Lock([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Using([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary( cscOptions: cscOptions, decompilerSettings: new DecompilerSettings { UseEnhancedUsing = false, FileScopedNamespaces = false, } ); } [Test] public async Task UsingVariables([ValueSource(nameof(roslyn3OrNewerWithNet40Options))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task LiftedOperators([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Operators([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Generics([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Loops([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions) { DecompilerSettings settings = Tester.GetSettings(cscOptions); // legacy csc generates a dead store in debug builds settings.RemoveDeadStores = (cscOptions == CompilerOptions.None); settings.UseExpressionBodyForCalculatedGetterOnlyProperties = false; await RunForLibrary(cscOptions: cscOptions, decompilerSettings: settings); } [Test] public async Task LocalFunctions([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task PropertiesAndEvents([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions | CompilerOptions.NullableEnable); } [Test] public async Task AutoProperties([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task QueryExpressions([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task TypeAnalysisTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CheckedUnchecked([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task UnsafeCode([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions | CompilerOptions.ReferenceUnsafe); } [Test] public async Task ConstructorInitializers([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task PInvoke([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { // This tests needs our own disassembler; ildasm has a bug with marshalinfo. await RunForLibrary(cscOptions: cscOptions, asmOptions: AssemblerOptions.UseOwnDisassembler); } [Test] public async Task OutVariables([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task PatternMatching([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task InitializerTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions | CompilerOptions.NullableEnable); } [Test] public async Task DynamicTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task ExpressionTrees([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task FixProxyCalls([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task ValueTypes([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task VariableNaming([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions | CompilerOptions.GeneratePdb); } [Test] public async Task VariableNamingWithoutSymbols([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { var settings = Tester.GetSettings(cscOptions); settings.UseDebugSymbols = false; await RunForLibrary(cscOptions: cscOptions, decompilerSettings: settings); } [Test] public async Task CS72_PrivateProtected([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task AsyncForeach([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task AsyncMain([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await Run(cscOptions: cscOptions); } [Test] public async Task AsyncStreams([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task AsyncUsing([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary( cscOptions: cscOptions, decompilerSettings: new DecompilerSettings { UseEnhancedUsing = false, FileScopedNamespaces = false } ); } [Test] public async Task CustomTaskType([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task NullableRefTypes([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions | CompilerOptions.NullableEnable); } [Test] public async Task NativeInts([ValueSource(nameof(roslyn3OrNewerWithNet40Options))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task FileScopedNamespaces([ValueSource(nameof(roslyn4OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings()); } [Test] public async Task Structs([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task FunctionPointers([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Records([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions | CompilerOptions.NullableEnable); } [Test] public async Task NullPropagation([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task StringInterpolation([ValueSource(nameof(roslynOnlyWithNet40Options))] CompilerOptions cscOptions) { await Run(cscOptions: cscOptions); } [Test] public async Task CS73_StackAllocInitializers([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task RefLocalsAndReturns([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task RefFields([ValueSource(nameof(roslyn4OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task ThrowExpressions([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task WellKnownConstants([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task QualifierTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task TupleTests([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task NamedArguments([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task OptionalArguments([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task ConstantsTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Issue1080([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings(CSharp.LanguageVersion.CSharp6)); } [Test] public async Task AssemblyCustomAttributes([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CustomAttributes([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CustomAttributes2([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CustomAttributeConflicts([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CustomAttributeSamples([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task MemberTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task MultidimensionalArray([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task EnumTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task InterfaceTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task TypeMemberTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task YieldReturn([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task UserDefinedConversions([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task Discards([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task DeconstructionTests([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CS9_ExtensionGetEnumerator([ValueSource(nameof(roslyn3OrNewerWithNet40Options))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task CovariantReturns([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task StaticAbstractInterfaceMembers([ValueSource(nameof(roslyn4OrNewerOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } [Test] public async Task MetadataAttributes([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions); } async Task RunForLibrary([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, DecompilerSettings decompilerSettings = null) { await Run(testName, asmOptions | AssemblerOptions.Library, cscOptions | CompilerOptions.Library, decompilerSettings); } async Task Run([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, DecompilerSettings decompilerSettings = null) { var csFile = Path.Combine(TestCasePath, testName + ".cs"); var exeFile = Path.Combine(TestCasePath, testName) + Tester.GetSuffix(cscOptions) + ".exe"; if (cscOptions.HasFlag(CompilerOptions.Library)) { exeFile = Path.ChangeExtension(exeFile, ".dll"); } // 1. Compile CompilerResults output = null; try { output = await Tester.CompileCSharp(csFile, cscOptions, exeFile).ConfigureAwait(false); } finally { if (output != null) output.DeleteTempFiles(); } // 2. Decompile var decompiled = await Tester.DecompileCSharp(exeFile, decompilerSettings ?? Tester.GetSettings(cscOptions)).ConfigureAwait(false); // 3. Compile CodeAssert.FilesAreEqual(csFile, decompiled, Tester.GetPreprocessorSymbols(cscOptions).ToArray()); Tester.RepeatOnIOError(() => File.Delete(decompiled)); } } }
ILSpy/ICSharpCode.Decompiler.Tests/PrettyTestRunner.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/PrettyTestRunner.cs", "repo_id": "ILSpy", "token_count": 9062 }
204
using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness { class PropertiesAndEvents { public static int Main(string[] args) { Index i = new Index(); i.AutoProp = "Name"; Console.WriteLine("AutoProp set!"); i[0] = 5; i[1] = 2; Console.WriteLine("{0} {1}", i[0], i[5]); Console.WriteLine("PI² = {0}", i.PISquare); return 0; } } class Index { int thisValue; public int this[int i] { get { Console.WriteLine("get_this({0})", i); return i * i; } set { Console.WriteLine("set_this({0}, {1})", i, value); thisValue = value; } } public string AutoProp { get; set; } public double PISquare { get { Console.WriteLine("get_PISquare"); return Math.Pow(Math.PI, 2); } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/PropertiesAndEvents.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/PropertiesAndEvents.cs", "repo_id": "ILSpy", "token_count": 323 }
205
.assembly extern mscorlib { .publickeytoken = ( b7 7a 5c 56 19 34 e0 89 ) .ver 4:0:0:0 } .assembly SecurityDeclarations { .custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = ( 01 00 07 31 2e 30 2e 30 2e 30 00 00 ) .hash algorithm 0x00008004 // SHA1 .ver 1:0:0:0 } .module SecurityDeclarations.dll .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WindowsCui .corflags 0x00000001 // ILOnly .class private auto ansi '<Module>' { } // end of class <Module> .class private auto ansi beforefieldinit SecurityDeclarations.NestedArrays extends [mscorlib]System.Object { .permissionset assert = { class 'SecurityDeclarations.SecurityAttrTest, SecurityDeclarations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' = { field object TestBoxed2 = object(object[4](int32(1) int32(2) int32(3) object[3](int32(4) int32(5) int32(6)))) } } // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20d4 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method NestedArrays::.ctor } // end of class SecurityDeclarations.NestedArrays .class private auto ansi beforefieldinit SecurityDeclarations.SecurityAttrTest extends [mscorlib]System.Security.Permissions.SecurityAttribute { // Fields .field private valuetype SecurityDeclarations.TestEnum[] _testEnumArray .field private int32[] _testInt32Array .field private string[] _testStringArray .field private class [mscorlib]System.Type[] _testTypeArray .field public object TestBoxed .field public object TestBoxed2 .field public object TestBoxedArray .field public object TestBoxedString .field public object TestBoxedType .field public valuetype SecurityDeclarations.TestEnum TestEnumType .field public int32 TestInt32 .field public string TestString .field public class [mscorlib]System.Type TestType // Methods .method public hidebysig specialname rtspecialname instance void .ctor ( valuetype [mscorlib]System.Security.Permissions.SecurityAction action ) cil managed { // Method begins at RVA 0x2059 // Header size: 1 // Code size: 10 (0xa) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call instance void [mscorlib]System.Security.Permissions.SecurityAttribute::.ctor(valuetype [mscorlib]System.Security.Permissions.SecurityAction) IL_0007: nop IL_0008: nop IL_0009: ret } // end of method SecurityAttrTest::.ctor .method public hidebysig virtual instance class [mscorlib]System.Security.IPermission CreatePermission () cil managed { // Method begins at RVA 0x2064 // Header size: 1 // Code size: 7 (0x7) .maxstack 8 IL_0000: nop IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor() IL_0006: throw } // end of method SecurityAttrTest::CreatePermission .method public hidebysig specialname instance valuetype SecurityDeclarations.TestEnum[] get_TestEnumArray () cil managed { // Method begins at RVA 0x208e // Header size: 1 // Code size: 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld valuetype SecurityDeclarations.TestEnum[] SecurityDeclarations.SecurityAttrTest::_testEnumArray IL_0006: ret } // end of method SecurityAttrTest::get_TestEnumArray .method public hidebysig specialname instance int32[] get_TestInt32Array () cil managed { // Method begins at RVA 0x207d // Header size: 1 // Code size: 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32[] SecurityDeclarations.SecurityAttrTest::_testInt32Array IL_0006: ret } // end of method SecurityAttrTest::get_TestInt32Array .method public hidebysig specialname instance string[] get_TestStringArray () cil managed { // Method begins at RVA 0x206c // Header size: 1 // Code size: 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string[] SecurityDeclarations.SecurityAttrTest::_testStringArray IL_0006: ret } // end of method SecurityAttrTest::get_TestStringArray .method public hidebysig specialname instance class [mscorlib]System.Type[] get_TestTypeArray () cil managed { // Method begins at RVA 0x209f // Header size: 1 // Code size: 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Type[] SecurityDeclarations.SecurityAttrTest::_testTypeArray IL_0006: ret } // end of method SecurityAttrTest::get_TestTypeArray .method public hidebysig specialname instance void set_TestEnumArray ( valuetype SecurityDeclarations.TestEnum[] 'value' ) cil managed { // Method begins at RVA 0x2096 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld valuetype SecurityDeclarations.TestEnum[] SecurityDeclarations.SecurityAttrTest::_testEnumArray IL_0007: ret } // end of method SecurityAttrTest::set_TestEnumArray .method public hidebysig specialname instance void set_TestInt32Array ( int32[] 'value' ) cil managed { // Method begins at RVA 0x2085 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32[] SecurityDeclarations.SecurityAttrTest::_testInt32Array IL_0007: ret } // end of method SecurityAttrTest::set_TestInt32Array .method public hidebysig specialname instance void set_TestStringArray ( string[] 'value' ) cil managed { // Method begins at RVA 0x2074 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string[] SecurityDeclarations.SecurityAttrTest::_testStringArray IL_0007: ret } // end of method SecurityAttrTest::set_TestStringArray .method public hidebysig specialname instance void set_TestTypeArray ( class [mscorlib]System.Type[] 'value' ) cil managed { // Method begins at RVA 0x20a7 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld class [mscorlib]System.Type[] SecurityDeclarations.SecurityAttrTest::_testTypeArray IL_0007: ret } // end of method SecurityAttrTest::set_TestTypeArray // Properties .property instance valuetype SecurityDeclarations.TestEnum[] TestEnumArray() { .get instance valuetype SecurityDeclarations.TestEnum[] SecurityDeclarations.SecurityAttrTest::get_TestEnumArray() .set instance void SecurityDeclarations.SecurityAttrTest::set_TestEnumArray(valuetype SecurityDeclarations.TestEnum[]) } .property instance int32[] TestInt32Array() { .get instance int32[] SecurityDeclarations.SecurityAttrTest::get_TestInt32Array() .set instance void SecurityDeclarations.SecurityAttrTest::set_TestInt32Array(int32[]) } .property instance string[] TestStringArray() { .get instance string[] SecurityDeclarations.SecurityAttrTest::get_TestStringArray() .set instance void SecurityDeclarations.SecurityAttrTest::set_TestStringArray(string[]) } .property instance class [mscorlib]System.Type[] TestTypeArray() { .get instance class [mscorlib]System.Type[] SecurityDeclarations.SecurityAttrTest::get_TestTypeArray() .set instance void SecurityDeclarations.SecurityAttrTest::set_TestTypeArray(class [mscorlib]System.Type[]) } } // end of class SecurityDeclarations.SecurityAttrTest .class private auto ansi beforefieldinit SecurityDeclarations.SimpleType extends [mscorlib]System.Object { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method SimpleType::.ctor } // end of class SecurityDeclarations.SimpleType .class private auto ansi sealed SecurityDeclarations.TestEnum extends [mscorlib]System.Enum { // Fields .field public static literal valuetype SecurityDeclarations.TestEnum A = int32(0) .field public static literal valuetype SecurityDeclarations.TestEnum B = int32(1) .field public static literal valuetype SecurityDeclarations.TestEnum C = int32(2) .field public specialname rtspecialname int32 value__ } // end of class SecurityDeclarations.TestEnum .class private auto ansi beforefieldinit SecurityDeclarations.TestEnumTypes extends [mscorlib]System.Object { .permissionset inheritcheck = { class 'SecurityDeclarations.SecurityAttrTest, SecurityDeclarations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' = { field enum SecurityDeclarations.TestEnum TestEnumType = int32(0) field object TestBoxed = object(int32(1)) property enum SecurityDeclarations.TestEnum[] TestEnumArray = int32[3](0 1 2) field object TestBoxed2 = object(object[4](int32(0) int32(1) int32(2) object[1](int32(3)))) field object TestBoxedArray = object(int32[3](0 1 2)) } } // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20c2 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method TestEnumTypes::.ctor } // end of class SecurityDeclarations.TestEnumTypes .class private auto ansi beforefieldinit SecurityDeclarations.TestInt32Types extends [mscorlib]System.Object { .permissionset permitonly = { class 'SecurityDeclarations.SecurityAttrTest, SecurityDeclarations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' = { field int32 TestInt32 = int32(5) field object TestBoxed = object(int32(10)) property int32[] TestInt32Array = int32[3](1 2 3) field object TestBoxedArray = object(int32[3](4 5 6)) field object TestBoxed2 = object(object[3](int32(7) int32(8) int32(9))) } } // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20cb // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method TestInt32Types::.ctor } // end of class SecurityDeclarations.TestInt32Types .class private auto ansi beforefieldinit SecurityDeclarations.TestStringTypes extends [mscorlib]System.Object { .permissionset assert = { class 'SecurityDeclarations.SecurityAttrTest, SecurityDeclarations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' = { field string TestString = string('Hello World!') field object TestBoxedString = object(string('Boxed String')) property string[] TestStringArray = string[2]('a' 'b') field object TestBoxedArray = object(string[2]('c' 'd')) } } // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b0 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method TestStringTypes::.ctor } // end of class SecurityDeclarations.TestStringTypes .class private sequential ansi sealed beforefieldinit SecurityDeclarations.TestStruct extends [mscorlib]System.ValueType { .pack 0 .size 1 } // end of class SecurityDeclarations.TestStruct .class private auto ansi beforefieldinit SecurityDeclarations.TestTypeTypes extends [mscorlib]System.Object { .permissionset demand = { class 'SecurityDeclarations.SecurityAttrTest, SecurityDeclarations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' = { field type TestType = type(SecurityDeclarations.SimpleType) field object TestBoxed = object(type(SecurityDeclarations.TestEnum)) property type[] TestTypeArray = type[2](SecurityDeclarations.TestStruct SecurityDeclarations.SimpleType) field object TestBoxedArray = object(type[2](SecurityDeclarations.TestStringTypes SecurityDeclarations.TestTypeTypes)) } } // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b9 // Header size: 1 // Code size: 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method TestTypeTypes::.ctor } // end of class SecurityDeclarations.TestTypeTypes
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Disassembler/Pretty/SortMembers.expected.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Disassembler/Pretty/SortMembers.expected.il", "repo_id": "ILSpy", "token_count": 4467 }
206
#define CORE_ASSEMBLY "System.Runtime" .assembly extern CORE_ASSEMBLY { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: .ver 4:0:0:0 } .class private auto ansi beforefieldinit EvalOrder extends [System.Private.CoreLib]System.Object { .field private valuetype SimpleStruct 'field' // Methods .method public hidebysig static void Test ( class EvalOrder p ) cil managed { // Method begins at RVA 0x20f0 // Code size 14 (0xe) .maxstack 8 ldarg.0 ldflda valuetype SimpleStruct EvalOrder::'field' ldc.i4.1 call instance void SimpleStruct::.ctor(int32) ret } // end of method EvalOrder::Test .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x206e // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Private.CoreLib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Example::.ctor } // end of class Example .class private sequential ansi sealed beforefieldinit SimpleStruct extends [System.Runtime]System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig specialname rtspecialname instance void .ctor ( int32 val ) cil managed { // Method begins at RVA 0x20f9 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.1 IL_0002: call void [System.Console]System.Console::WriteLine(int32) IL_0007: nop IL_0008: ret } // end of method SimpleStruct::.ctor } // end of class SimpleStruct
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/EvalOrder.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/EvalOrder.il", "repo_id": "ILSpy", "token_count": 698 }
207
// Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System.Core { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly ConsoleApp11 { .ver 1:0:0:0 } .module ConsoleApp11.exe // MVID: {B973FCD6-A9C4-48A9-8291-26DDC248E208} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00020003 // ILONLY 32BITPREFERRED // Image base: 0x000001C4B6C90000 .class public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1047 { .field private static bool dummy; .method private hidebysig instance void ProblemMethod() cil managed { IL_0000: ldfld bool ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1047::dummy; brfalse L_tgt1 br L_exit L_tgt1: br IL_0000 br IL_0000 L_exit: ret } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1047.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1047.il", "repo_id": "ILSpy", "token_count": 538 }
208
namespace ICSharpCode.Decompiler.Tests.TestCases.ILPretty { internal class BaseClass { public int importsClausePosition; } internal class Issue1681 : BaseClass { public void Test() { _ = importsClausePosition; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1681.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1681.cs", "repo_id": "ILSpy", "token_count": 91 }
209
using System; public static class Issue684 { static int Main(string[] A_0) { int[] array = new int[1000]; int num = int.Parse(Console.ReadLine()); // Point of this test was to ensure the stack slot here uses an appropriate type, // (bool instead of int). Unfortunately our type fixup runs too late to affect variable names. bool num2 = num >= 1000; if (!num2) { num2 = num < 2; } if (num2) { Console.WriteLine(-1); } else { int i = 2; for (int num3 = 2; num3 <= num; num3 = i) { Console.WriteLine(num3); for (; i <= num; i += num3) { int num4 = 1; array[i] = num4; } i = num3; while (true) { bool num5 = i <= num; if (num5) { num5 = array[i] != 0; } if (!num5) { break; } i++; } } } return 0; } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue684.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue684.cs", "repo_id": "ILSpy", "token_count": 428 }
210
using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class Discards { public class @_ { } public void GetOut(out int value) { value = 0; } public void GetOutOverloaded(out int value) { value = 0; } public void GetOutOverloaded(out string value) { value = "Hello World"; } public void MakeValue(Func<object, string, int> func) { } public void MakeValue(Func<@_, int> func) { } public void SimpleParameter(@_ _) { } public void ParameterHiddenByLocal(@_ _) { GetOut(out var _); } public void DiscardedOutVsLambdaParameter() { GetOut(out var _); MakeValue((@_ _) => 5); } public void ExplicitlyTypedDiscard() { GetOutOverloaded(out string _); GetOutOverloaded(out int _); } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/Discards.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/Discards.cs", "repo_id": "ILSpy", "token_count": 348 }
211
// 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; #if CS90 using System.Runtime.InteropServices; #endif namespace LocalFunctions { internal class LocalFunctions { [AttributeUsage(AttributeTargets.All)] internal class MyAttribute : Attribute { } public class Generic<T1> where T1 : struct, ICloneable, IConvertible { public int MixedLocalFunction<T2>() where T2 : ICloneable, IConvertible { #pragma warning disable CS0219 T2 t2 = default(T2); object z = this; for (int j = 0; j < 10; j++) { int i = 0; i += NonStaticMethod6<object>(0); #if CS90 [My] [return: My] int NonStaticMethod6<[My] T3>([My] int unused) #else int NonStaticMethod6<T3>(int unused) #endif { t2 = default(T2); int l = 0; return NonStaticMethod6_1<T1>() + NonStaticMethod6_1<T2>() + z.GetHashCode(); int NonStaticMethod6_1<T4>() { return i + l + NonStaticMethod6<T4>(0) + StaticMethod1<decimal>(); } } } return MixedLocalFunction<T1>() + MixedLocalFunction<T2>() + StaticMethod1<decimal>() + StaticMethod1<int>() + NonStaticMethod3() + StaticMethod4<object>(null) + StaticMethod5<T1>(); int NonStaticMethod3() { return GetHashCode(); } #if CS80 static int StaticMethod1<T3>() where T3 : struct #else int StaticMethod1<T3>() where T3 : struct #endif { return typeof(T1).Name.Length + typeof(T2).Name.Length + typeof(T3).Name.Length + StaticMethod1<float>() + StaticMethod1_1<T3, DayOfWeek>() + StaticMethod2_RepeatT2<T2, T3, DayOfWeek>(); } #if CS80 static int StaticMethod1_1<T3, T4>() where T3 : struct where T4 : Enum #else int StaticMethod1_1<T3, T4>() where T3 : struct where T4 : Enum #endif { return typeof(T1).Name.Length + typeof(T2).Name.Length + typeof(T3).Name.Length + typeof(T4).Name.Length + StaticMethod1<float>() + StaticMethod1_1<T3, DayOfWeek>(); } #pragma warning disable CS8387 #if CS80 static int StaticMethod2_RepeatT2<T2, T3, T4>() where T2 : IConvertible where T3 : struct where T4 : Enum #else int StaticMethod2_RepeatT2<T2, T3, T4>() where T2 : IConvertible where T3 : struct where T4 : Enum #endif #pragma warning restore CS8387 { return typeof(T2).Name.Length; } #if CS80 static int StaticMethod4<T>(T dd) #else int StaticMethod4<T>(T dd) #endif { return 0; } #if CS80 static int StaticMethod5<T3>() #else int StaticMethod5<T3>() #endif { int k = 0; return k + NonStaticMethod5_1<T1>(); int NonStaticMethod5_1<T4>() { return k; } } #pragma warning restore CS0219 } public int MixedLocalFunction2Delegate<T2>() where T2 : ICloneable, IConvertible { T2 t2 = default(T2); object z = this; for (int j = 0; j < 10; j++) { int i = 0; i += StaticInvokeAsFunc(NonStaticMethod6<object>); int NonStaticMethod6<T3>() { t2 = default(T2); int l = 0; return StaticInvokeAsFunc(NonStaticMethod6_1<T1>) + StaticInvokeAsFunc(NonStaticMethod6_1<T2>) + z.GetHashCode(); int NonStaticMethod6_1<T4>() { return i + l + StaticInvokeAsFunc(NonStaticMethod6<T4>) + StaticInvokeAsFunc(StaticMethod1<decimal>); } } } Console.WriteLine(t2); return StaticInvokeAsFunc(MixedLocalFunction2Delegate<T1>) + StaticInvokeAsFunc(MixedLocalFunction2Delegate<T2>) + StaticInvokeAsFunc(StaticMethod1<decimal>) + StaticInvokeAsFunc(StaticMethod1<int>) + StaticInvokeAsFunc(NonStaticMethod3) + StaticInvokeAsFunc(StaticMethod5<T1>) + new Func<object, int>(StaticMethod4<object>)(null) + StaticInvokeAsFunc2<object>(StaticMethod4<object>) + new Func<Func<object, int>, int>(StaticInvokeAsFunc2<object>)(StaticMethod4<object>); int NonStaticMethod3() { return GetHashCode(); } #if CS80 static int StaticInvokeAsFunc(Func<int> func) #else int StaticInvokeAsFunc(Func<int> func) #endif { return func(); } #if CS80 static int StaticInvokeAsFunc2<T>(Func<T, int> func) #else int StaticInvokeAsFunc2<T>(Func<T, int> func) #endif { return func(default(T)); } #if CS80 static int StaticMethod1<T3>() where T3 : struct #else int StaticMethod1<T3>() where T3 : struct #endif { return typeof(T1).Name.Length + typeof(T2).Name.Length + typeof(T3).Name.Length + StaticInvokeAsFunc(StaticMethod1<float>) + StaticInvokeAsFunc(StaticMethod1_1<T3, DayOfWeek>) + StaticInvokeAsFunc(StaticMethod2_RepeatT2<T2, T3, DayOfWeek>); } #if CS80 static int StaticMethod1_1<T3, T4>() where T3 : struct where T4 : Enum #else int StaticMethod1_1<T3, T4>() where T3 : struct where T4 : Enum #endif { return typeof(T1).Name.Length + typeof(T2).Name.Length + typeof(T3).Name.Length + typeof(T4).Name.Length + StaticInvokeAsFunc(StaticMethod1<float>) + StaticInvokeAsFunc(StaticMethod1_1<T3, DayOfWeek>); } #pragma warning disable CS8387 #if CS80 static int StaticMethod2_RepeatT2<T2, T3, T4>() where T2 : IConvertible where T3 : struct where T4 : Enum #else int StaticMethod2_RepeatT2<T2, T3, T4>() where T2 : IConvertible where T3 : struct where T4 : Enum #endif #pragma warning restore CS8387 { return typeof(T2).Name.Length; } #if CS80 static int StaticMethod4<T>(T dd) #else int StaticMethod4<T>(T dd) #endif { return 0; } #if CS80 static int StaticMethod5<T3>() #else int StaticMethod5<T3>() #endif { int k = 0; return k + StaticInvokeAsFunc(NonStaticMethod5_1<T1>); int NonStaticMethod5_1<T4>() { return k; } } } public static void Test_CaptureT<T2>() { #pragma warning disable CS0219 T2 t2 = default(T2); Method1<int>(); void Method1<T3>() { t2 = default(T2); T2 t2x = t2; T3 t3 = default(T3); Method1_1(); void Method1_1() { t2 = default(T2); t2x = t2; t3 = default(T3); } } #pragma warning restore CS0219 } public void TestGenericArgs<T2>() where T2 : List<T2> { ZZ<T2>(null); ZZ2<object>(null); #if CS80 static void Nop<T>(T data) #else void Nop<T>(T data) #endif { } #if CS80 static void ZZ<T3>(T3 t3) where T3 : T2 #else void ZZ<T3>(T3 t3) where T3 : T2 #endif { Nop<List<T2>>(t3); ZZ1<T3>(t3); ZZ3(); void ZZ3() { Nop<List<T2>>(t3); } } #if CS80 static void ZZ1<T3>(T3 t3) #else void ZZ1<T3>(T3 t3) #endif { Nop<List<T2>>((List<T2>)(object)t3); } #if CS80 static void ZZ2<T3>(T3 t3) #else void ZZ2<T3>(T3 t3) #endif { Nop<List<T2>>((List<T2>)(object)t3); } } #if false public void GenericArgsWithAnonymousType() { Method<int>(); #if CS80 static void Method<T2>() #else void Method<T2>() #endif { int i = 0; var obj2 = new { A = 1 }; Method2(obj2); Method3(obj2); void Method2<T3>(T3 obj1) { //keep nested i = 0; } #if CS80 static void Method3<T3>(T3 obj1) #else void Method3<T3>(T3 obj1) #endif { } } } #if CS80 public void NameConflict() { int i = 0; Method<int>(); void Method<T2>() { Method(); void Method() { Method<T2>(); i = 0; void Method<T2>() { i = 0; Method(); static void Method() { } } } } } #endif #endif } private int field; private Lazy<object> nonCapturinglocalFunctionInLambda = new Lazy<object>(delegate { return CreateValue(); #if CS80 static object CreateValue() #else object CreateValue() #endif { return null; } }); private Lazy<object> capturinglocalFunctionInLambda = new Lazy<object>(delegate { int x = 42; return Do(); object Do() { return CreateValue(); int CreateValue() { return x; } } }); private static void Test(int x) { } private static int GetInt(string a) { return a.Length; } private static string GetString(int a) { return a.ToString(); } public static void StaticContextNoCapture(int length) { for (int i = 0; i < length; i++) { LocalWrite("Hello " + i); } #if CS80 static void LocalWrite(string s) #else void LocalWrite(string s) #endif { Console.WriteLine(s); } } public static void StaticContextSimpleCapture(int length) { for (int i = 0; i < length; i++) { LocalWrite(); } void LocalWrite() { Console.WriteLine("Hello " + length); } } public static void StaticContextCaptureForLoopVariable(int length) { int i; for (i = 0; i < length; i++) { LocalWrite(); } void LocalWrite() { Console.WriteLine("Hello " + i + "/" + length); } } public void ContextNoCapture() { for (int i = 0; i < field; i++) { LocalWrite("Hello " + i); } #if CS80 static void LocalWrite(string s) #else void LocalWrite(string s) #endif { Console.WriteLine(s); } } public void ContextSimpleCapture() { for (int i = 0; i < field; i++) { LocalWrite(); } void LocalWrite() { Console.WriteLine("Hello " + field); } } public void ContextCaptureForLoopVariable() { int i; for (i = 0; i < field; i++) { LocalWrite(); } void LocalWrite() { Console.WriteLine("Hello " + i + "/" + field); } } public void CapturedOutsideLoop() { int i = 0; while (i < field) { i = GetInt("asdf"); LocalWrite(); } void LocalWrite() { Console.WriteLine("Hello " + i + "/" + field); } } public void CapturedInForeachLoop(IEnumerable<string> args) { foreach (string arg2 in args) { string arg = arg2; LocalWrite(); void LocalWrite() { Console.WriteLine("Hello " + arg); } } } public void Overloading() { Test(5); LocalFunctions.Test(2); #if CS80 static void Test(int x) #else void Test(int x) #endif { Console.WriteLine("x: {0}", x); } } private void Name() { } private void LocalFunctionHidingMethod() { Action action = this.Name; Name(); action(); #if CS80 static void Name() #else void Name() #endif { } } public void NamedArgument() { Use(Get(1), Get(2), Get(3)); Use(Get(1), c: Get(2), b: Get(3)); #if CS80 static int Get(int i) #else int Get(int i) #endif { return i; } #if CS80 static void Use(int a, int b, int c) #else void Use(int a, int b, int c) #endif { Console.WriteLine(a + b + c); } } public static Func<int> LambdaInLocalFunction() { int x = (int)Math.Pow(2.0, 10.0); return Create(); Func<int> Create() { return () => x; } } public static Func<int> MethodRef() { int x = (int)Math.Pow(2.0, 10.0); Enumerable.Range(1, 100).Select(LocalFunction); return null; int LocalFunction(int y) { return x * y; } } public static int Fib(int i) { return FibHelper(i); #if CS80 static int FibHelper(int n) #else int FibHelper(int n) #endif { if (n <= 0) { return 0; } return FibHelper(n - 1) + FibHelper(n - 2); } } public int MutuallyRecursiveLocalFunctions() { return B(4) + C(3); #if CS80 static int A(int i) #else int A(int i) #endif { if (i > 0) { return A(i - 1) + 2 * B(i - 1) + 3 * C(i - 1); } return 1; } #if CS80 static int B(int i) #else int B(int i) #endif { if (i > 0) { return 3 * A(i - 1) + B(i - 1); } return 1; } #if CS80 static int C(int i) #else int C(int i) #endif { if (i > 0) { return 2 * A(i - 1) + C(i - 1); } return 1; } } public static int NestedLocalFunctions(int i) { return A(); int A() { double x = Math.Pow(10.0, 2.0); return B(); int B() { return i + (int)x; } } } public static int LocalFunctionInLambda(IEnumerable<int> xs) { return xs.First(delegate (int x) { return Do(); bool Do() { return x == 3; } }); } public static IEnumerable<int> YieldReturn(int n) { return GetNumbers(); IEnumerable<int> GetNumbers() { for (int i = 0; i < n; i++) { yield return i; } } } public void WriteCapturedParameter(int i) { ParamWrite(); Console.WriteLine(i); void ParamWrite() { i++; } } //public static void LocalFunctionInUsing() //{ // using (MemoryStream memoryStream = new MemoryStream()) { // Do(); // void Do() // { // memoryStream.WriteByte(42); // } // } //} public void NestedCapture1() { Method1(null); #if CS80 static Action<object> Method1(Action<object> action) #else Action<object> Method1(Action<object> action) #endif { return Method1_1; void Method1_1(object containerBuilder) { Method1_2(containerBuilder); } void Method1_2(object containerBuilder) { action(containerBuilder); } } } public int NestedCapture2() { return Method(); #if CS80 static int Method() #else int Method() #endif { int t0 = 0; return ZZZ_0(); int ZZZ_0() { t0 = 0; int t2 = t0; return new Func<int>(ZZZ_0_0)(); int ZZZ_0_0() { t0 = 0; t2 = 0; return ZZZ_1(); } } int ZZZ_1() { t0 = 0; int t = t0; return new Func<int>(ZZZ_1_0)(); int ZZZ_1_0() { t0 = 0; t = 0; return 0; } } } } public int Issue1798_NestedCapture2() { return Method(); #if CS80 static int Method() #else int Method() #endif { int t0 = 0; return ZZZ_0(); int ZZZ_0() { t0 = 0; int t2 = t0; return ((Func<int>)delegate { t0 = 0; t2 = 0; return ZZZ_1(); })(); } int ZZZ_1() { t0 = 0; int t1 = t0; #if !OPT Func<int> func = delegate { #else return ((Func<int>)delegate { #endif t0 = 0; t1 = 0; return 0; #if !OPT }; return func(); #else })(); #endif } } } public int Issue1798_NestedCapture2b() { return Method(); #if CS80 static int Method() #else int Method() #endif { int t0 = 0; return ZZZ_0() + ZZZ_1(); int ZZZ_0() { t0 = 0; int t2 = t0; return ((Func<int>)delegate { t0 = 0; t2 = 0; return ZZZ_1(); })(); } int ZZZ_1() { t0 = 0; int t1 = t0; #if !OPT Func<int> func = delegate { #else return ((Func<int>)delegate { #endif t0 = 0; t1 = 0; return 0; #if !OPT }; return func(); #else })(); #endif } } } #if CS90 public void Issue2196() { EnumWindows(0L, 0L); [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "EnumWindows")] static extern int EnumWindows(long hWnd, long lParam); } #endif } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/LocalFunctions.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/LocalFunctions.cs", "repo_id": "ILSpy", "token_count": 7895 }
212
using System; using System.Collections.Generic; using System.Linq; namespace ICSharpCode.Decompiler.Tests.Pretty { internal class QualifierTests { private struct Test { private int dummy; private void DeclaringType(QualifierTests instance) { instance.NoParameters(); } private void DeclaringType() { StaticNoParameteres(); Parameter(null); StaticParameter(null); // The unnecessary cast is added, because we add casts before we add the qualifier. // normally it's preferable to have casts over having qualifiers, // this is an ugly edge case. QualifierTests.StaticParameter((object)null); } private void Parameter(object o) { } private static void StaticParameter(object o) { } private void Parameter(QualifierTests test) { Delegate(Parameter); Delegate(StaticParameter); Delegate(test.Parameter); Delegate(QualifierTests.StaticParameter); } private static void StaticParameter(QualifierTests test) { } private static void DeclaringTypeStatic() { } private void DeclaringTypeConflict(QualifierTests instance) { DeclaringType(); instance.DeclaringType(); fieldConflict(); instance.fieldConflict = 5; } private void DeclaringTypeConflict() { DeclaringTypeStatic(); QualifierTests.DeclaringTypeStatic(); } private void fieldConflict() { } private void Delegate(Action<object> action) { } public string ThisQualifierWithCast() { return ((object)this).ToString(); } public override string ToString() { // decompiled as return ((ValueType)this).ToString(); return base.ToString(); } } internal class Parent { public virtual void Virtual() { } public virtual void NewVirtual() { } public void New() { } public void BaseOnly() { } } internal class Child : Parent { public override void Virtual() { base.Virtual(); } public new void NewVirtual() { base.NewVirtual(); } public new void New() { base.New(); } public void BaseQualifiers() { Virtual(); base.Virtual(); NewVirtual(); base.NewVirtual(); New(); base.New(); BaseOnly(); } } private class i { public static void Test() { } } private class value { public static int item; public static void Test() { } } public class Root { private int prop; #if LEGACY_CSC public int Prop { get { return prop; } } #else public int Prop => prop; #endif public void M<T>(T a) { } } public abstract class Base : Root { public new abstract int Prop { get; } public new abstract void M<T>(T a); } public class Derived : Base { #if LEGACY_CSC public override int Prop { get { return ((Root)this).Prop; } } #else public override int Prop => ((Root)this).Prop; #endif public override void M<T>(T a) { ((Root)this).M(a); } } private int fieldConflict; private int innerConflict; private static int PropertyValueParameterConflictsWithTypeName { get { return value.item; } set { QualifierTests.value.item = value; } } private int this[string[] Array] { get { System.Array.Sort(Array); return 0; } set { System.Array.Sort(Array); QualifierTests.value.item = value; } } private void NoParameters() { Delegate(Parameter); Delegate(StaticParameter); } private static void StaticNoParameteres() { } private void Parameter(object o) { } private static void StaticParameter(object o) { } private void DeclaringType() { } private static void DeclaringTypeStatic() { } private void conflictWithParameter() { } private void conflictWithVariable(int val) { } private void Conflicts(int conflictWithParameter) { this.conflictWithParameter(); } private void Conflicts() { int conflictWithVariable = 5; this.conflictWithVariable(conflictWithVariable); // workaround for missing identifiers in il Capturer(() => conflictWithVariable); } private void Capturing() { int fieldConflict = 5; Capturer(() => this.fieldConflict + fieldConflict); Capturer(delegate { int innerConflict = 5; return this.fieldConflict + fieldConflict + Capturer2(() => this.innerConflict + innerConflict + this.fieldConflict + fieldConflict); }); } private void Capturer(Func<int> func) { } private int Capturer2(Func<int> func) { return 0; } private void Delegate(Action<object> action) { } private void ParameterConflictsWithTypeName(string[] Array) { System.Array.Sort(Array); } private void LocalConflictsWithTypeName() { for (int i = 0; i < 10; i++) { QualifierTests.i.Test(); } } public QualifierTests(string[] Array) { System.Array.Sort(Array); } } internal static class ZExt { public static void Do(this int test) { } public static void Do(this object test) { } #if CS72 public static void Do(this ref DateTime test) { } #endif public static void Do2(this int test, DateTime date) { test.Do(); ((IEnumerable<int>)null).Any(); ((object)null).Do(); #if CS72 date.Do(); #endif } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/QualifierTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/QualifierTests.cs", "repo_id": "ILSpy", "token_count": 2189 }
213
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public class T01_IndexerWithGetOnly { #if ROSLYN public int this[int i] => i; #else public int this[int i] { get { return i; } } #endif } public class T02_IndexerWithSetOnly { public int this[int i] { set { } } } public class T03_IndexerWithMoreParameters { #if ROSLYN public int this[int i, string s, Type t] => 0; #else public int this[int i, string s, Type t] { get { return 0; } } #endif } public class T04_IndexerInGenericClass<T> { #if ROSLYN public int this[T t] => 0; #else public int this[T t] { get { return 0; } } #endif } public class T05_OverloadedIndexer { #if ROSLYN public int this[int t] => 0; #else public int this[int t] { get { return 0; } } #endif public int this[string s] { get { return 0; } set { Console.WriteLine(value + " " + s); } } } public interface T06_IIndexerInInterface { int this[string s, string s2] { set; } } public interface T07_IMyInterface_IndexerInterfaceExplicitImplementation { int this[string s] { get; } } public class T07_MyClass_IndexerInterfaceExplicitImplementation : T07_IMyInterface_IndexerInterfaceExplicitImplementation { #if ROSLYN int T07_IMyInterface_IndexerInterfaceExplicitImplementation.this[string s] => 3; #else int T07_IMyInterface_IndexerInterfaceExplicitImplementation.this[string s] { get { return 3; } } #endif } public interface T08_IMyInterface_IndexerInterfaceImplementation { int this[string s] { get; } } public class T08_MyClass_IndexerInterfaceImplementation : T08_IMyInterface_IndexerInterfaceImplementation { #if ROSLYN public int this[string s] => 3; #else public int this[string s] { get { return 3; } } #endif } public interface T09_IMyInterface_MethodExplicit { void MyMethod(); } public abstract class T09_MyClass_IndexerAbstract { public abstract int this[string s, string s2] { set; } protected abstract string this[int index] { get; } } public class T09_MyClass_MethodExplicit : T09_IMyInterface_MethodExplicit { void T09_IMyInterface_MethodExplicit.MyMethod() { } } public interface T10_IMyInterface_MethodFromInterfaceVirtual { void MyMethod(); } public class T10_MyClass : T10_IMyInterface_MethodFromInterfaceVirtual { public virtual void MyMethod() { } } public interface T11_IMyInterface_MethodFromInterface { void MyMethod(); } public class T11_MyClass_MethodFromInterface : T11_IMyInterface_MethodFromInterface { public void MyMethod() { } } public interface T12_IMyInterface_MethodFromInterfaceAbstract { void MyMethod(); } public abstract class T12_MyClass_MethodFromInterfaceAbstract : T12_IMyInterface_MethodFromInterfaceAbstract { public abstract void MyMethod(); } public interface T13_IMyInterface_PropertyInterface { int MyProperty { get; set; } } public interface T14_IMyInterface_PropertyInterfaceExplicitImplementation { int MyProperty { get; set; } } public class T14_MyClass_PropertyInterfaceExplicitImplementation : T14_IMyInterface_PropertyInterfaceExplicitImplementation { int T14_IMyInterface_PropertyInterfaceExplicitImplementation.MyProperty { get { return 0; } set { } } } public interface T15_IMyInterface_PropertyInterfaceImplementation { int MyProperty { get; set; } } public class T15_MyClass_PropertyInterfaceImplementation : T15_IMyInterface_PropertyInterfaceImplementation { public int MyProperty { get { return 0; } set { } } } public class T16_MyClass_PropertyPrivateGetPublicSet { public int MyProperty { private get { return 3; } set { } } } public class T17_MyClass_PropertyPublicGetProtectedSet { public int MyProperty { get { return 3; } protected set { } } } public class T18_Base_PropertyOverrideDefaultAccessorOnly { public virtual int MyProperty { get { return 3; } protected set { } } } public class T18_Derived_PropertyOverrideDefaultAccessorOnly : T18_Base_PropertyOverrideDefaultAccessorOnly { #if ROSLYN public override int MyProperty => 4; #else public override int MyProperty { get { return 4; } } #endif } public class T19_Base_PropertyOverrideRestrictedAccessorOnly { public virtual int MyProperty { get { return 3; } protected set { } } } public class T19_Derived_PropertyOverrideRestrictedAccessorOnly : T19_Base_PropertyOverrideRestrictedAccessorOnly { public override int MyProperty { protected set { } } } public class T20_Base_PropertyOverrideOneAccessor { protected internal virtual int MyProperty { get { return 3; } protected set { } } } public class T20_DerivedNew_PropertyOverrideOneAccessor : T20_Base_PropertyOverrideOneAccessor { public new virtual int MyProperty { set { } } } public class T20_DerivedOverride_PropertyOverrideOneAccessor : T20_DerivedNew_PropertyOverrideOneAccessor { public override int MyProperty { set { } } } public class T21_Base_IndexerOverrideRestrictedAccessorOnly { public virtual int this[string s] { get { return 3; } protected set { } } protected internal virtual int this[int i] { protected get { return 2; } set { } } } public class T21_Derived_IndexerOverrideRestrictedAccessorOnly : T21_Base_IndexerOverrideRestrictedAccessorOnly { protected internal override int this[int i] { protected get { return 4; } } } public class T22_A_HideProperty { public virtual int P { get { return 0; } set { } } } public class T22_B_HideProperty : T22_A_HideProperty { private new int P { get { return 0; } set { } } } public class T22_C_HideProperty : T22_B_HideProperty { public override int P { set { } } } public class T23_A_HideMembers { public int F; #if ROSLYN public int Prop => 3; public int G => 3; #else public int Prop { get { return 3; } } public int G { get { return 3; } } #endif } public class T23_B_HideMembers : T23_A_HideMembers { #if ROSLYN public new int F => 3; public new string Prop => "a"; #else public new int F { get { return 3; } } public new string Prop { get { return "a"; } } #endif } public class T23_C_HideMembers : T23_A_HideMembers { public new int G; } public class T23_D_HideMembers : T23_A_HideMembers { public new void F() { } } public class T23_D1_HideMembers : T23_D_HideMembers { public new int F; } public class T23_E_HideMembers : T23_A_HideMembers { private new class F { } } public class T23_G_HideMembers2 { #if ROSLYN public int Item => 1; #else public int Item { get { return 1; } } #endif } public class T23_G2_HideMembers2 : T23_G_HideMembers2 { #if ROSLYN public int this[int i] => 2; #else public int this[int i] { get { return 2; } } #endif } public class T23_G3_HideMembers2 : T23_G2_HideMembers2 { #if ROSLYN public new int Item => 4; #else public new int Item { get { return 4; } } #endif } public class T23_H_HideMembers2 { #if ROSLYN public int this[int j] => 0; #else public int this[int j] { get { return 0; } } #endif } public class T23_H2_HideMembers2 : T23_H_HideMembers2 { #if ROSLYN public int Item => 2; #else public int Item { get { return 2; } } #endif } public class T23_H3_HideMembers2 : T23_H2_HideMembers2 { #if ROSLYN public new string this[int j] => null; #else public new string this[int j] { get { return null; } } #endif } public class T24_A_HideMembers2a : T24_IA_HideMembers2a { int T24_IA_HideMembers2a.this[int i] { get { throw new NotImplementedException(); } } } public class T24_A1_HideMembers2a : T24_A_HideMembers2a { #if ROSLYN public int this[int i] => 3; #else public int this[int i] { get { return 3; } } #endif } public interface T24_IA_HideMembers2a { int this[int i] { get; } } public class T25_G_HideMembers3<T> { public void M1(T p) { } public int M2(int t) { return 3; } } public class T25_G1_HideMembers3<T> : T25_G_HideMembers3<int> { public new int M1(int i) { return 0; } public int M2(T i) { return 2; } } public class T25_G2_HideMembers3<T> : T25_G_HideMembers3<int> { public int M1(T p) { return 4; } } public class T25_J_HideMembers3 { #if ROSLYN public int P => 2; #else public int P { get { return 2; } } #endif } public class T25_J2_HideMembers3 : T25_J_HideMembers3 { #pragma warning disable 0108 // Deliberate bad code for test case public int get_P; #pragma warning restore 0108 } public class T26_A_HideMembers4 { public void M<T>(T t) { } } public class T26_A1_HideMembers4 : T26_A_HideMembers4 { public new void M<K>(K t) { } public void M(int t) { } } public class T26_B_HideMembers4 { public void M<T>() { } public void M1<T>() { } public void M2<T>(T t) { } } public class T26_B1_HideMembers4 : T26_B_HideMembers4 { public void M<T1, T2>() { } public new void M1<R>() { } public new void M2<R>(R r) { } } public class T26_C_HideMembers4<T> { public void M<TT>(T t) { } } public class T26_C1_HideMembers4<K> : T26_C_HideMembers4<K> { public void M<TT>(TT t) { } } public class T27_A_HideMembers5 { public void M(int t) { } } public class T27_A1_HideMembers5 : T27_A_HideMembers5 { public void M(ref int t) { } } public class T27_B_HideMembers5 { public void M(ref int l) { } } public class T27_B1_HideMembers5 : T27_B_HideMembers5 { public void M(out int l) { l = 2; } public void M(ref long l) { } } public class T28_A_HideMemberSkipNotVisible { protected int F; #if ROSLYN protected string P => null; #else protected string P { get { return null; } } #endif } public class T28_B_HideMemberSkipNotVisible : T28_A_HideMemberSkipNotVisible { private new string F; private new int P { set { } } } public class T29_A_HideNestedClass { public class N1 { } protected class N2 { } private class N3 { } internal class N4 { } protected internal class N5 { } } public class T29_B_HideNestedClass : T29_A_HideNestedClass { public new int N1; public new int N2; public int N3; public new int N4; public new int N5; } public class T30_A_HidePropertyReservedMethod { #if ROSLYN public int P => 1; #else public int P { get { return 1; } } #endif } public class T30_B_HidePropertyReservedMethod : T30_A_HidePropertyReservedMethod { public int get_P() { return 2; } public void set_P(int value) { } } public class T31_A_HideIndexerDiffAccessor { #if ROSLYN public int this[int i] => 2; #else public int this[int i] { get { return 2; } } #endif } public class T31_B_HideIndexerDiffAccessor : T31_A_HideIndexerDiffAccessor { public new int this[int j] { set { } } } public class T32_A_HideIndexerGeneric<T> { public virtual int this[T r] { get { return 0; } set { } } } public class T32_B_HideIndexerGeneric : T32_A_HideIndexerGeneric<int> { private new int this[int k] { get { return 0; } set { } } } public class T32_C_HideIndexerGeneric<T> : T32_A_HideIndexerGeneric<T> { public override int this[T s] { set { } } } public class T32_D_HideIndexerGeneric<T> : T32_C_HideIndexerGeneric<T> { public new virtual int this[T s] { set { } } } public class T33_A_HideMethod { public virtual void F() { } } public class T33_B_HideMethod : T33_A_HideMethod { private new void F() { base.F(); } } public class T33_C_HideMethod : T33_B_HideMethod { public override void F() { base.F(); } } public class T34_A_HideMethodGeneric<T> { public virtual void F(T s) { } public new static bool Equals(object o1, object o2) { return true; } } public class T34_B_HideMethodGeneric : T34_A_HideMethodGeneric<string> { private new void F(string k) { } public void F(int i) { } } public class T34_C_HideMethodGeneric<T> : T34_A_HideMethodGeneric<T> { public override void F(T r) { } public void G(T t) { } } public class T34_D_HideMethodGeneric<T1> : T34_C_HideMethodGeneric<T1> { public new virtual void F(T1 k) { } public virtual void F<T2>(T2 k) { } public virtual void G<T2>(T2 t) { } } public class T35_A_HideMethodGenericSkipPrivate<T> { public virtual void F(T t) { } } public class T35_B_HideMethodGenericSkipPrivate<T> : T35_A_HideMethodGenericSkipPrivate<T> { private new void F(T t) { } private void K() { } } public class T35_C_HideMethodGenericSkipPrivate<T> : T35_B_HideMethodGenericSkipPrivate<T> { public override void F(T tt) { } public void K() { } } public class T35_D_HideMethodGenericSkipPrivate : T35_B_HideMethodGenericSkipPrivate<int> { public override void F(int t) { } } public class T36_A_HideMethodGeneric2 { public virtual void F(int i) { } public void K() { } } public class T36_B_HideMethodGeneric2<T> : T36_A_HideMethodGeneric2 { protected virtual void F(T t) { } public void K<T2>() { } } public class T36_C_HideMethodGeneric2 : T36_B_HideMethodGeneric2<int> { protected override void F(int k) { } public new void K<T3>() { } } public class T36_D_HideMethodGeneric2 : T36_B_HideMethodGeneric2<string> { public override void F(int k) { } public void L<T4>() { } } public class T36_E_HideMethodGeneric2<T> { public void M<T2>(T t, T2 t2) { } } public class T36_F_HideMethodGeneric2<T> : T36_E_HideMethodGeneric2<T> { public void M(T t1, T t2) { } } public class T37_C1_HideMethodDiffSignatures<T> { public virtual void M(T arg) { } } public class T37_C2_HideMethodDiffSignatures<T1, T2> : T37_C1_HideMethodDiffSignatures<T2> { public new virtual void M(T2 arg) { } } public class T37_C3_HideMethodDiffSignatures : T37_C2_HideMethodDiffSignatures<int, bool> { public new virtual void M(bool arg) { } } public class T38_A_HideMethodStatic { #if ROSLYN public int N => 0; #else public int N { get { return 0; } } #endif } public class T38_B_HideMethodStatic { public int N() { return 0; } } public class T39_A_HideEvent { public virtual event EventHandler E; public event EventHandler F; } public class T39_B_HideEvent : T39_A_HideEvent { public new virtual event EventHandler E; public new event EventHandler F; } public class T39_C_HideEvent : T39_B_HideEvent { public override event EventHandler E; } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/TypeMemberTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/TypeMemberTests.cs", "repo_id": "ILSpy", "token_count": 6936 }
214
// 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 AggressiveScalarReplacementOfAggregates { .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 07 01 00 00 00 00 ) .permissionset reqmin = {[mscorlib]System.Security.Permissions.SecurityPermissionAttribute = {property bool 'SkipVerification' = bool(true)}} .hash algorithm 0x00008004 .ver 0:0:0:0 } .module AggressiveScalarReplacementOfAggregates.dll .custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = ( 01 00 00 00 ) .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass extends [mscorlib]System.Object { .field public class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program thisField .field public int32 field1 .field public string field2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method DisplayClass::.ctor } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass .class public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass extends [mscorlib]System.Object { .field public class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass field3 .field public int32 field1 .field public string field2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method NestedDisplayClass::.ctor } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass .class public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program extends [mscorlib]System.Object { .method public hidebysig instance int32 Rand() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: nop IL_0001: newobj instance void [mscorlib]System.NotImplementedException::.ctor() IL_0006: throw } // end of method Program::Rand .method public hidebysig instance void Test1() cil managed { // Code size 55 (0x37) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldc.i4.s 42 IL_0009: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000e: dup IL_000f: ldstr "Hello World!" IL_0014: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0019: stloc.0 IL_001a: ldstr "{0} {1}" IL_001f: ldloc.0 IL_0020: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0025: box [mscorlib]System.Int32 IL_002a: ldloc.0 IL_002b: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0030: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0035: nop IL_0036: ret } // end of method Program::Test1 .method public hidebysig instance void Test2() cil managed { // Code size 60 (0x3c) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldc.i4.s 42 IL_0009: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000e: dup IL_000f: ldstr "Hello World!" IL_0014: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0019: stloc.0 IL_001a: ldstr "{0} {1}" IL_001f: ldloc.0 IL_0020: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0025: box [mscorlib]System.Int32 IL_002a: ldloc.0 IL_002b: callvirt instance int32 [mscorlib]System.Object::GetHashCode() IL_0030: box [mscorlib]System.Int32 IL_0035: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_003a: nop IL_003b: ret } // end of method Program::Test2 .method public hidebysig instance void Test3() cil managed { // Code size 50 (0x32) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldc.i4.s 42 IL_0009: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000e: dup IL_000f: ldstr "Hello World!" IL_0014: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0019: stloc.0 IL_001a: ldstr "{0} {1}" IL_001f: ldloc.0 IL_0020: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0025: box [mscorlib]System.Int32 IL_002a: ldloc.0 IL_002b: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0030: nop IL_0031: ret } // end of method Program::Test3 .method public hidebysig instance void Test4() cil managed { // Code size 114 (0x72) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass V_1, bool V_2) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldarg.0 IL_0008: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::thisField IL_000d: dup IL_000e: ldc.i4.s 42 IL_0010: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0015: dup IL_0016: ldstr "Hello World!" IL_001b: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0020: stloc.0 IL_0021: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::.ctor() IL_0026: dup IL_0027: ldc.i4 0x1267 IL_002c: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0031: dup IL_0032: ldstr "ILSpy" IL_0037: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_003c: stloc.1 IL_003d: ldloc.0 IL_003e: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0043: ldc.i4.s 100 IL_0045: cgt IL_0047: stloc.2 IL_0048: ldloc.2 IL_0049: brfalse.s IL_0056 IL_004b: nop IL_004c: ldloc.1 IL_004d: ldloc.0 IL_004e: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0053: nop IL_0054: br.s IL_005f IL_0056: nop IL_0057: ldloc.1 IL_0058: ldnull IL_0059: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_005e: nop IL_005f: ldstr "{0} {1}" IL_0064: ldloc.0 IL_0065: ldloc.1 IL_0066: ldfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_006b: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0070: nop IL_0071: ret } // end of method Program::Test4 .method public hidebysig instance void Test5() cil managed { // Code size 135 (0x87) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass V_1, bool V_2) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldarg.0 IL_0008: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::thisField IL_000d: dup IL_000e: ldc.i4.s 42 IL_0010: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0015: dup IL_0016: ldstr "Hello World!" IL_001b: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0020: stloc.0 IL_0021: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::.ctor() IL_0026: dup IL_0027: ldc.i4 0x1267 IL_002c: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0031: dup IL_0032: ldstr "ILSpy" IL_0037: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_003c: stloc.1 IL_003d: ldloc.0 IL_003e: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0043: ldc.i4.s 100 IL_0045: cgt IL_0047: stloc.2 IL_0048: ldloc.2 IL_0049: brfalse.s IL_0056 IL_004b: nop IL_004c: ldloc.1 IL_004d: ldloc.0 IL_004e: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0053: nop IL_0054: br.s IL_005f IL_0056: nop IL_0057: ldloc.1 IL_0058: ldnull IL_0059: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_005e: nop IL_005f: ldstr "{0} {1}" IL_0064: ldloc.1 IL_0065: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_006a: ldloc.1 IL_006b: ldflda int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0070: call instance string [mscorlib]System.Int32::ToString() IL_0075: call string [mscorlib]System.String::Concat(string, string) IL_007a: ldloc.1 IL_007b: ldfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0080: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0085: nop IL_0086: ret } // end of method Program::Test5 .method public hidebysig instance void Issue1898(int32 i) cil managed { // Code size 151 (0x97) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass V_1, int32 V_2, int32 V_3, int32 V_4, bool V_5) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldarg.0 IL_0008: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::thisField IL_000d: dup IL_000e: ldarg.1 IL_000f: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0014: stloc.0 IL_0015: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::.ctor() IL_001a: stloc.1 IL_001b: br.s IL_0092 IL_001d: nop IL_001e: ldarg.0 IL_001f: call instance int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program::Rand() IL_0024: stloc.3 IL_0025: ldloc.3 IL_0026: stloc.2 IL_0027: ldloc.2 IL_0028: ldc.i4.1 IL_0029: sub IL_002a: switch ( IL_003d, IL_004b, IL_0062) IL_003b: br.s IL_006b IL_003d: ldloc.1 IL_003e: ldarg.0 IL_003f: call instance int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program::Rand() IL_0044: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0049: br.s IL_0091 IL_004b: ldloc.1 IL_004c: ldarg.0 IL_004d: call instance int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program::Rand() IL_0052: stloc.s V_4 IL_0054: ldloca.s V_4 IL_0056: call instance string [mscorlib]System.Int32::ToString() IL_005b: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_0060: br.s IL_0091 IL_0062: ldloc.1 IL_0063: ldloc.0 IL_0064: stfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0069: br.s IL_0091 IL_006b: ldloc.1 IL_006c: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field1 IL_0071: call void [mscorlib]System.Console::WriteLine(int32) IL_0076: nop IL_0077: ldloc.1 IL_0078: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field2 IL_007d: call void [mscorlib]System.Console::WriteLine(string) IL_0082: nop IL_0083: ldloc.1 IL_0084: ldfld class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass ICSharpCode.Decompiler.Tests.TestCases.Ugly.NestedDisplayClass::field3 IL_0089: call void [mscorlib]System.Console::WriteLine(object) IL_008e: nop IL_008f: br.s IL_0091 IL_0091: nop IL_0092: ldc.i4.1 IL_0093: stloc.s V_5 IL_0095: br.s IL_001d } // end of method Program::Issue1898 .method public hidebysig instance void Test6(int32 i) cil managed { // Code size 68 (0x44) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, bool V_1) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldarg.1 IL_0008: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000d: dup IL_000e: ldstr "Hello World!" IL_0013: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0018: stloc.0 IL_0019: ldarg.1 IL_001a: ldc.i4.0 IL_001b: clt IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: brfalse.s IL_0027 IL_0021: nop IL_0022: ldarg.1 IL_0023: neg IL_0024: starg.s i IL_0026: nop IL_0027: ldstr "{0} {1}" IL_002c: ldloc.0 IL_002d: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0032: box [mscorlib]System.Int32 IL_0037: ldloc.0 IL_0038: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_003d: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0042: nop IL_0043: ret } // end of method Program::Test6 .method public hidebysig instance void Test6b(int32 i) cil managed { // Code size 69 (0x45) .maxstack 3 .locals init (int32 V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_1, bool V_2) IL_0000: nop IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0008: dup IL_0009: ldloc.0 IL_000a: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000f: dup IL_0010: ldstr "Hello World!" IL_0015: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_001a: stloc.1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: clt IL_001f: stloc.2 IL_0020: ldloc.2 IL_0021: brfalse.s IL_0028 IL_0023: nop IL_0024: ldloc.0 IL_0025: neg IL_0026: stloc.0 IL_0027: nop IL_0028: ldstr "{0} {1}" IL_002d: ldloc.1 IL_002e: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0033: box [mscorlib]System.Int32 IL_0038: ldloc.1 IL_0039: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_003e: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0043: nop IL_0044: ret } // end of method Program::Test6b .method public hidebysig instance void Test7(int32 i) cil managed { // Code size 71 (0x47) .maxstack 4 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0, int32 V_1) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldarg.1 IL_0008: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000d: dup IL_000e: ldstr "Hello World!" IL_0013: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0018: stloc.0 IL_0019: ldstr "{0} {1} {2}" IL_001e: ldloc.0 IL_001f: dup IL_0020: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: add IL_0029: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_002e: ldloc.1 IL_002f: box [mscorlib]System.Int32 IL_0034: ldloc.0 IL_0035: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_003a: ldarg.1 IL_003b: box [mscorlib]System.Int32 IL_0040: call void [mscorlib]System.Console::WriteLine(string, object, object, object) IL_0045: nop IL_0046: ret } // end of method Program::Test7 .method public hidebysig instance void Test8(int32 i) cil managed { // Code size 58 (0x3a) .maxstack 3 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_0) IL_0000: nop IL_0001: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0006: dup IL_0007: ldarg.1 IL_0008: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000d: dup IL_000e: ldstr "Hello World!" IL_0013: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0018: stloc.0 IL_0019: ldc.i4.s 42 IL_001b: starg.s i IL_001d: ldstr "{0} {1}" IL_0022: ldloc.0 IL_0023: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0028: box [mscorlib]System.Int32 IL_002d: ldloc.0 IL_002e: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0033: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0038: nop IL_0039: ret } // end of method Program::Test8 .method public hidebysig instance void Test8b(int32 i) cil managed { // Code size 59 (0x3b) .maxstack 3 .locals init (int32 V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::.ctor() IL_0008: dup IL_0009: ldloc.0 IL_000a: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_000f: dup IL_0010: ldstr "Hello World!" IL_0015: stfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_001a: stloc.1 IL_001b: ldc.i4.s 42 IL_001d: stloc.0 IL_001e: ldstr "{0} {1}" IL_0023: ldloc.1 IL_0024: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field1 IL_0029: box [mscorlib]System.Int32 IL_002e: ldloc.1 IL_002f: ldfld string ICSharpCode.Decompiler.Tests.TestCases.Ugly.DisplayClass::field2 IL_0034: call void [mscorlib]System.Console::WriteLine(string, object, object) IL_0039: nop IL_003a: ret } // end of method Program::Test8b .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Program::.ctor } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Program // ============================================================= // *********** DISASSEMBLY COMPLETE ***********************
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/AggressiveScalarReplacementOfAggregates.roslyn.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/AggressiveScalarReplacementOfAggregates.roslyn.il", "repo_id": "ILSpy", "token_count": 12388 }
215
// 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 tmpA29A { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 02 00 00 00 00 00 ) .permissionset reqmin = {[mscorlib]System.Security.Permissions.SecurityPermissionAttribute = {property bool 'SkipVerification' = bool(true)}} .hash algorithm 0x00008004 .ver 0:0:0:0 } .module tmpA29A.tmp .custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = ( 01 00 00 00 ) .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // =============== CLASS MEMBERS DECLARATION =================== .class private abstract auto ansi sealed beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method assembly hidebysig static class [mscorlib]System.Func`1<!!T> AsFunc<class T>(!!T 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 18 (0x12) .maxstack 8 IL_0000: ldarg.0 IL_0001: box !!T IL_0006: ldftn !!0 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods::Return<!!0>(!!0) IL_000c: newobj instance void class [mscorlib]System.Func`1<!!T>::.ctor(object, native int) IL_0011: ret } // end of method NoExtensionMethods::AsFunc .method private hidebysig static !!T Return<T>(!!T 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: ldarg.0 IL_0001: ret } // end of method NoExtensionMethods::Return .method assembly hidebysig static class [mscorlib]System.Func`2<int32,int32> ExtensionMethodAsStaticFunc() cil managed { // Code size 13 (0xd) .maxstack 8 IL_0000: ldnull IL_0001: ldftn !!0 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods::Return<int32>(!!0) IL_0007: newobj instance void class [mscorlib]System.Func`2<int32,int32>::.ctor(object, native int) IL_000c: ret } // end of method NoExtensionMethods::ExtensionMethodAsStaticFunc .method assembly hidebysig static class [mscorlib]System.Func`1<object> ExtensionMethodBoundToNull() cil managed { // Code size 13 (0xd) .maxstack 8 IL_0000: ldnull IL_0001: ldftn !!0 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods::Return<object>(!!0) IL_0007: newobj instance void class [mscorlib]System.Func`1<object>::.ctor(object, native int) IL_000c: ret } // end of method NoExtensionMethods::ExtensionMethodBoundToNull } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods // ============================================================= // *********** DISASSEMBLY COMPLETE ***********************
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoExtensionMethods.opt.net40.roslyn.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoExtensionMethods.opt.net40.roslyn.il", "repo_id": "ILSpy", "token_count": 1872 }
216
// 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 NoLocalFunctions { .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 07 01 00 00 00 00 ) .permissionset reqmin = {[mscorlib]System.Security.Permissions.SecurityPermissionAttribute = {property bool 'SkipVerification' = bool(true)}} .hash algorithm 0x00008004 .ver 0:0:0:0 } .module NoLocalFunctions.dll .custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = ( 01 00 00 00 ) .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi sealed beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle extends [mscorlib]System.Object { .field private initonly class [mscorlib]System.Func`1<int32> _func .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Func`1<int32> func) cil managed { // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: stfld class [mscorlib]System.Func`1<int32> ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle::_func IL_000f: ret } // end of method Handle::.ctor } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle .class public abstract auto ansi sealed beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions extends [mscorlib]System.Object { .class auto ansi sealed nested private beforefieldinit '<>c__DisplayClass1_0' extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .field public int32 x } // end of class '<>c__DisplayClass1_0' .class auto ansi sealed nested private beforefieldinit '<>c__DisplayClass2_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .field public int32 x .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass2_0'::.ctor .method assembly hidebysig instance int32 '<SimpleCaptureWithRef>g__F|0'() cil managed { // Code size 10 (0xa) .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ldarg.0 IL_0003: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0'::x IL_0008: add IL_0009: ret } // end of method '<>c__DisplayClass2_0'::'<SimpleCaptureWithRef>g__F|0' } // end of class '<>c__DisplayClass2_0' .method private hidebysig static void UseLocalFunctionReference() cil managed { // Code size 21 (0x15) .maxstack 2 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle V_0) IL_0000: nop IL_0001: nop IL_0002: ldnull IL_0003: ldftn int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions::'<UseLocalFunctionReference>g__F|0_0'() IL_0009: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_000e: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle::.ctor(class [mscorlib]System.Func`1<int32>) IL_0013: stloc.0 IL_0014: ret } // end of method NoLocalFunctions::UseLocalFunctionReference .method private hidebysig static void SimpleCapture() cil managed { // Code size 19 (0x13) .maxstack 2 .locals init (valuetype ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0' V_0) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0'::x IL_0009: nop IL_000a: ldloca.s V_0 IL_000c: call int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions::'<SimpleCapture>g__F|1_0'(valuetype ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0'&) IL_0011: pop IL_0012: ret } // end of method NoLocalFunctions::SimpleCapture .method private hidebysig static void SimpleCaptureWithRef() cil managed { // Code size 34 (0x22) .maxstack 2 .locals init (class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0' V_0, class ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle V_1) IL_0000: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0'::.ctor() IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: stfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0'::x IL_000e: nop IL_000f: ldloc.0 IL_0010: ldftn instance int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass2_0'::'<SimpleCaptureWithRef>g__F|0'() IL_0016: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_001b: newobj instance void ICSharpCode.Decompiler.Tests.TestCases.Ugly.Handle::.ctor(class [mscorlib]System.Func`1<int32>) IL_0020: stloc.1 IL_0021: ret } // end of method NoLocalFunctions::SimpleCaptureWithRef .method assembly hidebysig static int32 '<UseLocalFunctionReference>g__F|0_0'() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ret } // end of method NoLocalFunctions::'<UseLocalFunctionReference>g__F|0_0' .method assembly hidebysig static int32 '<SimpleCapture>g__F|1_0'(valuetype ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0'& A_0) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: ldarg.0 IL_0003: ldfld int32 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions/'<>c__DisplayClass1_0'::x IL_0008: add IL_0009: ret } // end of method NoLocalFunctions::'<SimpleCapture>g__F|1_0' } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoLocalFunctions // ============================================================= // *********** DISASSEMBLY COMPLETE ***********************
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoLocalFunctions.roslyn.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoLocalFunctions.roslyn.il", "repo_id": "ILSpy", "token_count": 3560 }
217
using System; using Microsoft.VisualBasic.CompilerServices; [StandardModule] internal sealed class Program { public static void SelectOnString() { switch (Environment.CommandLine) { case "123": Console.WriteLine("a"); break; case "444": Console.WriteLine("b"); break; case "222": Console.WriteLine("c"); break; case "11": Console.WriteLine("d"); break; case "dd": Console.WriteLine("e"); break; case "sss": Console.WriteLine("f"); break; case "aa": Console.WriteLine("g"); break; case null: case "": Console.WriteLine("empty"); break; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Select.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Select.cs", "repo_id": "ILSpy", "token_count": 290 }
218
// 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.CodeDom.Compiler; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using ICSharpCode.Decompiler.Tests.Helpers; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests { [TestFixture, Parallelizable(ParallelScope.All)] public class UglyTestRunner { static readonly string TestCasePath = Tester.TestCasePath + "/Ugly"; [Test] public void AllFilesHaveTests() { var testNames = GetType().GetMethods() .Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Any()) .Select(m => m.Name) .ToArray(); foreach (var file in new DirectoryInfo(TestCasePath).EnumerateFiles()) { if (file.Extension.Equals(".il", StringComparison.OrdinalIgnoreCase) || file.Extension.Equals(".cs", StringComparison.OrdinalIgnoreCase)) { var testName = file.Name.Split('.')[0]; Assert.That(testNames, Has.Member(testName)); } } } static readonly CompilerOptions[] noRoslynOptions = { CompilerOptions.None, CompilerOptions.Optimize }; static readonly CompilerOptions[] roslynOnlyOptions = { CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] defaultOptions = { CompilerOptions.None, CompilerOptions.Optimize, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; [Test] public async Task NoArrayInitializers([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings(CSharp.LanguageVersion.CSharp1) { ArrayInitializers = false }); } [Test] public async Task NoDecimalConstants([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings(CSharp.LanguageVersion.CSharp1) { DecimalConstants = false }); } [Test] public async Task NoExtensionMethods([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings(CSharp.LanguageVersion.CSharp9_0) { ExtensionMethods = false }); } [Test] public async Task NoForEachStatement([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings(CSharp.LanguageVersion.CSharp1) { ForEachStatement = false, UseEnhancedUsing = false, }); } [Test] public async Task NoLocalFunctions([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings(CSharp.LanguageVersion.CSharp1)); } [Test] public async Task NoPropertiesAndEvents([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings(CSharp.LanguageVersion.CSharp1) { AutomaticEvents = false, AutomaticProperties = false, }); } [Test] public async Task AggressiveScalarReplacementOfAggregates([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions) { await RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings(CSharp.LanguageVersion.CSharp3) { AggressiveScalarReplacementOfAggregates = true }); } async Task RunForLibrary([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, DecompilerSettings decompilerSettings = null) { await Run(testName, asmOptions | AssemblerOptions.Library, cscOptions | CompilerOptions.Library, decompilerSettings); } async Task Run([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, DecompilerSettings decompilerSettings = null) { var ilFile = Path.Combine(TestCasePath, testName) + Tester.GetSuffix(cscOptions) + ".il"; var csFile = Path.Combine(TestCasePath, testName + ".cs"); var expectedFile = Path.Combine(TestCasePath, testName + ".Expected.cs"); if (!File.Exists(ilFile)) { // re-create .il file if necessary CompilerResults output = null; try { output = await Tester.CompileCSharp(csFile, cscOptions).ConfigureAwait(false); await Tester.Disassemble(output.PathToAssembly, ilFile, asmOptions).ConfigureAwait(false); } finally { if (output != null) output.DeleteTempFiles(); } } var executable = await Tester.AssembleIL(ilFile, asmOptions).ConfigureAwait(false); var decompiled = await Tester.DecompileCSharp(executable, decompilerSettings).ConfigureAwait(false); CodeAssert.FilesAreEqual(expectedFile, decompiled, Tester.GetPreprocessorSymbols(cscOptions).ToArray()); Tester.RepeatOnIOError(() => File.Delete(decompiled)); } } }
ILSpy/ICSharpCode.Decompiler.Tests/UglyTestRunner.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/UglyTestRunner.cs", "repo_id": "ILSpy", "token_count": 2199 }
219
// // FormattingOptionsFactory.cs // // Author: // Mike Krüger <[email protected]> // // Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace ICSharpCode.Decompiler.CSharp.OutputVisitor { /// <summary> /// The formatting options factory creates pre defined formatting option styles. /// </summary> public static class FormattingOptionsFactory { /// <summary> /// Creates empty CSharpFormatting options. /// </summary> public static CSharpFormattingOptions CreateEmpty() { return new CSharpFormattingOptions(); } /// <summary> /// Creates mono indent style CSharpFormatting options. /// </summary> public static CSharpFormattingOptions CreateMono() { return new CSharpFormattingOptions { IndentNamespaceBody = true, IndentClassBody = true, IndentInterfaceBody = true, IndentStructBody = true, IndentEnumBody = true, IndentMethodBody = true, IndentPropertyBody = true, IndentEventBody = true, IndentBlocks = true, IndentSwitchBody = false, IndentCaseBody = true, IndentBreakStatements = true, IndentPreprocessorDirectives = true, IndentBlocksInsideExpressions = false, NamespaceBraceStyle = BraceStyle.NextLine, ClassBraceStyle = BraceStyle.NextLine, InterfaceBraceStyle = BraceStyle.NextLine, StructBraceStyle = BraceStyle.NextLine, EnumBraceStyle = BraceStyle.NextLine, MethodBraceStyle = BraceStyle.NextLine, ConstructorBraceStyle = BraceStyle.NextLine, DestructorBraceStyle = BraceStyle.NextLine, AnonymousMethodBraceStyle = BraceStyle.EndOfLine, PropertyBraceStyle = BraceStyle.EndOfLine, PropertyGetBraceStyle = BraceStyle.EndOfLine, PropertySetBraceStyle = BraceStyle.EndOfLine, SimpleGetBlockFormatting = PropertyFormatting.SingleLine, SimpleSetBlockFormatting = PropertyFormatting.SingleLine, EventBraceStyle = BraceStyle.EndOfLine, EventAddBraceStyle = BraceStyle.EndOfLine, EventRemoveBraceStyle = BraceStyle.EndOfLine, AllowEventAddBlockInline = true, AllowEventRemoveBlockInline = true, StatementBraceStyle = BraceStyle.EndOfLine, ElseNewLinePlacement = NewLinePlacement.SameLine, ElseIfNewLinePlacement = NewLinePlacement.SameLine, CatchNewLinePlacement = NewLinePlacement.SameLine, FinallyNewLinePlacement = NewLinePlacement.SameLine, WhileNewLinePlacement = NewLinePlacement.SameLine, ArrayInitializerWrapping = Wrapping.WrapIfTooLong, ArrayInitializerBraceStyle = BraceStyle.EndOfLine, AllowOneLinedArrayInitialziers = true, SpaceBeforeMethodCallParentheses = true, SpaceBeforeMethodDeclarationParentheses = true, SpaceBeforeConstructorDeclarationParentheses = true, SpaceBeforeDelegateDeclarationParentheses = true, SpaceAfterMethodCallParameterComma = true, SpaceAfterConstructorDeclarationParameterComma = true, SpaceBeforeNewParentheses = true, SpacesWithinNewParentheses = false, SpacesBetweenEmptyNewParentheses = false, SpaceBeforeNewParameterComma = false, SpaceAfterNewParameterComma = true, SpaceBeforeIfParentheses = true, SpaceBeforeWhileParentheses = true, SpaceBeforeForParentheses = true, SpaceBeforeForeachParentheses = true, SpaceBeforeCatchParentheses = true, SpaceBeforeSwitchParentheses = true, SpaceBeforeLockParentheses = true, SpaceBeforeUsingParentheses = true, SpaceAroundAssignment = true, SpaceAroundLogicalOperator = true, SpaceAroundEqualityOperator = true, SpaceAroundRelationalOperator = true, SpaceAroundBitwiseOperator = true, SpaceAroundAdditiveOperator = true, SpaceAroundMultiplicativeOperator = true, SpaceAroundShiftOperator = true, SpaceAroundNullCoalescingOperator = true, SpacesWithinParentheses = false, SpaceWithinMethodCallParentheses = false, SpaceWithinMethodDeclarationParentheses = false, SpacesWithinIfParentheses = false, SpacesWithinWhileParentheses = false, SpacesWithinForParentheses = false, SpacesWithinForeachParentheses = false, SpacesWithinCatchParentheses = false, SpacesWithinSwitchParentheses = false, SpacesWithinLockParentheses = false, SpacesWithinUsingParentheses = false, SpacesWithinCastParentheses = false, SpacesWithinSizeOfParentheses = false, SpacesWithinTypeOfParentheses = false, SpacesWithinCheckedExpressionParantheses = false, SpaceBeforeConditionalOperatorCondition = true, SpaceAfterConditionalOperatorCondition = true, SpaceBeforeConditionalOperatorSeparator = true, SpaceAfterConditionalOperatorSeparator = true, SpacesWithinBrackets = false, SpacesBeforeBrackets = true, SpaceBeforeBracketComma = false, SpaceAfterBracketComma = true, SpaceBeforeForSemicolon = false, SpaceAfterForSemicolon = true, SpaceAfterTypecast = false, AlignEmbeddedStatements = true, SimplePropertyFormatting = PropertyFormatting.SingleLine, AutoPropertyFormatting = PropertyFormatting.SingleLine, EmptyLineFormatting = EmptyLineFormatting.DoNotIndent, SpaceBeforeMethodDeclarationParameterComma = false, SpaceAfterMethodDeclarationParameterComma = true, SpaceAfterDelegateDeclarationParameterComma = true, SpaceBeforeFieldDeclarationComma = false, SpaceAfterFieldDeclarationComma = true, SpaceBeforeLocalVariableDeclarationComma = false, SpaceAfterLocalVariableDeclarationComma = true, SpaceBeforeIndexerDeclarationBracket = true, SpaceWithinIndexerDeclarationBracket = false, SpaceBeforeIndexerDeclarationParameterComma = false, SpaceInNamedArgumentAfterDoubleColon = true, RemoveEndOfLineWhiteSpace = true, SpaceAfterIndexerDeclarationParameterComma = true, MinimumBlankLinesBeforeUsings = 0, MinimumBlankLinesAfterUsings = 1, UsingPlacement = UsingPlacement.TopOfFile, MinimumBlankLinesBeforeFirstDeclaration = 0, MinimumBlankLinesBetweenTypes = 1, MinimumBlankLinesBetweenFields = 0, MinimumBlankLinesBetweenEventFields = 0, MinimumBlankLinesBetweenMembers = 1, MinimumBlankLinesAroundRegion = 1, MinimumBlankLinesInsideRegion = 1, AlignToFirstIndexerArgument = false, AlignToFirstIndexerDeclarationParameter = true, AlignToFirstMethodCallArgument = false, AlignToFirstMethodDeclarationParameter = true, KeepCommentsAtFirstColumn = true, ChainedMethodCallWrapping = Wrapping.DoNotWrap, MethodCallArgumentWrapping = Wrapping.DoNotWrap, NewLineAferMethodCallOpenParentheses = NewLinePlacement.DoNotCare, MethodCallClosingParenthesesOnNewLine = NewLinePlacement.DoNotCare, IndexerArgumentWrapping = Wrapping.DoNotWrap, NewLineAferIndexerOpenBracket = NewLinePlacement.DoNotCare, IndexerClosingBracketOnNewLine = NewLinePlacement.DoNotCare, NewLineBeforeNewQueryClause = NewLinePlacement.NewLine }; } /// <summary> /// Creates sharp develop indent style CSharpFormatting options. /// </summary> public static CSharpFormattingOptions CreateSharpDevelop() { var baseOptions = CreateKRStyle(); return baseOptions; } /// <summary> /// The K&amp;R style, so named because it was used in Kernighan and Ritchie's book The C Programming Language, /// is commonly used in C. It is less common for C++, C#, and others. /// </summary> public static CSharpFormattingOptions CreateKRStyle() { return new CSharpFormattingOptions() { IndentNamespaceBody = true, IndentClassBody = true, IndentInterfaceBody = true, IndentStructBody = true, IndentEnumBody = true, IndentMethodBody = true, IndentPropertyBody = true, IndentEventBody = true, IndentBlocks = true, IndentSwitchBody = true, IndentCaseBody = true, IndentBreakStatements = true, IndentPreprocessorDirectives = true, NamespaceBraceStyle = BraceStyle.NextLine, ClassBraceStyle = BraceStyle.NextLine, InterfaceBraceStyle = BraceStyle.NextLine, StructBraceStyle = BraceStyle.NextLine, EnumBraceStyle = BraceStyle.NextLine, MethodBraceStyle = BraceStyle.NextLine, ConstructorBraceStyle = BraceStyle.NextLine, DestructorBraceStyle = BraceStyle.NextLine, AnonymousMethodBraceStyle = BraceStyle.EndOfLine, PropertyBraceStyle = BraceStyle.EndOfLine, PropertyGetBraceStyle = BraceStyle.EndOfLine, PropertySetBraceStyle = BraceStyle.EndOfLine, SimpleGetBlockFormatting = PropertyFormatting.SingleLine, SimpleSetBlockFormatting = PropertyFormatting.SingleLine, EventBraceStyle = BraceStyle.EndOfLine, EventAddBraceStyle = BraceStyle.EndOfLine, EventRemoveBraceStyle = BraceStyle.EndOfLine, AllowEventAddBlockInline = true, AllowEventRemoveBlockInline = true, StatementBraceStyle = BraceStyle.EndOfLine, ElseNewLinePlacement = NewLinePlacement.SameLine, ElseIfNewLinePlacement = NewLinePlacement.SameLine, CatchNewLinePlacement = NewLinePlacement.SameLine, FinallyNewLinePlacement = NewLinePlacement.SameLine, WhileNewLinePlacement = NewLinePlacement.SameLine, ArrayInitializerWrapping = Wrapping.WrapIfTooLong, ArrayInitializerBraceStyle = BraceStyle.EndOfLine, SpaceBeforeMethodCallParentheses = false, SpaceBeforeMethodDeclarationParentheses = false, SpaceBeforeConstructorDeclarationParentheses = false, SpaceBeforeDelegateDeclarationParentheses = false, SpaceBeforeIndexerDeclarationBracket = false, SpaceAfterMethodCallParameterComma = true, SpaceAfterConstructorDeclarationParameterComma = true, NewLineBeforeConstructorInitializerColon = NewLinePlacement.NewLine, NewLineAfterConstructorInitializerColon = NewLinePlacement.SameLine, SpaceBeforeNewParentheses = false, SpacesWithinNewParentheses = false, SpacesBetweenEmptyNewParentheses = false, SpaceBeforeNewParameterComma = false, SpaceAfterNewParameterComma = true, SpaceBeforeIfParentheses = true, SpaceBeforeWhileParentheses = true, SpaceBeforeForParentheses = true, SpaceBeforeForeachParentheses = true, SpaceBeforeCatchParentheses = true, SpaceBeforeSwitchParentheses = true, SpaceBeforeLockParentheses = true, SpaceBeforeUsingParentheses = true, SpaceAroundAssignment = true, SpaceAroundLogicalOperator = true, SpaceAroundEqualityOperator = true, SpaceAroundRelationalOperator = true, SpaceAroundBitwiseOperator = true, SpaceAroundAdditiveOperator = true, SpaceAroundMultiplicativeOperator = true, SpaceAroundShiftOperator = true, SpaceAroundNullCoalescingOperator = true, SpacesWithinParentheses = false, SpaceWithinMethodCallParentheses = false, SpaceWithinMethodDeclarationParentheses = false, SpacesWithinIfParentheses = false, SpacesWithinWhileParentheses = false, SpacesWithinForParentheses = false, SpacesWithinForeachParentheses = false, SpacesWithinCatchParentheses = false, SpacesWithinSwitchParentheses = false, SpacesWithinLockParentheses = false, SpacesWithinUsingParentheses = false, SpacesWithinCastParentheses = false, SpacesWithinSizeOfParentheses = false, SpacesWithinTypeOfParentheses = false, SpacesWithinCheckedExpressionParantheses = false, SpaceBeforeConditionalOperatorCondition = true, SpaceAfterConditionalOperatorCondition = true, SpaceBeforeConditionalOperatorSeparator = true, SpaceAfterConditionalOperatorSeparator = true, SpaceBeforeArrayDeclarationBrackets = false, SpacesWithinBrackets = false, SpacesBeforeBrackets = false, SpaceBeforeBracketComma = false, SpaceAfterBracketComma = true, SpaceBeforeForSemicolon = false, SpaceAfterForSemicolon = true, SpaceAfterTypecast = false, AlignEmbeddedStatements = true, SimplePropertyFormatting = PropertyFormatting.SingleLine, AutoPropertyFormatting = PropertyFormatting.SingleLine, EmptyLineFormatting = EmptyLineFormatting.DoNotIndent, SpaceBeforeMethodDeclarationParameterComma = false, SpaceAfterMethodDeclarationParameterComma = true, SpaceAfterDelegateDeclarationParameterComma = true, SpaceBeforeFieldDeclarationComma = false, SpaceAfterFieldDeclarationComma = true, SpaceBeforeLocalVariableDeclarationComma = false, SpaceAfterLocalVariableDeclarationComma = true, SpaceWithinIndexerDeclarationBracket = false, SpaceBeforeIndexerDeclarationParameterComma = false, SpaceInNamedArgumentAfterDoubleColon = true, SpaceAfterIndexerDeclarationParameterComma = true, RemoveEndOfLineWhiteSpace = true, MinimumBlankLinesBeforeUsings = 0, MinimumBlankLinesAfterUsings = 1, MinimumBlankLinesBeforeFirstDeclaration = 0, MinimumBlankLinesBetweenTypes = 1, MinimumBlankLinesBetweenFields = 0, MinimumBlankLinesBetweenEventFields = 0, MinimumBlankLinesBetweenMembers = 1, MinimumBlankLinesAroundRegion = 1, MinimumBlankLinesInsideRegion = 1, KeepCommentsAtFirstColumn = true, ChainedMethodCallWrapping = Wrapping.DoNotWrap, MethodCallArgumentWrapping = Wrapping.DoNotWrap, NewLineAferMethodCallOpenParentheses = NewLinePlacement.DoNotCare, MethodCallClosingParenthesesOnNewLine = NewLinePlacement.DoNotCare, IndexerArgumentWrapping = Wrapping.DoNotWrap, NewLineAferIndexerOpenBracket = NewLinePlacement.DoNotCare, IndexerClosingBracketOnNewLine = NewLinePlacement.DoNotCare, NewLineBeforeNewQueryClause = NewLinePlacement.NewLine }; } /// <summary> /// Creates allman indent style CSharpFormatting options used in Visual Studio. /// </summary> public static CSharpFormattingOptions CreateAllman() { var baseOptions = CreateKRStyle(); baseOptions.AnonymousMethodBraceStyle = BraceStyle.NextLine; baseOptions.PropertyBraceStyle = BraceStyle.NextLine; baseOptions.PropertyGetBraceStyle = BraceStyle.NextLine; baseOptions.PropertySetBraceStyle = BraceStyle.NextLine; baseOptions.EventBraceStyle = BraceStyle.NextLine; baseOptions.EventAddBraceStyle = BraceStyle.NextLine; baseOptions.EventRemoveBraceStyle = BraceStyle.NextLine; baseOptions.StatementBraceStyle = BraceStyle.NextLine; baseOptions.ArrayInitializerBraceStyle = BraceStyle.NextLine; baseOptions.CatchNewLinePlacement = NewLinePlacement.NewLine; baseOptions.ElseNewLinePlacement = NewLinePlacement.NewLine; baseOptions.ElseIfNewLinePlacement = NewLinePlacement.SameLine; baseOptions.FinallyNewLinePlacement = NewLinePlacement.NewLine; baseOptions.WhileNewLinePlacement = NewLinePlacement.DoNotCare; baseOptions.ArrayInitializerWrapping = Wrapping.DoNotWrap; baseOptions.IndentBlocksInsideExpressions = true; return baseOptions; } /// <summary> /// The Whitesmiths style, also called Wishart style to a lesser extent, is less common today than the previous three. It was originally used in the documentation for the first commercial C compiler, the Whitesmiths Compiler. /// </summary> public static CSharpFormattingOptions CreateWhitesmiths() { var baseOptions = CreateKRStyle(); baseOptions.NamespaceBraceStyle = BraceStyle.NextLineShifted; baseOptions.ClassBraceStyle = BraceStyle.NextLineShifted; baseOptions.InterfaceBraceStyle = BraceStyle.NextLineShifted; baseOptions.StructBraceStyle = BraceStyle.NextLineShifted; baseOptions.EnumBraceStyle = BraceStyle.NextLineShifted; baseOptions.MethodBraceStyle = BraceStyle.NextLineShifted; baseOptions.ConstructorBraceStyle = BraceStyle.NextLineShifted; baseOptions.DestructorBraceStyle = BraceStyle.NextLineShifted; baseOptions.AnonymousMethodBraceStyle = BraceStyle.NextLineShifted; baseOptions.PropertyBraceStyle = BraceStyle.NextLineShifted; baseOptions.PropertyGetBraceStyle = BraceStyle.NextLineShifted; baseOptions.PropertySetBraceStyle = BraceStyle.NextLineShifted; baseOptions.EventBraceStyle = BraceStyle.NextLineShifted; baseOptions.EventAddBraceStyle = BraceStyle.NextLineShifted; baseOptions.EventRemoveBraceStyle = BraceStyle.NextLineShifted; baseOptions.StatementBraceStyle = BraceStyle.NextLineShifted; baseOptions.IndentBlocksInsideExpressions = true; return baseOptions; } /// <summary> /// Like the Allman and Whitesmiths styles, GNU style puts braces on a line by themselves, indented by 2 spaces, /// except when opening a function definition, where they are not indented. /// In either case, the contained code is indented by 2 spaces from the braces. /// Popularised by Richard Stallman, the layout may be influenced by his background of writing Lisp code. /// In Lisp the equivalent to a block (a progn) /// is a first class data entity and giving it its own indent level helps to emphasize that, /// whereas in C a block is just syntax. /// Although not directly related to indentation, GNU coding style also includes a space before the bracketed /// list of arguments to a function. /// </summary> public static CSharpFormattingOptions CreateGNU() { var baseOptions = CreateAllman(); baseOptions.StatementBraceStyle = BraceStyle.NextLineShifted2; return baseOptions; } } }
ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/FormattingOptionsFactory.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/FormattingOptionsFactory.cs", "repo_id": "ILSpy", "token_count": 6085 }
220
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using ICSharpCode.Decompiler.Disassembler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.TypeSystem.Implementation; using static ICSharpCode.Decompiler.Metadata.ILOpCodeExtensions; namespace ICSharpCode.Decompiler.CSharp { class RequiredNamespaceCollector { static readonly Decompiler.TypeSystem.GenericContext genericContext = default; readonly HashSet<string> namespaces; readonly HashSet<IType> visitedTypes = new HashSet<IType>(); public RequiredNamespaceCollector(HashSet<string> namespaces) { this.namespaces = namespaces; for (int i = 0; i < KnownTypeReference.KnownTypeCodeCount; i++) { var ktr = KnownTypeReference.Get((KnownTypeCode)i); if (ktr == null) continue; namespaces.Add(ktr.Namespace); } } public static void CollectNamespaces(MetadataModule module, HashSet<string> namespaces) { var collector = new RequiredNamespaceCollector(namespaces); foreach (var type in module.TypeDefinitions) { collector.CollectNamespaces(type, module, (CodeMappingInfo)null); } collector.HandleAttributes(module.GetAssemblyAttributes()); collector.HandleAttributes(module.GetModuleAttributes()); } public static void CollectAttributeNamespaces(MetadataModule module, HashSet<string> namespaces) { var collector = new RequiredNamespaceCollector(namespaces); collector.HandleAttributes(module.GetAssemblyAttributes()); collector.HandleAttributes(module.GetModuleAttributes()); } public static void CollectNamespaces(IEntity entity, MetadataModule module, HashSet<string> namespaces) { var collector = new RequiredNamespaceCollector(namespaces); collector.CollectNamespaces(entity, module); } void CollectNamespaces(IEntity entity, MetadataModule module, CodeMappingInfo mappingInfo = null) { if (entity == null || entity.MetadataToken.IsNil) return; if (mappingInfo == null) mappingInfo = CSharpDecompiler.GetCodeMappingInfo(entity.ParentModule.PEFile, entity.MetadataToken); switch (entity) { case ITypeDefinition td: namespaces.Add(td.Namespace); HandleAttributes(td.GetAttributes()); HandleTypeParameters(td.TypeParameters); foreach (var baseType in td.DirectBaseTypes) { CollectNamespacesForTypeReference(baseType); } foreach (var nestedType in td.NestedTypes) { CollectNamespaces(nestedType, module, mappingInfo); } foreach (var field in td.Fields) { CollectNamespaces(field, module, mappingInfo); } foreach (var property in td.Properties) { CollectNamespaces(property, module, mappingInfo); } foreach (var @event in td.Events) { CollectNamespaces(@event, module, mappingInfo); } foreach (var method in td.Methods) { CollectNamespaces(method, module, mappingInfo); } break; case IField field: HandleAttributes(field.GetAttributes()); CollectNamespacesForTypeReference(field.ReturnType); break; case IMethod method: var reader = module.PEFile.Reader; var parts = mappingInfo.GetMethodParts((MethodDefinitionHandle)method.MetadataToken).ToList(); foreach (var part in parts) { var partMethod = module.ResolveMethod(part, genericContext); HandleAttributes(partMethod.GetAttributes()); HandleAttributes(partMethod.GetReturnTypeAttributes()); CollectNamespacesForTypeReference(partMethod.ReturnType); foreach (var param in partMethod.Parameters) { HandleAttributes(param.GetAttributes()); CollectNamespacesForTypeReference(param.Type); } HandleTypeParameters(partMethod.TypeParameters); HandleOverrides(part.GetMethodImplementations(module.metadata), module); var methodDef = module.metadata.GetMethodDefinition(part); if (method.HasBody) { MethodBodyBlock body; try { body = reader.GetMethodBody(methodDef.RelativeVirtualAddress); } catch (BadImageFormatException) { continue; } CollectNamespacesFromMethodBody(body, module); } } break; case IProperty property: HandleAttributes(property.GetAttributes()); CollectNamespacesForTypeReference(property.ReturnType); CollectNamespaces(property.Getter, module, mappingInfo); CollectNamespaces(property.Setter, module, mappingInfo); break; case IEvent @event: HandleAttributes(@event.GetAttributes()); CollectNamespacesForTypeReference(@event.ReturnType); CollectNamespaces(@event.AddAccessor, module, mappingInfo); CollectNamespaces(@event.RemoveAccessor, module, mappingInfo); break; } } void HandleOverrides(ImmutableArray<MethodImplementationHandle> immutableArray, MetadataModule module) { foreach (var h in immutableArray) { var methodImpl = module.metadata.GetMethodImplementation(h); CollectNamespacesForTypeReference(module.ResolveType(methodImpl.Type, genericContext)); CollectNamespacesForMemberReference(module.ResolveMethod(methodImpl.MethodBody, genericContext)); CollectNamespacesForMemberReference(module.ResolveMethod(methodImpl.MethodDeclaration, genericContext)); } } void CollectNamespacesForTypeReference(IType type) { if (!visitedTypes.Add(type)) return; switch (type) { case ParameterizedType parameterizedType: namespaces.Add(parameterizedType.Namespace); CollectNamespacesForTypeReference(parameterizedType.GenericType); foreach (var arg in parameterizedType.TypeArguments) CollectNamespacesForTypeReference(arg); return; // no need to collect base types again case TypeWithElementType typeWithElementType: CollectNamespacesForTypeReference(typeWithElementType.ElementType); break; case TupleType tupleType: foreach (var elementType in tupleType.ElementTypes) { CollectNamespacesForTypeReference(elementType); } break; case FunctionPointerType fnPtrType: CollectNamespacesForTypeReference(fnPtrType.ReturnType); foreach (var paramType in fnPtrType.ParameterTypes) { CollectNamespacesForTypeReference(paramType); } break; default: namespaces.Add(type.Namespace); break; } foreach (var baseType in type.GetAllBaseTypes()) { namespaces.Add(baseType.Namespace); } } public static void CollectNamespaces(EntityHandle entity, MetadataModule module, HashSet<string> namespaces) { if (entity.IsNil) return; CollectNamespaces(module.ResolveEntity(entity, genericContext), module, namespaces); } void HandleAttributes(IEnumerable<IAttribute> attributes) { foreach (var attr in attributes) { namespaces.Add(attr.AttributeType.Namespace); foreach (var arg in attr.FixedArguments) { HandleAttributeValue(arg.Type, arg.Value); } foreach (var arg in attr.NamedArguments) { HandleAttributeValue(arg.Type, arg.Value); } } } void HandleAttributeValue(IType type, object value) { CollectNamespacesForTypeReference(type); if (value is IType typeofType) CollectNamespacesForTypeReference(typeofType); if (value is ImmutableArray<CustomAttributeTypedArgument<IType>> arr) { foreach (var element in arr) { HandleAttributeValue(element.Type, element.Value); } } } void HandleTypeParameters(IEnumerable<ITypeParameter> typeParameters) { foreach (var typeParam in typeParameters) { HandleAttributes(typeParam.GetAttributes()); foreach (var constraint in typeParam.DirectBaseTypes) { CollectNamespacesForTypeReference(constraint); } } } void CollectNamespacesFromMethodBody(MethodBodyBlock method, MetadataModule module) { var metadata = module.metadata; var instructions = method.GetILReader(); if (!method.LocalSignature.IsNil) { ImmutableArray<IType> localSignature; try { localSignature = module.DecodeLocalSignature(method.LocalSignature, genericContext); } catch (BadImageFormatException) { // Issue #1211: ignore invalid local signatures localSignature = ImmutableArray<IType>.Empty; } foreach (var type in localSignature) CollectNamespacesForTypeReference(type); } foreach (var region in method.ExceptionRegions) { if (region.CatchType.IsNil) continue; IType ty; try { ty = module.ResolveType(region.CatchType, genericContext); } catch (BadImageFormatException) { continue; } CollectNamespacesForTypeReference(ty); } while (instructions.RemainingBytes > 0) { ILOpCode opCode; try { opCode = instructions.DecodeOpCode(); } catch (BadImageFormatException) { return; } switch (opCode.GetOperandType()) { case OperandType.Field: case OperandType.Method: case OperandType.Sig: case OperandType.Tok: case OperandType.Type: EntityHandle handle; try { handle = MetadataTokenHelpers.EntityHandleOrNil(instructions.ReadInt32()); } catch (BadImageFormatException) { return; } if (handle.IsNil) break; switch (handle.Kind) { case HandleKind.TypeDefinition: case HandleKind.TypeReference: case HandleKind.TypeSpecification: IType type; try { type = module.ResolveType(handle, genericContext); } catch (BadImageFormatException) { break; } CollectNamespacesForTypeReference(type); break; case HandleKind.FieldDefinition: case HandleKind.MethodDefinition: case HandleKind.MethodSpecification: case HandleKind.MemberReference: IMember member; try { member = module.ResolveEntity(handle, genericContext) as IMember; } catch (BadImageFormatException) { break; } CollectNamespacesForMemberReference(member); break; case HandleKind.StandaloneSignature: StandaloneSignature sig; try { sig = metadata.GetStandaloneSignature((StandaloneSignatureHandle)handle); } catch (BadImageFormatException) { break; } if (sig.GetKind() == StandaloneSignatureKind.Method) { FunctionPointerType fpt; try { (_, fpt) = module.DecodeMethodSignature((StandaloneSignatureHandle)handle, genericContext); } catch (BadImageFormatException) { break; } CollectNamespacesForTypeReference(fpt); } break; } break; default: try { instructions.SkipOperand(opCode); } catch (BadImageFormatException) { return; } break; } } } void CollectNamespacesForMemberReference(IMember member) { switch (member) { case IField field: CollectNamespacesForTypeReference(field.DeclaringType); CollectNamespacesForTypeReference(field.ReturnType); break; case IMethod method: CollectNamespacesForTypeReference(method.DeclaringType); CollectNamespacesForTypeReference(method.ReturnType); foreach (var param in method.Parameters) CollectNamespacesForTypeReference(param.Type); foreach (var arg in method.TypeArguments) CollectNamespacesForTypeReference(arg); break; } } } }
ILSpy/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs", "repo_id": "ILSpy", "token_count": 4722 }
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; namespace ICSharpCode.Decompiler.CSharp.Resolver { [Flags] public enum OverloadResolutionErrors { None = 0, /// <summary> /// Too many positional arguments (some could not be mapped to any parameter). /// </summary> TooManyPositionalArguments = 0x0001, /// <summary> /// A named argument could not be mapped to any parameter /// </summary> NoParameterFoundForNamedArgument = 0x0002, /// <summary> /// Type inference failed for a generic method. /// </summary> TypeInferenceFailed = 0x0004, /// <summary> /// Type arguments were explicitly specified, but did not match the number of type parameters. /// </summary> WrongNumberOfTypeArguments = 0x0008, /// <summary> /// After substituting type parameters with the inferred types; a constructed type within the formal parameters /// does not satisfy its constraint. /// </summary> ConstructedTypeDoesNotSatisfyConstraint = 0x0010, /// <summary> /// No argument was mapped to a non-optional parameter /// </summary> MissingArgumentForRequiredParameter = 0x0020, /// <summary> /// Several arguments were mapped to a single (non-params-array) parameter /// </summary> MultipleArgumentsForSingleParameter = 0x0040, /// <summary> /// 'ref'/'out' passing mode doesn't match for at least 1 parameter /// </summary> ParameterPassingModeMismatch = 0x0080, /// <summary> /// Argument type cannot be converted to parameter type /// </summary> ArgumentTypeMismatch = 0x0100, /// <summary> /// There is no unique best overload. /// This error does not apply to any single candidate, but only to the overall result of overload resolution. /// </summary> /// <remarks> /// This error does not prevent a candidate from being applicable. /// </remarks> AmbiguousMatch = 0x0200, /// <summary> /// The member is not accessible. /// </summary> /// <remarks> /// This error is generated by member lookup; not by overload resolution. /// </remarks> Inaccessible = 0x0400, /// <summary> /// A generic method /// </summary> /// <remarks> /// This error does not prevent a candidate from being applicable. /// </remarks> MethodConstraintsNotSatisfied = 0x0800, /// <summary> /// Using 'out var' instead of 'out T' would result in loss of type information. /// </summary> OutVarTypeMismatch = 0x1000, } }
ILSpy/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolutionErrors.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolutionErrors.cs", "repo_id": "ILSpy", "token_count": 1051 }
222
// // ThisReferenceExpression.cs // // Author: // Mike Krüger <[email protected]> // // 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> /// this /// </summary> public class ThisReferenceExpression : Expression { public TextLocation Location { get; set; } public override TextLocation StartLocation { get { return Location; } } public override TextLocation EndLocation { get { return new TextLocation(Location.Line, Location.Column + "this".Length); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitThisReferenceExpression(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitThisReferenceExpression(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitThisReferenceExpression(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { ThisReferenceExpression o = other as ThisReferenceExpression; return o != null; } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs", "repo_id": "ILSpy", "token_count": 695 }
223
// // NamespaceDeclaration.cs // // Author: // Mike Krüger <[email protected]> // // Copyright (c) 2009 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; namespace ICSharpCode.Decompiler.CSharp.Syntax { /// <summary> /// namespace Name { Members } /// </summary> public class NamespaceDeclaration : AstNode { public static readonly Role<AstNode> MemberRole = SyntaxTree.MemberRole; public static readonly Role<AstType> NamespaceNameRole = new Role<AstType>("NamespaceName", AstType.Null); public override NodeType NodeType { get { return NodeType.Unknown; } } public bool IsFileScoped { get; set; } public CSharpTokenNode NamespaceToken { get { return GetChildByRole(Roles.NamespaceKeyword); } } public AstType NamespaceName { get { return GetChildByRole(NamespaceNameRole) ?? AstType.Null; } set { SetChildByRole(NamespaceNameRole, value); } } public string Name { get { return UsingDeclaration.ConstructNamespace(NamespaceName); } set { var arr = value.Split('.'); NamespaceName = ConstructType(arr, arr.Length - 1); } } static AstType ConstructType(string[] arr, int i) { if (i < 0 || i >= arr.Length) throw new ArgumentOutOfRangeException(nameof(i)); if (i == 0) return new SimpleType(arr[i]); return new MemberType(ConstructType(arr, i - 1), arr[i]); } /// <summary> /// Gets the full namespace name (including any parent namespaces) /// </summary> public string FullName { get { NamespaceDeclaration parentNamespace = Parent as NamespaceDeclaration; if (parentNamespace != null) return BuildQualifiedName(parentNamespace.FullName, Name); return Name; } } public IEnumerable<string> Identifiers { get { var result = new Stack<string>(); AstType type = NamespaceName; while (type is MemberType) { var mt = (MemberType)type; result.Push(mt.MemberName); type = mt.Target; } if (type is SimpleType) result.Push(((SimpleType)type).Identifier); return result; } } public CSharpTokenNode LBraceToken { get { return GetChildByRole(Roles.LBrace); } } public AstNodeCollection<AstNode> Members { get { return GetChildrenByRole(MemberRole); } } public CSharpTokenNode RBraceToken { get { return GetChildByRole(Roles.RBrace); } } public NamespaceDeclaration() { } public NamespaceDeclaration(string name) { this.Name = name; } public static string BuildQualifiedName(string name1, string name2) { if (string.IsNullOrEmpty(name1)) return name2; if (string.IsNullOrEmpty(name2)) return name1; return name1 + "." + name2; } public void AddMember(AstNode child) { AddChild(child, MemberRole); } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitNamespaceDeclaration(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitNamespaceDeclaration(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitNamespaceDeclaration(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { NamespaceDeclaration o = other as NamespaceDeclaration; return o != null && MatchString(this.Name, o.Name) && this.Members.DoMatch(o.Members, match); } } };
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs", "repo_id": "ILSpy", "token_count": 1574 }
224
// // TryCatchStatement.cs // // Author: // Mike Krüger <[email protected]> // // 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> /// try TryBlock CatchClauses finally FinallyBlock /// </summary> public class TryCatchStatement : Statement { public static readonly TokenRole TryKeywordRole = new TokenRole("try"); public static readonly Role<BlockStatement> TryBlockRole = new Role<BlockStatement>("TryBlock", BlockStatement.Null); public static readonly Role<CatchClause> CatchClauseRole = new Role<CatchClause>("CatchClause", CatchClause.Null); public static readonly TokenRole FinallyKeywordRole = new TokenRole("finally"); public static readonly Role<BlockStatement> FinallyBlockRole = new Role<BlockStatement>("FinallyBlock", BlockStatement.Null); public CSharpTokenNode TryToken { get { return GetChildByRole(TryKeywordRole); } } public BlockStatement TryBlock { get { return GetChildByRole(TryBlockRole); } set { SetChildByRole(TryBlockRole, value); } } public AstNodeCollection<CatchClause> CatchClauses { get { return GetChildrenByRole(CatchClauseRole); } } public CSharpTokenNode FinallyToken { get { return GetChildByRole(FinallyKeywordRole); } } public BlockStatement FinallyBlock { get { return GetChildByRole(FinallyBlockRole); } set { SetChildByRole(FinallyBlockRole, value); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitTryCatchStatement(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitTryCatchStatement(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitTryCatchStatement(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { TryCatchStatement o = other as TryCatchStatement; return o != null && this.TryBlock.DoMatch(o.TryBlock, match) && this.CatchClauses.DoMatch(o.CatchClauses, match) && this.FinallyBlock.DoMatch(o.FinallyBlock, match); } } /// <summary> /// catch (Type VariableName) { Body } /// </summary> public class CatchClause : AstNode { public static readonly TokenRole CatchKeywordRole = new TokenRole("catch"); public static readonly TokenRole WhenKeywordRole = new TokenRole("when"); public static readonly Role<Expression> ConditionRole = Roles.Condition; public static readonly TokenRole CondLPar = new TokenRole("("); public static readonly TokenRole CondRPar = new TokenRole(")"); #region Null public new static readonly CatchClause Null = new NullCatchClause(); sealed class NullCatchClause : CatchClause { 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 CatchClause(PatternMatching.Pattern pattern) { return pattern != null ? new PatternPlaceholder(pattern) : null; } sealed class PatternPlaceholder : CatchClause, 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 CatchToken { get { return GetChildByRole(CatchKeywordRole); } } public CSharpTokenNode LParToken { get { return GetChildByRole(Roles.LPar); } } public AstType Type { get { return GetChildByRole(Roles.Type); } set { SetChildByRole(Roles.Type, value); } } public string VariableName { get { return GetChildByRole(Roles.Identifier).Name; } set { if (string.IsNullOrEmpty(value)) SetChildByRole(Roles.Identifier, null); else SetChildByRole(Roles.Identifier, Identifier.Create(value)); } } public Identifier VariableNameToken { get { return GetChildByRole(Roles.Identifier); } set { SetChildByRole(Roles.Identifier, value); } } public CSharpTokenNode RParToken { get { return GetChildByRole(Roles.RPar); } } public CSharpTokenNode WhenToken { get { return GetChildByRole(WhenKeywordRole); } } public CSharpTokenNode CondLParToken { get { return GetChildByRole(CondLPar); } } public Expression Condition { get { return GetChildByRole(ConditionRole); } set { SetChildByRole(ConditionRole, value); } } public CSharpTokenNode CondRParToken { get { return GetChildByRole(CondRPar); } } public BlockStatement Body { get { return GetChildByRole(Roles.Body); } set { SetChildByRole(Roles.Body, value); } } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitCatchClause(this); } public override T AcceptVisitor<T>(IAstVisitor<T> visitor) { return visitor.VisitCatchClause(this); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitCatchClause(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { CatchClause o = other as CatchClause; return o != null && this.Type.DoMatch(o.Type, match) && MatchString(this.VariableName, o.VariableName) && this.Body.DoMatch(o.Body, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs", "repo_id": "ILSpy", "token_count": 2646 }
225
// 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.Linq; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.CSharp.Syntax { public abstract class EntityDeclaration : AstNode { public static readonly Role<AttributeSection> AttributeRole = new Role<AttributeSection>("Attribute", null); public static readonly Role<CSharpModifierToken> ModifierRole = new Role<CSharpModifierToken>("Modifier", null); public static readonly Role<AstType> PrivateImplementationTypeRole = new Role<AstType>("PrivateImplementationType", AstType.Null); public override NodeType NodeType { get { return NodeType.Member; } } public abstract SymbolKind SymbolKind { get; } public AstNodeCollection<AttributeSection> Attributes { get { return base.GetChildrenByRole(AttributeRole); } } public Modifiers Modifiers { get { return GetModifiers(this); } set { SetModifiers(this, value); } } public bool HasModifier(Modifiers mod) { return (Modifiers & mod) == mod; } public IEnumerable<CSharpModifierToken> ModifierTokens { get { return GetChildrenByRole(ModifierRole); } } public virtual string Name { get { return GetChildByRole(Roles.Identifier).Name; } set { SetChildByRole(Roles.Identifier, Identifier.Create(value, TextLocation.Empty)); } } public virtual Identifier NameToken { get { return GetChildByRole(Roles.Identifier); } set { SetChildByRole(Roles.Identifier, value); } } public virtual AstType ReturnType { get { return GetChildByRole(Roles.Type); } set { SetChildByRole(Roles.Type, value); } } public CSharpTokenNode SemicolonToken { get { return GetChildByRole(Roles.Semicolon); } } internal static Modifiers GetModifiers(AstNode node) { Modifiers m = 0; foreach (CSharpModifierToken t in node.GetChildrenByRole(ModifierRole)) { m |= t.Modifier; } return m; } internal static void SetModifiers(AstNode node, Modifiers newValue) { Modifiers oldValue = GetModifiers(node); AstNode insertionPos = node.GetChildrenByRole(AttributeRole).LastOrDefault(); foreach (Modifiers m in CSharpModifierToken.AllModifiers) { if ((m & newValue) != 0) { if ((m & oldValue) == 0) { // Modifier was added var newToken = new CSharpModifierToken(TextLocation.Empty, m); node.InsertChildAfter(insertionPos, newToken, ModifierRole); insertionPos = newToken; } else { // Modifier already exists insertionPos = node.GetChildrenByRole(ModifierRole).First(t => t.Modifier == m); } } else { if ((m & oldValue) != 0) { // Modifier was removed node.GetChildrenByRole(ModifierRole).First(t => t.Modifier == m).Remove(); } } } } protected bool MatchAttributesAndModifiers(EntityDeclaration o, PatternMatching.Match match) { return (this.Modifiers == Modifiers.Any || this.Modifiers == o.Modifiers) && this.Attributes.DoMatch(o.Attributes, match); } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs", "repo_id": "ILSpy", "token_count": 1415 }
226
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching; namespace ICSharpCode.Decompiler.CSharp.Transforms { /// <summary> /// Combines query expressions and removes transparent identifiers. /// </summary> public class CombineQueryExpressions : IAstTransform { public void Run(AstNode rootNode, TransformContext context) { if (!context.Settings.QueryExpressions) return; CombineQueries(rootNode, new Dictionary<string, object>()); } static readonly InvocationExpression castPattern = new InvocationExpression { Target = new MemberReferenceExpression { Target = new AnyNode("inExpr"), MemberName = "Cast", TypeArguments = { new AnyNode("targetType") } } }; void CombineQueries(AstNode node, Dictionary<string, object> fromOrLetIdentifiers) { AstNode next; for (AstNode child = node.FirstChild; child != null; child = next) { // store reference to next child before transformation next = child.NextSibling; CombineQueries(child, fromOrLetIdentifiers); } QueryExpression query = node as QueryExpression; if (query != null) { QueryFromClause fromClause = (QueryFromClause)query.Clauses.First(); QueryExpression innerQuery = fromClause.Expression as QueryExpression; if (innerQuery != null) { if (TryRemoveTransparentIdentifier(query, fromClause, innerQuery, fromOrLetIdentifiers)) { RemoveTransparentIdentifierReferences(query, fromOrLetIdentifiers); } else { QueryContinuationClause continuation = new QueryContinuationClause(); continuation.PrecedingQuery = innerQuery.Detach(); continuation.Identifier = fromClause.Identifier; continuation.CopyAnnotationsFrom(fromClause); fromClause.ReplaceWith(continuation); } } else { Match m = castPattern.Match(fromClause.Expression); if (m.Success) { fromClause.Type = m.Get<AstType>("targetType").Single().Detach(); fromClause.Expression = m.Get<Expression>("inExpr").Single().Detach(); } } } } static readonly QuerySelectClause selectTransparentIdentifierPattern = new QuerySelectClause { Expression = new AnonymousTypeCreateExpression { Initializers = { new Repeat( new Choice { new IdentifierExpression(Pattern.AnyString).WithName("expr"), // name is equivalent to name = name new MemberReferenceExpression(new AnyNode(), Pattern.AnyString).WithName("expr"), // expr.name is equivalent to name = expr.name new NamedExpression { Name = Pattern.AnyString, Expression = new AnyNode() }.WithName("expr") } ) { MinCount = 1 } } } }; bool TryRemoveTransparentIdentifier(QueryExpression query, QueryFromClause fromClause, QueryExpression innerQuery, Dictionary<string, object> letClauses) { if (!CSharpDecompiler.IsTransparentIdentifier(fromClause.Identifier)) return false; QuerySelectClause selectClause = innerQuery.Clauses.Last() as QuerySelectClause; Match match = selectTransparentIdentifierPattern.Match(selectClause); if (!match.Success) return false; // from * in (from x in ... select new { members of anonymous type }) ... // => // from x in ... { let x = ... } ... fromClause.Remove(); selectClause.Remove(); // Move clauses from innerQuery to query QueryClause insertionPos = null; foreach (var clause in innerQuery.Clauses) { query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach()); } foreach (var expr in match.Get<Expression>("expr")) { switch (expr) { case IdentifierExpression identifier: letClauses[identifier.Identifier] = identifier.Annotation<ILVariableResolveResult>(); break; case MemberReferenceExpression member: AddQueryLetClause(member.MemberName, member); break; case NamedExpression namedExpression: if (namedExpression.Expression is IdentifierExpression identifierExpression && namedExpression.Name == identifierExpression.Identifier) { letClauses[namedExpression.Name] = identifierExpression.Annotation<ILVariableResolveResult>(); continue; } AddQueryLetClause(namedExpression.Name, namedExpression.Expression); break; } } return true; void AddQueryLetClause(string name, Expression expression) { QueryLetClause letClause = new QueryLetClause { Identifier = name, Expression = expression.Detach() }; var annotation = new LetIdentifierAnnotation(); letClause.AddAnnotation(annotation); letClauses[name] = annotation; query.Clauses.InsertAfter(insertionPos, letClause); } } /// <summary> /// Removes all occurrences of transparent identifiers /// </summary> void RemoveTransparentIdentifierReferences(AstNode node, Dictionary<string, object> fromOrLetIdentifiers) { foreach (AstNode child in node.Children) { RemoveTransparentIdentifierReferences(child, fromOrLetIdentifiers); } MemberReferenceExpression mre = node as MemberReferenceExpression; if (mre != null) { IdentifierExpression ident = mre.Target as IdentifierExpression; if (ident != null && CSharpDecompiler.IsTransparentIdentifier(ident.Identifier)) { IdentifierExpression newIdent = new IdentifierExpression(mre.MemberName); mre.TypeArguments.MoveTo(newIdent.TypeArguments); newIdent.CopyAnnotationsFrom(mre); newIdent.RemoveAnnotations<Semantics.MemberResolveResult>(); // remove the reference to the property of the anonymous type if (fromOrLetIdentifiers.TryGetValue(mre.MemberName, out var annotation)) newIdent.AddAnnotation(annotation); mre.ReplaceWith(newIdent); return; } } } } public class LetIdentifierAnnotation { } }
ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs", "repo_id": "ILSpy", "token_count": 2421 }
227
// Copyright (c) 2017 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.Semantics; namespace ICSharpCode.Decompiler.CSharp.Transforms { /// <summary> /// This transform is used to remove CLSCompliant attributes added by the compiler. We remove them in order to get rid of many warnings. /// </summary> /// <remarks>This transform is only enabled, when exporting a full assembly as project.</remarks> public class RemoveCLSCompliantAttribute : IAstTransform { public void Run(AstNode rootNode, TransformContext context) { foreach (var section in rootNode.Children.OfType<AttributeSection>()) { if (section.AttributeTarget == "assembly") continue; foreach (var attribute in section.Attributes) { var trr = attribute.Type.Annotation<TypeResolveResult>(); if (trr != null && trr.Type.FullName == "System.CLSCompliantAttribute") attribute.Remove(); } if (section.Attributes.Count == 0) section.Remove(); } } } }
ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/RemoveCLSCompliantAttribute.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/RemoveCLSCompliantAttribute.cs", "repo_id": "ILSpy", "token_count": 654 }
228
using System; using System.Collections.Generic; using System.Reflection.Metadata; using System.Text; namespace ICSharpCode.Decompiler.DebugInfo { public struct Variable { public Variable(int index, string name) { Index = index; Name = name; } public int Index { get; } public string Name { get; } } public struct PdbExtraTypeInfo { public string[] TupleElementNames; public bool[] DynamicFlags; } public interface IDebugInfoProvider { string Description { get; } IList<SequencePoint> GetSequencePoints(MethodDefinitionHandle method); IList<Variable> GetVariables(MethodDefinitionHandle method); bool TryGetName(MethodDefinitionHandle method, int index, out string name); bool TryGetExtraTypeInfo(MethodDefinitionHandle method, int index, out PdbExtraTypeInfo extraTypeInfo); string SourceFileName { get; } } }
ILSpy/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs", "repo_id": "ILSpy", "token_count": 272 }
229
// 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.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using ICSharpCode.Decompiler.Metadata; namespace ICSharpCode.Decompiler.Disassembler { public struct OpCodeInfo : IEquatable<OpCodeInfo> { public readonly ILOpCode Code; public readonly string Name; string encodedName; public OpCodeInfo(ILOpCode code, string name) { this.Code = code; this.Name = name ?? ""; this.encodedName = null; } public bool Equals(OpCodeInfo other) { return other.Code == this.Code && other.Name == this.Name; } public static bool operator ==(OpCodeInfo lhs, OpCodeInfo rhs) => lhs.Equals(rhs); public static bool operator !=(OpCodeInfo lhs, OpCodeInfo rhs) => !(lhs == rhs); public override bool Equals(object obj) { if (obj is OpCodeInfo opCode) return Equals(opCode); return false; } public override int GetHashCode() { return unchecked(982451629 * Code.GetHashCode() + 982451653 * Name.GetHashCode()); } public string Link => "https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes." + EncodedName.ToLowerInvariant(); public string EncodedName { get { if (encodedName != null) return encodedName; switch (Name) { case "constrained.": encodedName = "Constrained"; return encodedName; case "no.": encodedName = "No"; return encodedName; case "readonly.": encodedName = "Reaonly"; return encodedName; case "tail.": encodedName = "Tailcall"; return encodedName; case "unaligned.": encodedName = "Unaligned"; return encodedName; case "volatile.": encodedName = "Volatile"; return encodedName; } string text = ""; bool toUpperCase = true; foreach (var ch in Name) { if (ch == '.') { text += '_'; toUpperCase = true; } else if (toUpperCase) { text += char.ToUpperInvariant(ch); toUpperCase = false; } else { text += ch; } } encodedName = text; return encodedName; } } } }
ILSpy/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs", "repo_id": "ILSpy", "token_count": 1235 }
230
using System.Collections.Generic; using System.Text.RegularExpressions; namespace Humanizer.Inflections { /// <summary> /// A container for exceptions to simple pluralization/singularization rules. /// Vocabularies.Default contains an extensive list of rules for US English. /// At this time, multiple vocabularies and removing existing rules are not supported. /// </summary> internal class Vocabulary { internal Vocabulary() { } private readonly List<Rule> _plurals = new List<Rule>(); private readonly List<Rule> _singulars = new List<Rule>(); private readonly List<string> _uncountables = new List<string>(); /// <summary> /// Adds a word to the vocabulary which cannot easily be pluralized/singularized by RegEx, e.g. "person" and "people". /// </summary> /// <param name="singular">The singular form of the irregular word, e.g. "person".</param> /// <param name="plural">The plural form of the irregular word, e.g. "people".</param> /// <param name="matchEnding">True to match these words on their own as well as at the end of longer words. False, otherwise.</param> public void AddIrregular(string singular, string plural, bool matchEnding = true) { if (matchEnding) { AddPlural("(" + singular[0] + ")" + singular.Substring(1) + "$", "$1" + plural.Substring(1)); AddSingular("(" + plural[0] + ")" + plural.Substring(1) + "$", "$1" + singular.Substring(1)); } else { AddPlural($"^{singular}$", plural); AddSingular($"^{plural}$", singular); } } /// <summary> /// Adds an uncountable word to the vocabulary, e.g. "fish". Will be ignored when plurality is changed. /// </summary> /// <param name="word">Word to be added to the list of uncountables.</param> public void AddUncountable(string word) { _uncountables.Add(word.ToLower()); } /// <summary> /// Adds a rule to the vocabulary that does not follow trivial rules for pluralization, e.g. "bus" -> "buses" /// </summary> /// <param name="rule">RegEx to be matched, case insensitive, e.g. "(bus)es$"</param> /// <param name="replacement">RegEx replacement e.g. "$1"</param> public void AddPlural(string rule, string replacement) { _plurals.Add(new Rule(rule, replacement)); } /// <summary> /// Adds a rule to the vocabulary that does not follow trivial rules for singularization, e.g. "vertices/indices -> "vertex/index" /// </summary> /// <param name="rule">RegEx to be matched, case insensitive, e.g. ""(vert|ind)ices$""</param> /// <param name="replacement">RegEx replacement e.g. "$1ex"</param> public void AddSingular(string rule, string replacement) { _singulars.Add(new Rule(rule, replacement)); } /// <summary> /// Pluralizes the provided input considering irregular words /// </summary> /// <param name="word">Word to be pluralized</param> /// <param name="inputIsKnownToBeSingular">Normally you call Pluralize on singular words; but if you're unsure call it with false</param> /// <returns></returns> public string Pluralize(string word, bool inputIsKnownToBeSingular = true) { var result = ApplyRules(_plurals, word, false); if (inputIsKnownToBeSingular) { return result ?? word; } var asSingular = ApplyRules(_singulars, word, false); var asSingularAsPlural = ApplyRules(_plurals, asSingular, false); if (asSingular != null && asSingular != word && asSingular + "s" != word && asSingularAsPlural == word && result != word) { return word; } return result; } /// <summary> /// Singularizes the provided input considering irregular words /// </summary> /// <param name="word">Word to be singularized</param> /// <param name="inputIsKnownToBePlural">Normally you call Singularize on plural words; but if you're unsure call it with false</param> /// <param name="skipSimpleWords">Skip singularizing single words that have an 's' on the end</param> /// <returns></returns> public string Singularize(string word, bool inputIsKnownToBePlural = true, bool skipSimpleWords = false) { var result = ApplyRules(_singulars, word, skipSimpleWords); if (inputIsKnownToBePlural) { return result ?? word; } // the Plurality is unknown so we should check all possibilities var asPlural = ApplyRules(_plurals, word, false); var asPluralAsSingular = ApplyRules(_singulars, asPlural, false); if (asPlural != word && word + "s" != asPlural && asPluralAsSingular == word && result != word) { return word; } return result ?? word; } private string ApplyRules(IList<Rule> rules, string word, bool skipFirstRule) { if (word == null) { return null; } if (word.Length < 1) { return word; } if (IsUncountable(word)) { return word; } var result = word; var end = skipFirstRule ? 1 : 0; for (var i = rules.Count - 1; i >= end; i--) { if ((result = rules[i].Apply(word)) != null) { break; } } return result; } private bool IsUncountable(string word) { return _uncountables.Contains(word.ToLower()); } private class Rule { private readonly Regex _regex; private readonly string _replacement; public Rule(string pattern, string replacement) { _regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); _replacement = replacement; } public string Apply(string word) { if (!_regex.IsMatch(word)) { return null; } return _regex.Replace(word, _replacement); } } } }
ILSpy/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs", "repo_id": "ILSpy", "token_count": 1987 }
231
// Copyright (c) 2012 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 System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.IL.ControlFlow { enum StateRangeAnalysisMode { IteratorMoveNext, IteratorDispose, AsyncMoveNext, AwaitInFinally } /// <summary> /// Symbolically executes code to determine which blocks are reachable for which values /// of the 'state' field. /// </summary> /// <remarks> /// Assumption: there are no loops/backward jumps /// We 'run' the code, with "state" being a symbolic variable /// so it can form expressions like "state + x" (when there's a sub instruction) /// /// For each block, we maintain the set of values for state for which the block is reachable. /// This is (int.MinValue, int.MaxValue) for the first instruction. /// These ranges are propagated depending on the conditional jumps performed by the code. /// </remarks> class StateRangeAnalysis { public CancellationToken CancellationToken; readonly StateRangeAnalysisMode mode; readonly IField? stateField; readonly bool legacyVisualBasic; readonly SymbolicEvaluationContext evalContext; readonly Dictionary<Block, LongSet> ranges = new Dictionary<Block, LongSet>(); readonly Dictionary<BlockContainer, LongSet>? rangesForLeave; // used only for AwaitInFinally readonly internal Dictionary<IMethod, LongSet>? finallyMethodToStateRange; // used only for IteratorDispose internal ILVariable? doFinallyBodies; internal ILVariable? skipFinallyBodies; public StateRangeAnalysis(StateRangeAnalysisMode mode, IField? stateField, ILVariable? cachedStateVar = null, bool legacyVisualBasic = false) { this.mode = mode; this.stateField = stateField; this.legacyVisualBasic = legacyVisualBasic; if (mode == StateRangeAnalysisMode.IteratorDispose) { finallyMethodToStateRange = new Dictionary<IMethod, LongSet>(); } if (mode == StateRangeAnalysisMode.AwaitInFinally) { rangesForLeave = new Dictionary<BlockContainer, LongSet>(); } evalContext = new SymbolicEvaluationContext(stateField, legacyVisualBasic); if (cachedStateVar != null) evalContext.AddStateVariable(cachedStateVar); } public IEnumerable<ILVariable> CachedStateVars { get => evalContext.StateVariables; } /// <summary> /// Creates a new StateRangeAnalysis with the same settings, including any cached state vars /// discovered by this analysis. /// However, the new analysis has a fresh set of result ranges. /// </summary> internal StateRangeAnalysis CreateNestedAnalysis() { var sra = new StateRangeAnalysis(mode, stateField, legacyVisualBasic: legacyVisualBasic); sra.doFinallyBodies = this.doFinallyBodies; sra.skipFinallyBodies = this.skipFinallyBodies; foreach (var v in this.evalContext.StateVariables) { sra.evalContext.AddStateVariable(v); } return sra; } /// <summary> /// Assign state ranges for all blocks within 'inst'. /// </summary> /// <returns> /// The set of states for which the exit point of the instruction is reached. /// This must be a subset of the input set. /// /// Returns an empty set for unsupported instructions. /// </returns> public LongSet AssignStateRanges(ILInstruction inst, LongSet stateRange) { CancellationToken.ThrowIfCancellationRequested(); switch (inst) { case BlockContainer blockContainer: AddStateRange(blockContainer.EntryPoint, stateRange); foreach (var block in blockContainer.Blocks) { // We assume that there are no jumps to blocks already processed. // TODO: is SortBlocks() guaranteeing this, even if the user code has loops? if (ranges.TryGetValue(block, out stateRange)) { AssignStateRanges(block, stateRange); } } // Since we don't track 'leave' edges, we can only conservatively // return LongSet.Empty. return LongSet.Empty; case Block block: foreach (var instInBlock in block.Instructions) { if (stateRange.IsEmpty) break; var oldStateRange = stateRange; stateRange = AssignStateRanges(instInBlock, stateRange); // End-point can only be reachable in a subset of the states where the start-point is reachable. Debug.Assert(stateRange.IsSubsetOf(oldStateRange)); // If the end-point is unreachable, it must be reachable in no states. Debug.Assert(stateRange.IsEmpty || !instInBlock.HasFlag(InstructionFlags.EndPointUnreachable)); } return stateRange; case TryFinally tryFinally when mode == StateRangeAnalysisMode.IteratorDispose: var afterTry = AssignStateRanges(tryFinally.TryBlock, stateRange); // really finally should start with 'stateRange.UnionWith(afterTry)', but that's // equal to 'stateRange'. Debug.Assert(afterTry.IsSubsetOf(stateRange)); var afterFinally = AssignStateRanges(tryFinally.FinallyBlock, stateRange); return afterTry.IntersectWith(afterFinally); case SwitchInstruction switchInst: SymbolicValue val = evalContext.Eval(switchInst.Value); if (val.Type != SymbolicValueType.State) goto default; List<LongInterval> exitIntervals = new List<LongInterval>(); foreach (var section in switchInst.Sections) { // switch (state + Constant) // matches 'case VALUE:' // iff (state + Constant == value) // iff (state == value - Constant) var effectiveLabels = section.Labels.AddOffset(unchecked(-val.Constant)); var result = AssignStateRanges(section.Body, stateRange.IntersectWith(effectiveLabels)); exitIntervals.AddRange(result.Intervals); } // exitIntervals = union of exits of all sections return new LongSet(exitIntervals); case IfInstruction ifInst: val = evalContext.Eval(ifInst.Condition).AsBool(); if (val.Type != SymbolicValueType.StateInSet) { goto default; } LongSet trueRanges = val.ValueSet; var afterTrue = AssignStateRanges(ifInst.TrueInst, stateRange.IntersectWith(trueRanges)); var afterFalse = AssignStateRanges(ifInst.FalseInst, stateRange.ExceptWith(trueRanges)); return afterTrue.UnionWith(afterFalse); case Branch br: AddStateRange(br.TargetBlock, stateRange); return LongSet.Empty; case Leave leave when mode == StateRangeAnalysisMode.AwaitInFinally: AddStateRangeForLeave(leave.TargetContainer, stateRange); return LongSet.Empty; case Nop nop: return stateRange; case StLoc stloc when stloc.Variable == doFinallyBodies || stloc.Variable == skipFinallyBodies: // pre-roslyn async/await uses a generated 'bool doFinallyBodies'; // do not treat this as user code. // Mono also does this for yield-return. return stateRange; case StLoc stloc: val = evalContext.Eval(stloc.Value); if (val.Type == SymbolicValueType.State && val.Constant == 0) { evalContext.AddStateVariable(stloc.Variable); return stateRange; } else { goto default; // user code } case Call call when mode == StateRangeAnalysisMode.IteratorDispose: // Call to finally method. // Usually these are in finally blocks, but sometimes (e.g. foreach over array), // the C# compiler puts the call to a finally method outside the try-finally block. finallyMethodToStateRange!.Add((IMethod)call.Method.MemberDefinition, stateRange); return LongSet.Empty; // return Empty since we executed user code (the finally method) case StObj stobj when mode == StateRangeAnalysisMode.IteratorMoveNext: { if (stobj.MatchStFld(out var target, out var field, out var value) && target.MatchLdThis() && field.MemberDefinition == stateField && value.MatchLdcI4(-1)) { // Mono resets the state field during MoveNext(); // don't consider this user code. return stateRange; } else { goto default; } } default: // User code - abort analysis if (mode == StateRangeAnalysisMode.IteratorDispose && !(inst is Leave l && l.IsLeavingFunction)) { throw new SymbolicAnalysisFailedException("Unexpected instruction in Iterator.Dispose()"); } return LongSet.Empty; } } private void AddStateRange(Block block, LongSet stateRange) { if (ranges.TryGetValue(block, out var existingRange)) ranges[block] = stateRange.UnionWith(existingRange); else ranges.Add(block, stateRange); } private void AddStateRangeForLeave(BlockContainer target, LongSet stateRange) { if (rangesForLeave!.TryGetValue(target, out var existingRange)) rangesForLeave[target] = stateRange.UnionWith(existingRange); else rangesForLeave.Add(target, stateRange); } /// <summary> /// Gets a mapping from states to blocks. /// /// Within the given container (which should be the container that was analyzed), /// the mapping prefers the last block. /// Blocks outside of the given container are preferred over blocks within the container. /// </summary> public LongDict<Block> GetBlockStateSetMapping(BlockContainer container) { return LongDict.Create(GetMapping()); IEnumerable<(LongSet, Block)> GetMapping() { // First, consider container exits: foreach (var (block, states) in ranges) { if (block.Parent != container) yield return (states, block); } // Then blocks within the container: foreach (var block in container.Blocks.Reverse()) { if (ranges.TryGetValue(block, out var states)) { yield return (states, block); } } } } public LongDict<BlockContainer> GetBlockStateSetMappingForLeave() { Debug.Assert(mode == StateRangeAnalysisMode.AwaitInFinally); return LongDict.Create(rangesForLeave!.Select(kv => (kv.Value, kv.Key))); } } }
ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/StateRangeAnalysis.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/StateRangeAnalysis.cs", "repo_id": "ILSpy", "token_count": 3828 }
232
#nullable enable // Copyright (c) 2014-2016 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.IL.Transforms; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.IL { /// <summary> /// A block consists of a list of IL instructions. /// /// <para> /// Note: if execution reaches the end of the instruction list, /// the FinalInstruction (which is not part of the list) will be executed. /// The block returns returns the result value of the FinalInstruction. /// For blocks returning void, the FinalInstruction will usually be 'nop'. /// </para> /// /// There are three different uses for blocks: /// 1) Blocks in block containers. Used as targets for Branch instructions. /// 2) Blocks to group a bunch of statements, e.g. the TrueInst of an IfInstruction. /// 3) Inline blocks that evaluate to a value, e.g. for array initializers. /// </summary> partial class Block : ILInstruction { public static readonly SlotInfo InstructionSlot = new SlotInfo("Instruction", isCollection: true); public static readonly SlotInfo FinalInstructionSlot = new SlotInfo("FinalInstruction"); public readonly BlockKind Kind; public readonly InstructionCollection<ILInstruction> Instructions; ILInstruction finalInstruction = null!; /// <summary> /// For blocks in a block container, this field holds /// the number of incoming control flow edges to this block. /// </summary> /// <remarks> /// This variable is automatically updated when adding/removing branch instructions from the ILAst, /// or when adding the block as an entry point to a BlockContainer. /// </remarks> public int IncomingEdgeCount { get; internal set; } /// <summary> /// A 'final instruction' that gets executed after the <c>Instructions</c> collection. /// Provides the return value for the block. /// </summary> /// <remarks> /// Blocks in containers must have 'Nop' as a final instruction. /// /// Note that the FinalInstruction is included in Block.Children, /// but not in Block.Instructions! /// </remarks> public ILInstruction FinalInstruction { get { return finalInstruction; } set { ValidateChild(value); SetChildInstruction(ref finalInstruction, value, Instructions.Count); } } protected internal override void InstructionCollectionUpdateComplete() { base.InstructionCollectionUpdateComplete(); if (finalInstruction.Parent == this) finalInstruction.ChildIndex = Instructions.Count; } public Block(BlockKind kind = BlockKind.ControlFlow) : base(OpCode.Block) { this.Kind = kind; this.Instructions = new InstructionCollection<ILInstruction>(this, 0); this.FinalInstruction = new Nop(); } public override ILInstruction Clone() { Block clone = new Block(Kind); clone.AddILRange(this); clone.Instructions.AddRange(this.Instructions.Select(inst => inst.Clone())); clone.FinalInstruction = this.FinalInstruction.Clone(); return clone; } internal override void CheckInvariant(ILPhase phase) { base.CheckInvariant(phase); for (int i = 0; i < Instructions.Count - 1; i++) { // only the last instruction may have an unreachable endpoint Debug.Assert(!Instructions[i].HasFlag(InstructionFlags.EndPointUnreachable)); } switch (this.Kind) { case BlockKind.ControlFlow: Debug.Assert(finalInstruction.OpCode == OpCode.Nop); break; case BlockKind.CallInlineAssign: Debug.Assert(MatchInlineAssignBlock(out _, out _)); break; case BlockKind.CallWithNamedArgs: Debug.Assert(finalInstruction is CallInstruction); foreach (var inst in Instructions) { var stloc = inst as StLoc; DebugAssert(stloc != null, "Instructions in CallWithNamedArgs must be assignments"); DebugAssert(stloc.Variable.Kind == VariableKind.NamedArgument); DebugAssert(stloc.Variable.IsSingleDefinition && stloc.Variable.LoadCount == 1); DebugAssert(stloc.Variable.LoadInstructions.Single().Parent == finalInstruction); } var call = (CallInstruction)finalInstruction; if (call.IsInstanceCall) { // special case: with instance calls, Instructions[0] must be for the this parameter ILVariable v = ((StLoc)Instructions[0]).Variable; Debug.Assert(call.Arguments[0].MatchLdLoc(v)); } break; case BlockKind.ArrayInitializer: var final = finalInstruction as LdLoc; Debug.Assert(final != null && final.Variable.IsSingleDefinition && final.Variable.Kind == VariableKind.InitializerTarget); IType? type = null; Debug.Assert(Instructions[0].MatchStLoc(final!.Variable, out var init) && init.MatchNewArr(out type)); for (int i = 1; i < Instructions.Count; i++) { DebugAssert(Instructions[i].MatchStObj(out ILInstruction? target, out _, out var t) && type != null && type.Equals(t)); DebugAssert(target.MatchLdElema(out t, out ILInstruction? array) && type.Equals(t)); DebugAssert(array.MatchLdLoc(out ILVariable? v) && v == final.Variable); } break; case BlockKind.CollectionInitializer: case BlockKind.ObjectInitializer: var final2 = finalInstruction as LdLoc; Debug.Assert(final2 != null); var initVar2 = final2!.Variable; Debug.Assert(initVar2.StoreCount == 1 && initVar2.Kind == VariableKind.InitializerTarget); IType? type2 = null; bool condition = Instructions[0].MatchStLoc(final2.Variable, out var init2); Debug.Assert(condition); Debug.Assert(init2 is NewObj || init2 is DefaultValue || (init2 is CallInstruction c && c.Method.FullNameIs("System.Activator", "CreateInstance") && c.Method.TypeArguments.Count == 1) || (init2 is Block named && named.Kind == BlockKind.CallWithNamedArgs)); switch (init2) { case NewObj newObj: type2 = newObj.Method.DeclaringType; break; case DefaultValue defaultValue: type2 = defaultValue.Type; break; case Block callWithNamedArgs when callWithNamedArgs.Kind == BlockKind.CallWithNamedArgs: type2 = ((CallInstruction)callWithNamedArgs.FinalInstruction).Method.ReturnType; break; case CallInstruction ci2 when TransformCollectionAndObjectInitializers.IsRecordCloneMethodCall(ci2): type2 = ci2.Method.DeclaringType; break; case Call c2 when c2.Method.FullNameIs("System.Activator", "CreateInstance") && c2.Method.TypeArguments.Count == 1: type2 = c2.Method.TypeArguments[0]; break; default: Debug.Assert(false); break; } for (int i = 1; i < Instructions.Count; i++) { Debug.Assert(Instructions[i] is StLoc || AccessPathElement.GetAccessPath(Instructions[i], type2).Kind != AccessPathKind.Invalid); } break; case BlockKind.DeconstructionConversions: Debug.Assert(this.SlotInfo == DeconstructInstruction.ConversionsSlot); break; case BlockKind.DeconstructionAssignments: Debug.Assert(this.SlotInfo == DeconstructInstruction.AssignmentsSlot); break; case BlockKind.InterpolatedString: Debug.Assert(FinalInstruction is Call { Method: { Name: "ToStringAndClear" }, Arguments: { Count: 1 } }); var interpolInit = Instructions[0] as StLoc; DebugAssert(interpolInit != null && interpolInit.Variable.Kind == VariableKind.InitializerTarget && interpolInit.Variable.AddressCount == Instructions.Count && interpolInit.Variable.StoreCount == 1); for (int i = 1; i < Instructions.Count; i++) { Call? inst = Instructions[i] as Call; DebugAssert(inst != null); DebugAssert(inst.Arguments.Count >= 1 && inst.Arguments[0].MatchLdLoca(interpolInit.Variable)); } break; } } public override StackType ResultType { get { return finalInstruction.ResultType; } } /// <summary> /// Gets the name of this block. /// </summary> public string Label { get { return Disassembler.DisassemblerHelpers.OffsetToString(this.StartILOffset); } } public override void WriteTo(ITextOutput output, ILAstWritingOptions options) { WriteILRange(output, options); output.Write("Block "); output.WriteLocalReference(Label, this, isDefinition: true); if (Kind != BlockKind.ControlFlow) output.Write($" ({Kind})"); if (Parent is BlockContainer) output.Write(" (incoming: {0})", IncomingEdgeCount); output.Write(' '); output.MarkFoldStart("{...}"); output.WriteLine("{"); output.Indent(); int index = 0; foreach (var inst in Instructions) { if (options.ShowChildIndexInBlock) { output.Write("[" + index + "] "); index++; } inst.WriteTo(output, options); output.WriteLine(); } if (finalInstruction.OpCode != OpCode.Nop) { output.Write("final: "); finalInstruction.WriteTo(output, options); output.WriteLine(); } output.Unindent(); output.Write("}"); output.MarkFoldEnd(); } protected override int GetChildCount() { return Instructions.Count + 1; } protected override ILInstruction GetChild(int index) { if (index == Instructions.Count) return finalInstruction; return Instructions[index]; } protected override void SetChild(int index, ILInstruction value) { if (index == Instructions.Count) FinalInstruction = value; else Instructions[index] = value; } protected override SlotInfo GetChildSlot(int index) { if (index == Instructions.Count) return FinalInstructionSlot; else return InstructionSlot; } protected override InstructionFlags ComputeFlags() { var flags = InstructionFlags.None; foreach (var inst in Instructions) { flags |= inst.Flags; } flags |= FinalInstruction.Flags; return flags; } public override InstructionFlags DirectFlags { get { return InstructionFlags.None; } } /// <summary> /// Deletes this block from its parent container. /// This may cause the indices of other blocks in that container to change. /// /// It is an error to call this method on blocks that are not directly within a container. /// It is also an error to call this method on the entry-point block. /// </summary> public void Remove() { Debug.Assert(ChildIndex > 0); var container = (BlockContainer)Parent!; Debug.Assert(container.Blocks[ChildIndex] == this); container.Blocks.SwapRemoveAt(ChildIndex); } /// <summary> /// Apply a list of transforms to this function. /// </summary> public void RunTransforms(IEnumerable<IBlockTransform> transforms, BlockTransformContext context) { this.CheckInvariant(ILPhase.Normal); foreach (var transform in transforms) { context.CancellationToken.ThrowIfCancellationRequested(); Debug.Assert(context.IndexOfFirstAlreadyTransformedInstruction <= this.Instructions.Count); context.StepStartGroup(transform.GetType().Name); transform.Run(this, context); this.CheckInvariant(ILPhase.Normal); context.StepEndGroup(); } } /// <summary> /// Gets the predecessor of the given instruction. /// Returns null if inst.Parent is not a block. /// </summary> public static ILInstruction? GetPredecessor(ILInstruction inst) { if (inst.Parent is Block block && inst.ChildIndex > 0) { return block.Instructions[inst.ChildIndex - 1]; } else { return null; } } /// <summary> /// If inst is a block consisting of a single instruction, returns that instruction. /// Otherwise, returns the input instruction. /// </summary> [return: NotNullIfNotNull("inst")] public static ILInstruction? Unwrap(ILInstruction? inst) { if (inst is Block block) { if (block.Instructions.Count == 1 && block.finalInstruction.MatchNop()) return block.Instructions[0]; } return inst; } /// <summary> /// Gets the closest parent Block. /// Returns null, if the instruction is not a descendant of a Block. /// </summary> public static Block? FindClosestBlock(ILInstruction? inst) { var curr = inst; while (curr != null) { if (curr is Block b) return b; curr = curr.Parent; } return null; } public bool MatchInlineAssignBlock([NotNullWhen(true)] out CallInstruction? call, [NotNullWhen(true)] out ILInstruction? value) { call = null; value = null; if (this.Kind != BlockKind.CallInlineAssign) return false; if (this.Instructions.Count != 1) return false; call = this.Instructions[0] as CallInstruction; if (call == null || call.Arguments.Count == 0) return false; if (!call.Arguments.Last().MatchStLoc(out var tmp, out value)) return false; if (!(tmp.IsSingleDefinition && tmp.LoadCount == 1)) return false; return this.FinalInstruction.MatchLdLoc(tmp); } public bool MatchIfAtEndOfBlock([NotNullWhen(true)] out ILInstruction? condition, [NotNullWhen(true)] out ILInstruction? trueInst, [NotNullWhen(true)] out ILInstruction? falseInst) { condition = null; trueInst = null; falseInst = null; if (Instructions.Count < 2) return false; if (Instructions[Instructions.Count - 2].MatchIfInstruction(out condition, out trueInst)) { // Swap trueInst<>falseInst for every logic.not in the condition. falseInst = Instructions.Last(); while (condition.MatchLogicNot(out var arg)) { condition = arg; (trueInst, falseInst) = (falseInst, trueInst); } return true; } return false; } } public enum BlockKind { /// <summary> /// Block is used for control flow. /// All blocks in block containers must have this type. /// Control flow blocks cannot evaluate to a value (FinalInstruction must be Nop). /// </summary> ControlFlow, /// <summary> /// Block is used for array initializers, e.g. `new int[] { expr1, expr2 }`. /// </summary> ArrayInitializer, CollectionInitializer, ObjectInitializer, StackAllocInitializer, /// <summary> /// Block is used for using the result of a property setter inline. /// Example: <code>Use(this.Property = value);</code> /// This is only for inline assignments to property or indexers; other inline assignments work /// by using the result value of the stloc/stobj instructions. /// /// Constructed by TransformAssignment. /// Can be deconstructed using Block.MatchInlineAssignBlock(). /// </summary> /// <example> /// Block { /// call setter(..., stloc s(...)) /// final: ldloc s /// } /// </example> CallInlineAssign, /// <summary> /// Call using named arguments. /// </summary> /// <remarks> /// Each instruction is assigning to a new local. /// The final instruction is a call. /// The locals for this block have exactly one store and /// exactly one load, which must be an immediate argument to the call. /// </remarks> /// <example> /// Block { /// stloc arg0 = ... /// stloc arg1 = ... /// final: call M(..., arg1, arg0, ...) /// } /// </example> CallWithNamedArgs, /// <summary> /// <see cref="DeconstructInstruction"/> /// </summary> DeconstructionConversions, /// <summary> /// <see cref="DeconstructInstruction"/> /// </summary> DeconstructionAssignments, WithInitializer, /// <summary> /// String interpolation using DefaultInterpolatedStringHandler. /// </summary> /// <example> /// Block { /// stloc I_0 = newobj DefaultInterpolatedStringHandler(...) /// call AppendXXX(I_0, ...) /// ... /// final: call ToStringAndClear(ldloc I_0) /// } /// </example> InterpolatedString, } }
ILSpy/ICSharpCode.Decompiler/IL/Instructions/Block.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/Block.cs", "repo_id": "ILSpy", "token_count": 5935 }
233
#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; namespace ICSharpCode.Decompiler.IL { /// <summary>If statement / conditional expression. <c>if (condition) trueExpr else falseExpr</c></summary> /// <remarks> /// The condition must return StackType.I4, use comparison instructions like Ceq to check if other types are non-zero. /// /// If the condition evaluates to non-zero, the TrueInst is executed. /// If the condition evaluates to zero, the FalseInst is executed. /// The return value of the IfInstruction is the return value of the TrueInst or FalseInst. /// /// IfInstruction is also used to represent logical operators: /// "a || b" ==> if (a) (ldc.i4 1) else (b) /// "a &amp;&amp; b" ==> if (a) (b) else (ldc.i4 0) /// "a ? b : c" ==> if (a) (b) else (c) /// </remarks> partial class IfInstruction : ILInstruction { public IfInstruction(ILInstruction condition, ILInstruction trueInst, ILInstruction? falseInst = null) : base(OpCode.IfInstruction) { this.Condition = condition; this.TrueInst = trueInst; this.FalseInst = falseInst ?? new Nop(); } public static IfInstruction LogicAnd(ILInstruction lhs, ILInstruction rhs) { return new IfInstruction(lhs, rhs, new LdcI4(0)); } public static IfInstruction LogicOr(ILInstruction lhs, ILInstruction? rhs) { return new IfInstruction(lhs, new LdcI4(1), rhs); } internal override void CheckInvariant(ILPhase phase) { base.CheckInvariant(phase); Debug.Assert(condition.ResultType == StackType.I4); Debug.Assert(trueInst.ResultType == falseInst.ResultType || trueInst.HasDirectFlag(InstructionFlags.EndPointUnreachable) || falseInst.HasDirectFlag(InstructionFlags.EndPointUnreachable)); } public override StackType ResultType { get { if (trueInst.HasDirectFlag(InstructionFlags.EndPointUnreachable)) return falseInst.ResultType; else return trueInst.ResultType; } } public override InstructionFlags DirectFlags { get { return InstructionFlags.ControlFlow; } } protected override InstructionFlags ComputeFlags() { return InstructionFlags.ControlFlow | condition.Flags | SemanticHelper.CombineBranches(trueInst.Flags, falseInst.Flags); } public override void WriteTo(ITextOutput output, ILAstWritingOptions options) { WriteILRange(output, options); if (options.UseLogicOperationSugar) { if (MatchLogicAnd(out var lhs, out var rhs)) { output.Write("logic.and("); lhs.WriteTo(output, options); output.Write(", "); rhs.WriteTo(output, options); output.Write(')'); return; } if (MatchLogicOr(out lhs, out rhs)) { output.Write("logic.or("); lhs.WriteTo(output, options); output.Write(", "); rhs.WriteTo(output, options); output.Write(')'); return; } } output.Write(OpCode); output.Write(" ("); condition.WriteTo(output, options); output.Write(") "); trueInst.WriteTo(output, options); if (falseInst.OpCode != OpCode.Nop) { output.Write(" else "); falseInst.WriteTo(output, options); } } /// <summary> /// Gets whether the input instruction occurs in a context where it is being compared with 0. /// </summary> internal static bool IsInConditionSlot(ILInstruction inst) { var slot = inst.SlotInfo; if (slot == IfInstruction.ConditionSlot) return true; if (slot == IfInstruction.TrueInstSlot || slot == IfInstruction.FalseInstSlot || slot == NullCoalescingInstruction.FallbackInstSlot) return IsInConditionSlot(inst.Parent!); if (inst.Parent is Comp comp) { if (comp.Left == inst && comp.Right.MatchLdcI4(0)) return true; if (comp.Right == inst && comp.Left.MatchLdcI4(0)) return true; } return false; } } }
ILSpy/ICSharpCode.Decompiler/IL/Instructions/IfInstruction.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/IfInstruction.cs", "repo_id": "ILSpy", "token_count": 1715 }
234
#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.Diagnostics; using System.Linq; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.IL { public abstract class TryInstruction : ILInstruction { public static readonly SlotInfo TryBlockSlot = new SlotInfo("TryBlock"); protected TryInstruction(OpCode opCode, ILInstruction tryBlock) : base(opCode) { this.TryBlock = tryBlock; } ILInstruction tryBlock = null!; public ILInstruction TryBlock { get { return this.tryBlock; } set { ValidateChild(value); SetChildInstruction(ref this.tryBlock, value, 0); } } } /// <summary> /// Try-catch statement. /// </summary> /// <remarks> /// The return value of the try or catch blocks is ignored, the TryCatch always returns void. /// </remarks> partial class TryCatch : TryInstruction { public static readonly SlotInfo HandlerSlot = new SlotInfo("Handler", isCollection: true); public readonly InstructionCollection<TryCatchHandler> Handlers; public TryCatch(ILInstruction tryBlock) : base(OpCode.TryCatch, tryBlock) { this.Handlers = new InstructionCollection<TryCatchHandler>(this, 1); } public override ILInstruction Clone() { var clone = new TryCatch(TryBlock.Clone()); clone.AddILRange(this); clone.Handlers.AddRange(this.Handlers.Select(h => (TryCatchHandler)h.Clone())); return clone; } public override void WriteTo(ITextOutput output, ILAstWritingOptions options) { WriteILRange(output, options); output.Write(".try "); TryBlock.WriteTo(output, options); foreach (var handler in Handlers) { output.Write(' '); handler.WriteTo(output, options); } } public override StackType ResultType { get { return StackType.Void; } } protected override InstructionFlags ComputeFlags() { var flags = TryBlock.Flags; foreach (var handler in Handlers) flags = SemanticHelper.CombineBranches(flags, handler.Flags); return flags | InstructionFlags.ControlFlow; } public override InstructionFlags DirectFlags { get { return InstructionFlags.ControlFlow; } } protected override int GetChildCount() { return 1 + Handlers.Count; } protected override ILInstruction GetChild(int index) { if (index == 0) return TryBlock; else return Handlers[index - 1]; } protected override void SetChild(int index, ILInstruction value) { if (index == 0) TryBlock = value; else Handlers[index - 1] = (TryCatchHandler)value; } protected override SlotInfo GetChildSlot(int index) { if (index == 0) return TryBlockSlot; else return HandlerSlot; } } /// <summary> /// Catch handler within a try-catch statement. /// /// When an exception occurs in the try block of the parent try.catch statement, the runtime searches /// the nearest enclosing TryCatchHandler with a matching variable type and /// assigns the exception object to the <see cref="Variable"/>, and executes the <see cref="Filter"/>. /// If the filter evaluates to 0, the exception is not caught and the runtime looks for the next catch handler. /// If the filter evaluates to 1, the stack is unwound, the exception caught and assigned to the <see cref="Variable"/>, /// and the <see cref="Body"/> is executed. /// </summary> partial class TryCatchHandler { internal override void CheckInvariant(ILPhase phase) { base.CheckInvariant(phase); Debug.Assert(Parent is TryCatch); Debug.Assert(filter.ResultType == StackType.I4); Debug.Assert(this.IsDescendantOf(variable.Function!)); } public override StackType ResultType { get { return StackType.Void; } } protected override InstructionFlags ComputeFlags() { return filter.Flags | body.Flags | InstructionFlags.ControlFlow | InstructionFlags.MayWriteLocals; } public override InstructionFlags DirectFlags { get { // the body is not evaluated if the filter returns 0 return InstructionFlags.ControlFlow | InstructionFlags.MayWriteLocals; } } public override void WriteTo(ITextOutput output, ILAstWritingOptions options) { WriteILRange(output, options); output.Write("catch "); if (variable != null) { output.WriteLocalReference(variable.Name, variable, isDefinition: true); output.Write(" : "); Disassembler.DisassemblerHelpers.WriteOperand(output, variable.Type); } output.Write(" when ("); filter.WriteTo(output, options); output.Write(')'); output.Write(' '); body.WriteTo(output, options); } /// <summary> /// Gets the ILRange of the instructions at the start of the catch-block, /// that take the exception object and store it in the exception variable slot. /// Note: This range is empty, if Filter is not empty, i.e., ldloc 1. /// </summary> public Interval ExceptionSpecifierILRange { get; private set; } public void AddExceptionSpecifierILRange(Interval newRange) { ExceptionSpecifierILRange = CombineILRange(ExceptionSpecifierILRange, newRange); } } partial class TryFinally { public static readonly SlotInfo FinallyBlockSlot = new SlotInfo("FinallyBlock"); public TryFinally(ILInstruction tryBlock, ILInstruction finallyBlock) : base(OpCode.TryFinally, tryBlock) { this.FinallyBlock = finallyBlock; } ILInstruction finallyBlock = null!; public ILInstruction FinallyBlock { get { return this.finallyBlock; } set { ValidateChild(value); SetChildInstruction(ref this.finallyBlock, value, 1); } } public override ILInstruction Clone() { return new TryFinally(TryBlock.Clone(), finallyBlock.Clone()).WithILRange(this); } public override void WriteTo(ITextOutput output, ILAstWritingOptions options) { WriteILRange(output, options); output.Write(".try "); TryBlock.WriteTo(output, options); output.Write(" finally "); finallyBlock.WriteTo(output, options); } public override StackType ResultType { get { return TryBlock.ResultType; } } protected override InstructionFlags ComputeFlags() { // if the endpoint of either the try or the finally is unreachable, the endpoint of the try-finally will be unreachable return TryBlock.Flags | finallyBlock.Flags | InstructionFlags.ControlFlow; } public override InstructionFlags DirectFlags { get { return InstructionFlags.ControlFlow; } } protected override int GetChildCount() { return 2; } protected override ILInstruction GetChild(int index) { switch (index) { case 0: return TryBlock; case 1: return finallyBlock; default: throw new IndexOutOfRangeException(); } } protected override void SetChild(int index, ILInstruction value) { switch (index) { case 0: TryBlock = value; break; case 1: FinallyBlock = value; break; default: throw new IndexOutOfRangeException(); } } protected override SlotInfo GetChildSlot(int index) { switch (index) { case 0: return TryBlockSlot; case 1: return FinallyBlockSlot; default: throw new IndexOutOfRangeException(); } } } partial class TryFault { public static readonly SlotInfo FaultBlockSlot = new SlotInfo("FaultBlock"); public TryFault(ILInstruction tryBlock, ILInstruction faultBlock) : base(OpCode.TryFinally, tryBlock) { this.FaultBlock = faultBlock; } ILInstruction faultBlock = null!; public ILInstruction FaultBlock { get { return this.faultBlock; } set { ValidateChild(value); SetChildInstruction(ref this.faultBlock, value, 1); } } public override ILInstruction Clone() { return new TryFault(TryBlock.Clone(), faultBlock.Clone()).WithILRange(this); } public override void WriteTo(ITextOutput output, ILAstWritingOptions options) { WriteILRange(output, options); output.Write(".try "); TryBlock.WriteTo(output, options); output.Write(" fault "); faultBlock.WriteTo(output, options); } public override StackType ResultType { get { return TryBlock.ResultType; } } protected override InstructionFlags ComputeFlags() { // The endpoint of the try-fault is unreachable iff the try endpoint is unreachable return TryBlock.Flags | (faultBlock.Flags & ~InstructionFlags.EndPointUnreachable) | InstructionFlags.ControlFlow; } public override InstructionFlags DirectFlags { get { return InstructionFlags.ControlFlow; } } protected override int GetChildCount() { return 2; } protected override ILInstruction GetChild(int index) { switch (index) { case 0: return TryBlock; case 1: return faultBlock; default: throw new IndexOutOfRangeException(); } } protected override void SetChild(int index, ILInstruction value) { switch (index) { case 0: TryBlock = value; break; case 1: FaultBlock = value; break; default: throw new IndexOutOfRangeException(); } } protected override SlotInfo GetChildSlot(int index) { switch (index) { case 0: return TryBlockSlot; case 1: return FaultBlockSlot; default: throw new IndexOutOfRangeException(); } } } public partial class Throw { internal StackType resultType = StackType.Void; } }
ILSpy/ICSharpCode.Decompiler/IL/Instructions/TryInstruction.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/TryInstruction.cs", "repo_id": "ILSpy", "token_count": 3587 }
235
// 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.Collections.Immutable; using System.Linq; using System.Resources; using ICSharpCode.Decompiler.CSharp.Resolver; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.IL.Transforms { /// <summary> /// /// </summary> class DeconstructionTransform : IStatementTransform { StatementTransformContext context; readonly Dictionary<ILVariable, int> deconstructionResultsLookup = new Dictionary<ILVariable, int>(); ILVariable[] deconstructionResults; ILVariable tupleVariable; TupleType tupleType; /* stloc tuple(call MakeIntIntTuple(ldloc this)) ---- stloc myInt(call op_Implicit(ldfld Item2(ldloca tuple))) stloc a(ldfld Item1(ldloca tuple)) stloc b(ldloc myInt) ==> deconstruct { init: <empty> deconstruct: match.deconstruct(temp = ldloca tuple) { match(result0 = deconstruct.result 0(temp)), match(result1 = deconstruct.result 1(temp)) } conversions: { stloc conv2(call op_Implicit(ldloc result1)) } assignments: { stloc a(ldloc result0) stloc b(ldloc conv2) } } * */ void IStatementTransform.Run(Block block, int pos, StatementTransformContext context) { if (!context.Settings.Deconstruction) return; try { this.context = context; Reset(); if (TransformDeconstruction(block, pos)) return; if (InlineDeconstructionInitializer(block, pos)) return; } finally { this.context = null; Reset(); } } private void Reset() { this.deconstructionResultsLookup.Clear(); this.tupleVariable = null; this.tupleType = null; this.deconstructionResults = null; } struct ConversionInfo { public IType inputType; public Conv conv; } /// <summary> /// Get index of deconstruction result or tuple element /// Returns -1 on failure. /// </summary> int FindIndex(ILInstruction inst, out Action<DeconstructInstruction> delayedActions) { delayedActions = null; if (inst.MatchLdLoc(out var v)) { if (!deconstructionResultsLookup.TryGetValue(v, out int index)) return -1; return index; } if (inst.MatchLdFld(out _, out _)) { if (!TupleTransform.MatchTupleFieldAccess((LdFlda)((LdObj)inst).Target, out var tupleType, out var target, out int index)) return -1; // Item fields are one-based, we use zero-based indexing. index--; // normalize tuple type tupleType = TupleType.FromUnderlyingType(context.TypeSystem, tupleType); if (!target.MatchLdLoca(out v)) return -1; if (this.tupleVariable == null) { this.tupleVariable = v; this.tupleType = (TupleType)tupleType; this.deconstructionResults = new ILVariable[this.tupleType.Cardinality]; } if (this.tupleType.Cardinality < 2) return -1; if (v != tupleVariable || !this.tupleType.Equals(tupleType)) return -1; if (this.deconstructionResults[index] == null) { var freshVar = new ILVariable(VariableKind.StackSlot, this.tupleType.ElementTypes[index]) { Name = "E_" + index }; delayedActions += _ => context.Function.Variables.Add(freshVar); this.deconstructionResults[index] = freshVar; } delayedActions += _ => { inst.ReplaceWith(new LdLoc(this.deconstructionResults[index])); }; return index; } return -1; } /// <summary> /// stloc v(value) /// expr(..., deconstruct { ... }, ...) /// => /// expr(..., deconstruct { init: stloc v(value) ... }, ...) /// </summary> bool InlineDeconstructionInitializer(Block block, int pos) { if (!block.Instructions[pos].MatchStLoc(out var v, out var value)) return false; if (!(v.IsSingleDefinition && v.LoadCount == 1)) return false; if (pos + 1 >= block.Instructions.Count) return false; var result = ILInlining.FindLoadInNext(block.Instructions[pos + 1], v, value, InliningOptions.FindDeconstruction); if (result.Type != ILInlining.FindResultType.Deconstruction) return false; var deconstruction = (DeconstructInstruction)result.LoadInst; LdLoc loadInst = v.LoadInstructions[0]; if (!loadInst.IsDescendantOf(deconstruction.Assignments)) return false; if (loadInst.SlotInfo == StObj.TargetSlot) { if (value.OpCode == OpCode.LdFlda || value.OpCode == OpCode.LdElema) return false; } if (deconstruction.Init.Count > 0) { var a = deconstruction.Init[0].Variable.LoadInstructions.Single(); var b = v.LoadInstructions.Single(); if (!b.IsBefore(a)) return false; } context.Step("InlineDeconstructionInitializer", block.Instructions[pos]); deconstruction.Init.Insert(0, (StLoc)block.Instructions[pos]); block.Instructions.RemoveAt(pos); v.Kind = VariableKind.DeconstructionInitTemporary; return true; } bool TransformDeconstruction(Block block, int pos) { int startPos = pos; Action<DeconstructInstruction> delayedActions = null; if (MatchDeconstruction(block.Instructions[pos], out IMethod deconstructMethod, out ILInstruction rootTestedOperand)) { pos++; } if (!MatchConversions(block, ref pos, out var conversions, out var conversionStLocs, ref delayedActions)) return false; if (!MatchAssignments(block, ref pos, conversions, conversionStLocs, ref delayedActions)) return false; // first tuple element may not be discarded, // otherwise we would run this transform on a suffix of the actual pattern. if (deconstructionResults[0] == null) return false; context.Step("Deconstruction", block.Instructions[startPos]); DeconstructInstruction replacement = new DeconstructInstruction(); IType deconstructedType; if (deconstructMethod == null) { deconstructedType = this.tupleType; rootTestedOperand = new LdLoc(this.tupleVariable); } else { if (deconstructMethod.IsStatic) { deconstructedType = deconstructMethod.Parameters[0].Type; } else { deconstructedType = deconstructMethod.DeclaringType; } } var rootTempVariable = context.Function.RegisterVariable(VariableKind.PatternLocal, deconstructedType); replacement.Pattern = new MatchInstruction(rootTempVariable, deconstructMethod, rootTestedOperand) { IsDeconstructCall = deconstructMethod != null, IsDeconstructTuple = this.tupleType != null }; int index = 0; foreach (ILVariable v in deconstructionResults) { var result = v; if (result == null) { var freshVar = new ILVariable(VariableKind.PatternLocal, this.tupleType.ElementTypes[index]) { Name = "E_" + index }; context.Function.Variables.Add(freshVar); result = freshVar; } else { result.Kind = VariableKind.PatternLocal; } replacement.Pattern.SubPatterns.Add( new MatchInstruction( result, new DeconstructResultInstruction(index, result.StackType, new LdLoc(rootTempVariable)) ) ); index++; } replacement.Conversions = new Block(BlockKind.DeconstructionConversions); foreach (var convInst in conversionStLocs) { replacement.Conversions.Instructions.Add(convInst); } replacement.Assignments = new Block(BlockKind.DeconstructionAssignments); delayedActions?.Invoke(replacement); block.Instructions[startPos] = replacement; block.Instructions.RemoveRange(startPos + 1, pos - startPos - 1); return true; } bool MatchDeconstruction(ILInstruction inst, out IMethod deconstructMethod, out ILInstruction testedOperand) { testedOperand = null; deconstructMethod = null; deconstructionResults = null; if (!(inst is CallInstruction call)) return false; if (!MatchInstruction.IsDeconstructMethod(call.Method)) return false; if (call.Method.IsStatic || call.Method.DeclaringType.IsReferenceType == false) { if (!(call is Call)) return false; } else { if (!(call is CallVirt)) return false; } if (call.Arguments.Count < 3) return false; deconstructionResults = new ILVariable[call.Arguments.Count - 1]; for (int i = 0; i < deconstructionResults.Length; i++) { if (!call.Arguments[i + 1].MatchLdLoca(out var v)) return false; // TODO v.LoadCount may be 2 if the deconstruction is assigned to a tuple variable // or 0? because of discards if (!(v.StoreCount == 0 && v.AddressCount == 1 && v.LoadCount <= 1)) return false; deconstructionResultsLookup.Add(v, i); deconstructionResults[i] = v; } testedOperand = call.Arguments[0]; deconstructMethod = call.Method; return true; } bool MatchConversions(Block block, ref int pos, out Dictionary<ILVariable, ConversionInfo> conversions, out List<StLoc> conversionStLocs, ref Action<DeconstructInstruction> delayedActions) { conversions = new Dictionary<ILVariable, ConversionInfo>(); conversionStLocs = new List<StLoc>(); int previousIndex = -1; while (MatchConversion( block.Instructions.ElementAtOrDefault(pos), out var inputInstruction, out var outputVariable, out var info)) { int index = FindIndex(inputInstruction, out var tupleAccessAdjustment); if (index <= previousIndex) return false; if (!(outputVariable.IsSingleDefinition && outputVariable.LoadCount == 1)) return false; delayedActions += tupleAccessAdjustment; deconstructionResultsLookup.Add(outputVariable, index); conversions.Add(outputVariable, info); conversionStLocs.Add((StLoc)block.Instructions[pos]); pos++; previousIndex = index; } return true; } bool MatchConversion(ILInstruction inst, out ILInstruction inputInstruction, out ILVariable outputVariable, out ConversionInfo info) { info = default; inputInstruction = null; if (!inst.MatchStLoc(out outputVariable, out var value)) return false; if (!(value is Conv conv)) return false; info = new ConversionInfo { inputType = conv.Argument.InferType(context.TypeSystem), conv = conv }; inputInstruction = conv.Argument; return true; } bool MatchAssignments(Block block, ref int pos, Dictionary<ILVariable, ConversionInfo> conversions, List<StLoc> conversionStLocs, ref Action<DeconstructInstruction> delayedActions) { int previousIndex = -1; int conversionStLocIndex = 0; int startPos = pos; while (MatchAssignment(block.Instructions.ElementAtOrDefault(pos), out var targetType, out var valueInst, out var addAssignment)) { int index = FindIndex(valueInst, out var tupleAccessAdjustment); if (index <= previousIndex) return false; AddMissingAssignmentsForConversions(index, ref delayedActions); if (!(valueInst.MatchLdLoc(out var resultVariable) && conversions.TryGetValue(resultVariable, out var conversionInfo))) { conversionInfo = new ConversionInfo { inputType = valueInst.InferType(context.TypeSystem) }; } if (block.Instructions[pos].MatchStLoc(out var assignmentTarget, out _) && assignmentTarget.Kind == VariableKind.StackSlot && assignmentTarget.IsSingleDefinition && conversionInfo.conv == null) { delayedActions += _ => { assignmentTarget.Type = conversionInfo.inputType; }; } else { if (!IsCompatibleImplicitConversion(targetType, conversionInfo)) return false; } delayedActions += addAssignment; delayedActions += tupleAccessAdjustment; pos++; previousIndex = index; } AddMissingAssignmentsForConversions(int.MaxValue, ref delayedActions); if (deconstructionResults != null) { int i = previousIndex + 1; while (i < deconstructionResults.Length) { var v = deconstructionResults[i]; // this should only happen in release mode, where usually the last deconstruction element // is not stored to a temporary, if it is used directly (and only once!) // after the deconstruction. if (v?.LoadCount == 1) { delayedActions += (DeconstructInstruction deconstructInst) => { var freshVar = context.Function.RegisterVariable(VariableKind.StackSlot, v.Type); deconstructInst.Assignments.Instructions.Add(new StLoc(freshVar, new LdLoc(v))); v.LoadInstructions[0].Variable = freshVar; }; } i++; } } return startPos != pos; void AddMissingAssignmentsForConversions(int index, ref Action<DeconstructInstruction> delayedActions) { while (conversionStLocIndex < conversionStLocs.Count) { var stLoc = conversionStLocs[conversionStLocIndex]; int conversionResultIndex = deconstructionResultsLookup[stLoc.Variable]; if (conversionResultIndex >= index) break; if (conversionResultIndex > previousIndex) { delayedActions += (DeconstructInstruction deconstructInst) => { var freshVar = context.Function.RegisterVariable(VariableKind.StackSlot, stLoc.Variable.Type); deconstructInst.Assignments.Instructions.Add(new StLoc(stLoc.Variable, new LdLoc(freshVar))); stLoc.Variable = freshVar; }; } previousIndex = conversionResultIndex; conversionStLocIndex++; } } } bool MatchAssignment(ILInstruction inst, out IType targetType, out ILInstruction valueInst, out Action<DeconstructInstruction> addAssignment) { targetType = null; valueInst = null; addAssignment = null; if (inst == null) return false; if (inst.MatchStLoc(out var v, out var value) && value is Block block && block.MatchInlineAssignBlock(out var call, out valueInst)) { if (!DeconstructInstruction.IsAssignment(call, context.TypeSystem, out targetType, out _)) return false; if (!(v.IsSingleDefinition && v.LoadCount == 0)) return false; var valueInstCopy = valueInst; addAssignment = (DeconstructInstruction deconstructInst) => { call.Arguments[call.Arguments.Count - 1] = valueInstCopy; deconstructInst.Assignments.Instructions.Add(call); }; return true; } else if (DeconstructInstruction.IsAssignment(inst, context.TypeSystem, out targetType, out valueInst)) { // OK - use the assignment as is addAssignment = (DeconstructInstruction deconstructInst) => { deconstructInst.Assignments.Instructions.Add(inst); }; return true; } else { return false; } } bool IsCompatibleImplicitConversion(IType targetType, ConversionInfo conversionInfo) { var c = CSharpConversions.Get(context.TypeSystem) .ImplicitConversion(conversionInfo.inputType, targetType); if (!c.IsValid) return false; var inputType = conversionInfo.inputType; var conv = conversionInfo.conv; if (c.IsIdentityConversion || c.IsReferenceConversion) { return conv == null || conv.Kind == ConversionKind.Nop; } if (c.IsNumericConversion && conv != null) { switch (conv.Kind) { case ConversionKind.IntToFloat: return inputType.GetSign() == conv.InputSign; case ConversionKind.FloatPrecisionChange: return true; case ConversionKind.SignExtend: return inputType.GetSign() == Sign.Signed; case ConversionKind.ZeroExtend: return inputType.GetSign() == Sign.Unsigned; default: return false; } } return false; } } }
ILSpy/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs", "repo_id": "ILSpy", "token_count": 6190 }
236
// Copyright (c) 2016 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Linq; using System.Threading; using ICSharpCode.Decompiler.FlowAnalysis; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.IL.Transforms { /// <summary> /// Live range splitting for IL variables. /// </summary> public class SplitVariables : IILTransform { public void Run(ILFunction function, ILTransformContext context) { var groupStores = new GroupStores(function, context.CancellationToken); function.Body.AcceptVisitor(groupStores); // Replace analyzed variables with their split versions: foreach (var inst in function.Descendants.OfType<IInstructionWithVariableOperand>()) { if (groupStores.IsAnalyzedVariable(inst.Variable)) { inst.Variable = groupStores.GetNewVariable(inst); } } function.Variables.RemoveDead(); } static bool IsCandidateVariable(ILVariable v) { switch (v.Kind) { case VariableKind.Local: foreach (var ldloca in v.AddressInstructions) { if (DetermineAddressUse(ldloca, ldloca.Variable) == AddressUse.Unknown) { // If we don't understand how the address is being used, // we can't split the variable. return false; } } return true; case VariableKind.StackSlot: // stack slots: are already split by construction, // except for the locals-turned-stackslots in async functions // or stack slots handled by the infeasible path transform if (v.Function.IsAsync || v.RemoveIfRedundant) goto case VariableKind.Local; else return false; default: // parameters: avoid splitting parameters // pinned locals: must not split (doing so would extend the life of the pin to the end of the method) return false; } } enum AddressUse { Unknown, /// <summary> /// Address is immediately used for reading and/or writing, /// without the possibility of the variable being directly stored to (via 'stloc') /// in between the 'ldloca' and the use of the address. /// </summary> Immediate, /// <summary> /// We support some limited form of ref locals referring to a target variable, /// without giving up splitting of the target variable. /// Requirements: /// * the ref local is single-assignment /// * the ref local is initialized directly with 'ldloca target; stloc ref_local', /// not a derived pointer (e.g. 'ldloca target; ldflda F; stloc ref_local'). /// * all uses of the ref_local are immediate. /// There may be stores to the target variable in between the 'stloc ref_local' and its uses, /// but we handle that case by treating each use of the ref_local as an address access /// of the target variable (as if the ref_local was eliminated via copy propagation). /// </summary> WithSupportedRefLocals, } static AddressUse DetermineAddressUse(ILInstruction addressLoadingInstruction, ILVariable targetVar) { switch (addressLoadingInstruction.Parent) { case LdObj _: case StObj stobj when stobj.Target == addressLoadingInstruction: return AddressUse.Immediate; case LdFlda ldflda: return DetermineAddressUse(ldflda, targetVar); case Await await: // GetAwaiter() may write to the struct, but shouldn't store the address for later use return AddressUse.Immediate; case CallInstruction call: return HandleCall(addressLoadingInstruction, targetVar, call); case StLoc stloc when stloc.Variable.IsSingleDefinition: // Address stored in local variable: also check all uses of that variable. if (!(stloc.Variable.Kind == VariableKind.StackSlot || stloc.Variable.Kind == VariableKind.Local)) return AddressUse.Unknown; var value = stloc.Value; while (value is LdFlda ldFlda) { value = ldFlda.Target; } if (value.OpCode != OpCode.LdLoca) { // GroupStores only handles ref-locals correctly when they are supported by GetAddressLoadForRefLocalUse(), // which only works for ldflda*(ldloca) return AddressUse.Unknown; } foreach (var load in stloc.Variable.LoadInstructions) { if (DetermineAddressUse(load, targetVar) != AddressUse.Immediate) return AddressUse.Unknown; } return AddressUse.WithSupportedRefLocals; default: return AddressUse.Unknown; } } static AddressUse HandleCall(ILInstruction addressLoadingInstruction, ILVariable targetVar, CallInstruction call) { // Address is passed to method. // We'll assume the method only uses the address locally, // unless we can see an address being returned from the method: IType returnType = (call is NewObj) ? call.Method.DeclaringType : call.Method.ReturnType; if (returnType.IsByRefLike) { // If the address is returned from the method, it check whether it's consumed immediately. // This can still be fine, as long as we also check the consumer's other arguments for 'stloc targetVar'. if (DetermineAddressUse(call, targetVar) != AddressUse.Immediate) return AddressUse.Unknown; } foreach (var p in call.Method.Parameters) { // catch "out Span<int>" and similar if (p.Type.SkipModifiers() is ByReferenceType brt && brt.ElementType.IsByRefLike) return AddressUse.Unknown; } // ensure there's no 'stloc target' in between the ldloca and the call consuming the address for (int i = addressLoadingInstruction.ChildIndex + 1; i < call.Arguments.Count; i++) { foreach (var inst in call.Arguments[i].Descendants) { if (inst is StLoc store && store.Variable == targetVar) return AddressUse.Unknown; } } return AddressUse.Immediate; } /// <summary> /// Given 'ldloc ref_local' and 'ldloca target; stloc ref_local', returns the ldloca. /// This function must return a non-null LdLoca for every use of a SupportedRefLocal. /// </summary> static LdLoca GetAddressLoadForRefLocalUse(LdLoc ldloc) { if (!ldloc.Variable.IsSingleDefinition) return null; // only single-definition variables can be supported ref locals var store = ldloc.Variable.StoreInstructions.SingleOrDefault(); if (store is StLoc stloc) { var value = stloc.Value; while (value is LdFlda ldFlda) { value = ldFlda.Target; } return value as LdLoca; } return null; } /// <summary> /// Use the union-find structure to merge /// </summary> /// <remarks> /// Instructions in a group are stores to the same variable that must stay together (cannot be split). /// </remarks> class GroupStores : ReachingDefinitionsVisitor { readonly UnionFind<IInstructionWithVariableOperand> unionFind = new UnionFind<IInstructionWithVariableOperand>(); /// <summary> /// For each uninitialized variable, one representative instruction that /// potentially observes the unintialized value of the variable. /// Used to merge together all such loads of the same uninitialized value. /// </summary> readonly Dictionary<ILVariable, IInstructionWithVariableOperand> uninitVariableUsage = new Dictionary<ILVariable, IInstructionWithVariableOperand>(); public GroupStores(ILFunction scope, CancellationToken cancellationToken) : base(scope, IsCandidateVariable, cancellationToken) { } protected internal override void VisitLdLoc(LdLoc inst) { base.VisitLdLoc(inst); HandleLoad(inst); var refLocalAddressLoad = GetAddressLoadForRefLocalUse(inst); if (refLocalAddressLoad != null) { // SupportedRefLocal: act as if we copy-propagated the ldloca // to the point of use: HandleLoad(refLocalAddressLoad); } } protected internal override void VisitLdLoca(LdLoca inst) { base.VisitLdLoca(inst); HandleLoad(inst); } void HandleLoad(IInstructionWithVariableOperand inst) { if (IsAnalyzedVariable(inst.Variable)) { if (IsPotentiallyUninitialized(state, inst.Variable)) { // merge all uninit loads together: if (uninitVariableUsage.TryGetValue(inst.Variable, out var uninitLoad)) { unionFind.Merge(inst, uninitLoad); } else { uninitVariableUsage.Add(inst.Variable, inst); } } foreach (var store in GetStores(state, inst.Variable)) { unionFind.Merge(inst, (IInstructionWithVariableOperand)store); } } } readonly Dictionary<IInstructionWithVariableOperand, ILVariable> newVariables = new Dictionary<IInstructionWithVariableOperand, ILVariable>(); /// <summary> /// Gets the new variable for a LdLoc, StLoc or TryCatchHandler instruction. /// </summary> internal ILVariable GetNewVariable(IInstructionWithVariableOperand inst) { var representative = unionFind.Find(inst); ILVariable v; if (!newVariables.TryGetValue(representative, out v)) { v = new ILVariable(inst.Variable.Kind, inst.Variable.Type, inst.Variable.StackType, inst.Variable.Index); v.Name = inst.Variable.Name; v.HasGeneratedName = inst.Variable.HasGeneratedName; v.StateMachineField = inst.Variable.StateMachineField; v.InitialValueIsInitialized = inst.Variable.InitialValueIsInitialized; v.UsesInitialValue = false; // we'll set UsesInitialValue when we encounter an uninit load v.RemoveIfRedundant = inst.Variable.RemoveIfRedundant; newVariables.Add(representative, v); inst.Variable.Function.Variables.Add(v); } if (inst.Variable.UsesInitialValue && uninitVariableUsage.TryGetValue(inst.Variable, out var uninitLoad) && uninitLoad == inst) { v.UsesInitialValue = true; } return v; } } } }
ILSpy/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs", "repo_id": "ILSpy", "token_count": 3767 }
237
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Reflection.Metadata; namespace ICSharpCode.Decompiler.Metadata { /// <summary> /// Decodes custom attribute blobs. /// </summary> internal readonly struct CustomAttributeDecoder<TType> { // This is a stripped-down copy of SRM's internal CustomAttributeDecoder. // We need it to decode security declarations. private readonly ICustomAttributeTypeProvider<TType> _provider; private readonly MetadataReader _reader; private readonly bool _provideBoxingTypeInfo; public CustomAttributeDecoder(ICustomAttributeTypeProvider<TType> provider, MetadataReader reader, bool provideBoxingTypeInfo = false) { _reader = reader; _provider = provider; _provideBoxingTypeInfo = provideBoxingTypeInfo; } public ImmutableArray<CustomAttributeNamedArgument<TType>> DecodeNamedArguments(ref BlobReader valueReader, int count) { var arguments = ImmutableArray.CreateBuilder<CustomAttributeNamedArgument<TType>>(count); for (int i = 0; i < count; i++) { CustomAttributeNamedArgumentKind kind = (CustomAttributeNamedArgumentKind)valueReader.ReadSerializationTypeCode(); if (kind != CustomAttributeNamedArgumentKind.Field && kind != CustomAttributeNamedArgumentKind.Property) { throw new BadImageFormatException(); } ArgumentTypeInfo info = DecodeNamedArgumentType(ref valueReader); string name = valueReader.ReadSerializedString(); CustomAttributeTypedArgument<TType> argument = DecodeArgument(ref valueReader, info); arguments.Add(new CustomAttributeNamedArgument<TType>(name, kind, argument.Type, argument.Value)); } return arguments.MoveToImmutable(); } private struct ArgumentTypeInfo { public TType Type; public TType ElementType; public SerializationTypeCode TypeCode; public SerializationTypeCode ElementTypeCode; } private ArgumentTypeInfo DecodeNamedArgumentType(ref BlobReader valueReader, bool isElementType = false) { var info = new ArgumentTypeInfo { TypeCode = valueReader.ReadSerializationTypeCode(), }; switch (info.TypeCode) { case SerializationTypeCode.Boolean: case SerializationTypeCode.Byte: case SerializationTypeCode.Char: case SerializationTypeCode.Double: case SerializationTypeCode.Int16: case SerializationTypeCode.Int32: case SerializationTypeCode.Int64: case SerializationTypeCode.SByte: case SerializationTypeCode.Single: case SerializationTypeCode.String: case SerializationTypeCode.UInt16: case SerializationTypeCode.UInt32: case SerializationTypeCode.UInt64: info.Type = _provider.GetPrimitiveType((PrimitiveTypeCode)info.TypeCode); break; case SerializationTypeCode.Type: info.Type = _provider.GetSystemType(); break; case SerializationTypeCode.TaggedObject: info.Type = _provider.GetPrimitiveType(PrimitiveTypeCode.Object); break; case SerializationTypeCode.SZArray: if (isElementType) { // jagged arrays are not allowed. throw new BadImageFormatException(); } var elementInfo = DecodeNamedArgumentType(ref valueReader, isElementType: true); info.ElementType = elementInfo.Type; info.ElementTypeCode = elementInfo.TypeCode; info.Type = _provider.GetSZArrayType(info.ElementType); break; case SerializationTypeCode.Enum: string typeName = valueReader.ReadSerializedString(); info.Type = _provider.GetTypeFromSerializedName(typeName); info.TypeCode = (SerializationTypeCode)_provider.GetUnderlyingEnumType(info.Type); break; default: throw new BadImageFormatException(); } return info; } private CustomAttributeTypedArgument<TType> DecodeArgument(ref BlobReader valueReader, ArgumentTypeInfo info) { var outer = info; if (info.TypeCode == SerializationTypeCode.TaggedObject) { info = DecodeNamedArgumentType(ref valueReader); } // PERF_TODO: https://github.com/dotnet/corefx/issues/6533 // Cache /reuse common arguments to avoid boxing (small integers, true, false). object value; switch (info.TypeCode) { case SerializationTypeCode.Boolean: value = valueReader.ReadBoolean(); break; case SerializationTypeCode.Byte: value = valueReader.ReadByte(); break; case SerializationTypeCode.Char: value = valueReader.ReadChar(); break; case SerializationTypeCode.Double: value = valueReader.ReadDouble(); break; case SerializationTypeCode.Int16: value = valueReader.ReadInt16(); break; case SerializationTypeCode.Int32: value = valueReader.ReadInt32(); break; case SerializationTypeCode.Int64: value = valueReader.ReadInt64(); break; case SerializationTypeCode.SByte: value = valueReader.ReadSByte(); break; case SerializationTypeCode.Single: value = valueReader.ReadSingle(); break; case SerializationTypeCode.UInt16: value = valueReader.ReadUInt16(); break; case SerializationTypeCode.UInt32: value = valueReader.ReadUInt32(); break; case SerializationTypeCode.UInt64: value = valueReader.ReadUInt64(); break; case SerializationTypeCode.String: value = valueReader.ReadSerializedString(); break; case SerializationTypeCode.Type: string typeName = valueReader.ReadSerializedString(); value = _provider.GetTypeFromSerializedName(typeName); break; case SerializationTypeCode.SZArray: value = DecodeArrayArgument(ref valueReader, info); break; default: throw new BadImageFormatException(); } if (_provideBoxingTypeInfo && outer.TypeCode == SerializationTypeCode.TaggedObject) { return new CustomAttributeTypedArgument<TType>(outer.Type, new CustomAttributeTypedArgument<TType>(info.Type, value)); } return new CustomAttributeTypedArgument<TType>(info.Type, value); } private ImmutableArray<CustomAttributeTypedArgument<TType>>? DecodeArrayArgument(ref BlobReader blobReader, ArgumentTypeInfo info) { int count = blobReader.ReadInt32(); if (count == -1) { return null; } if (count == 0) { return ImmutableArray<CustomAttributeTypedArgument<TType>>.Empty; } if (count < 0) { throw new BadImageFormatException(); } var elementInfo = new ArgumentTypeInfo { Type = info.ElementType, TypeCode = info.ElementTypeCode, }; var array = ImmutableArray.CreateBuilder<CustomAttributeTypedArgument<TType>>(count); for (int i = 0; i < count; i++) { array.Add(DecodeArgument(ref blobReader, elementInfo)); } return array.MoveToImmutable(); } } }
ILSpy/ICSharpCode.Decompiler/Metadata/CustomAttributeDecoder.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/CustomAttributeDecoder.cs", "repo_id": "ILSpy", "token_count": 2503 }
238
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace LightJson.Serialization { using System.IO; using ErrorType = JsonParseException.ErrorType; /// <summary> /// Represents a text scanner that reads one character at a time. /// </summary> internal sealed class TextScanner { private TextReader reader; private TextPosition position; /// <summary> /// Initializes a new instance of the <see cref="TextScanner"/> class. /// </summary> /// <param name="reader">The TextReader to read the text.</param> public TextScanner(TextReader reader) { this.reader = reader; } /// <summary> /// Gets the position of the scanner within the text. /// </summary> /// <value>The position of the scanner within the text.</value> public TextPosition Position { get { return this.position; } } /// <summary> /// Reads the next character in the stream without changing the current position. /// </summary> /// <returns>The next character in the stream.</returns> public char Peek() => (char)this.Peek(throwAtEndOfFile: true); /// <summary> /// Reads the next character in the stream without changing the current position. /// </summary> /// <param name="throwAtEndOfFile"><see langword="true"/> to throw an exception if the end of the file is /// reached; otherwise, <see langword="false"/>.</param> /// <returns>The next character in the stream, or -1 if the end of the file is reached with /// <paramref name="throwAtEndOfFile"/> set to <see langword="false"/>.</returns> public int Peek(bool throwAtEndOfFile) { var next = this.reader.Peek(); if (next == -1 && throwAtEndOfFile) { throw new JsonParseException( ErrorType.IncompleteMessage, this.position); } else { return next; } } /// <summary> /// Reads the next character in the stream, advancing the text position. /// </summary> /// <returns>The next character in the stream.</returns> public char Read() { var next = this.reader.Read(); if (next == -1) { throw new JsonParseException( ErrorType.IncompleteMessage, this.position); } else { if (next == '\n') { this.position.Line += 1; this.position.Column = 0; } else { this.position.Column += 1; } return (char)next; } } /// <summary> /// Advances the scanner to next non-whitespace character. /// </summary> public void SkipWhitespace() { while (true) { char next = this.Peek(); if (char.IsWhiteSpace(next)) { this.Read(); continue; } else if (next == '/') { this.SkipComment(); continue; } else { break; } } } /// <summary> /// Verifies that the given character matches the next character in the stream. /// If the characters do not match, an exception will be thrown. /// </summary> /// <param name="next">The expected character.</param> public void Assert(char next) { var errorPosition = this.position; if (this.Read() != next) { throw new JsonParseException( string.Format("Parser expected '{0}'", next), ErrorType.InvalidOrUnexpectedCharacter, errorPosition); } } /// <summary> /// Verifies that the given string matches the next characters in the stream. /// If the strings do not match, an exception will be thrown. /// </summary> /// <param name="next">The expected string.</param> public void Assert(string next) { for (var i = 0; i < next.Length; i += 1) { this.Assert(next[i]); } } private void SkipComment() { // First character is the first slash this.Read(); switch (this.Peek()) { case '/': this.SkipLineComment(); return; case '*': this.SkipBlockComment(); return; default: throw new JsonParseException( string.Format("Parser expected '{0}'", this.Peek()), ErrorType.InvalidOrUnexpectedCharacter, this.position); } } private void SkipLineComment() { // First character is the second '/' of the opening '//' this.Read(); while (true) { switch (this.reader.Peek()) { case '\n': // Reached the end of the line this.Read(); return; case -1: // Reached the end of the file return; default: this.Read(); continue; } } } private void SkipBlockComment() { // First character is the '*' of the opening '/*' this.Read(); bool foundStar = false; while (true) { switch (this.reader.Peek()) { case '*': this.Read(); foundStar = true; continue; case '/': this.Read(); if (foundStar) { return; } else { foundStar = false; continue; } case -1: // Reached the end of the file return; default: this.Read(); foundStar = false; continue; } } } } }
ILSpy/ICSharpCode.Decompiler/Metadata/LightJson/Serialization/TextScanner.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/LightJson/Serialization/TextScanner.cs", "repo_id": "ILSpy", "token_count": 2081 }
239
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } }
ILSpy/ICSharpCode.Decompiler/NRTAttributes.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/NRTAttributes.cs", "repo_id": "ILSpy", "token_count": 215 }
240
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Linq; using ICSharpCode.Decompiler.Semantics; namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// Helper methods for COM. /// </summary> public static class ComHelper { /// <summary> /// Gets whether the specified type is imported from COM. /// </summary> public static bool IsComImport(ITypeDefinition typeDefinition) { return typeDefinition != null && typeDefinition.Kind == TypeKind.Interface && typeDefinition.HasAttribute(KnownAttribute.ComImport); } /// <summary> /// Gets the CoClass of the specified COM interface. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Co", Justification = "Consistent with CoClassAttribute")] public static IType GetCoClass(ITypeDefinition typeDefinition) { if (typeDefinition == null) return SpecialType.UnknownType; var coClassAttribute = typeDefinition.GetAttribute(KnownAttribute.CoClass); if (coClassAttribute != null && coClassAttribute.FixedArguments.Length == 1) { if (coClassAttribute.FixedArguments[0].Value is IType ty) return ty; } return SpecialType.UnknownType; } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/ComHelper.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/ComHelper.cs", "repo_id": "ILSpy", "token_count": 704 }
241
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #nullable enable using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// Represents a method, constructor, destructor or operator. /// </summary> public interface IMethod : IParameterizedMember { /// <summary> /// Gets the attributes associated with the return type. (e.g. [return: MarshalAs(...)]) /// </summary> /// <remarks> /// Does not include inherited attributes. /// </remarks> IEnumerable<IAttribute> GetReturnTypeAttributes(); /// <summary> /// Gets whether the return type is 'ref readonly'. /// </summary> bool ReturnTypeIsRefReadOnly { get; } /// <summary> /// Gets whether this method may only be called on fresh instances. /// Used with C# 9 `init;` property setters. /// </summary> bool IsInitOnly { get; } /// <summary> /// Gets whether the method accepts the 'this' reference as ref readonly. /// This can be either because the method is C# 8.0 'readonly', or because it is within a C# 7.2 'readonly struct' /// </summary> bool ThisIsRefReadOnly { get; } /// <summary> /// Gets the type parameters of this method; or an empty list if the method is not generic. /// </summary> IReadOnlyList<ITypeParameter> TypeParameters { get; } /// <summary> /// Gets the type arguments passed to this method. /// If the method is generic but not parameterized yet, this property returns the type parameters, /// as if the method was parameterized with its own type arguments (<c>void M&lt;T&gt;() { M&lt;T&gt;(); }</c>). /// </summary> IReadOnlyList<IType> TypeArguments { get; } bool IsExtensionMethod { get; } bool IsLocalFunction { get; } bool IsConstructor { get; } bool IsDestructor { get; } bool IsOperator { get; } /// <summary> /// Gets whether the method has a body. /// This property returns <c>false</c> for <c>abstract</c> or <c>extern</c> methods, /// or for <c>partial</c> methods without implementation. /// </summary> bool HasBody { get; } /// <summary> /// Gets whether the method is a property/event accessor. /// </summary> [MemberNotNullWhen(true, nameof(AccessorOwner))] bool IsAccessor { get; } /// <summary> /// If this method is an accessor, returns the corresponding property/event. /// Otherwise, returns null. /// </summary> IMember? AccessorOwner { get; } /// <summary> /// Gets the kind of accessor this is. /// </summary> MethodSemanticsAttributes AccessorKind { get; } /// <summary> /// If this method is reduced from an extension method or a local function returns the original method, <c>null</c> otherwise. /// A reduced method doesn't contain the extension method parameter. That means that it has one parameter less than its definition. /// A local function doesn't contain compiler-generated method parameters at the end. /// </summary> IMethod? ReducedFrom { get; } /// <summary> /// Specializes this method with the given substitution. /// If this method is already specialized, the new substitution is composed with the existing substition. /// </summary> new IMethod Specialize(TypeParameterSubstitution substitution); } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/IMethod.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/IMethod.cs", "repo_id": "ILSpy", "token_count": 1293 }
242
// 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.Globalization; using System.Linq; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.TypeSystem.Implementation { public abstract class AbstractTypeParameter : ITypeParameter, ICompilationProvider { readonly ICompilation compilation; readonly SymbolKind ownerType; readonly IEntity owner; readonly int index; readonly string name; readonly VarianceModifier variance; protected AbstractTypeParameter(IEntity owner, int index, string name, VarianceModifier variance) { if (owner == null) throw new ArgumentNullException(nameof(owner)); this.owner = owner; this.compilation = owner.Compilation; this.ownerType = owner.SymbolKind; this.index = index; this.name = name ?? ((this.OwnerType == SymbolKind.Method ? "!!" : "!") + index.ToString(CultureInfo.InvariantCulture)); this.variance = variance; } protected AbstractTypeParameter(ICompilation compilation, SymbolKind ownerType, int index, string name, VarianceModifier variance) { if (compilation == null) throw new ArgumentNullException(nameof(compilation)); this.compilation = compilation; this.ownerType = ownerType; this.index = index; this.name = name ?? ((this.OwnerType == SymbolKind.Method ? "!!" : "!") + index.ToString(CultureInfo.InvariantCulture)); this.variance = variance; } SymbolKind ISymbol.SymbolKind { get { return SymbolKind.TypeParameter; } } public SymbolKind OwnerType { get { return ownerType; } } public IEntity Owner { get { return owner; } } public int Index { get { return index; } } public abstract IEnumerable<IAttribute> GetAttributes(); public VarianceModifier Variance { get { return variance; } } public ICompilation Compilation { get { return compilation; } } volatile IType effectiveBaseClass; public IType EffectiveBaseClass { get { if (effectiveBaseClass == null) { // protect against cyclic type parameters using (var busyLock = BusyManager.Enter(this)) { if (!busyLock.Success) return SpecialType.UnknownType; // don't cache this error effectiveBaseClass = CalculateEffectiveBaseClass(); } } return effectiveBaseClass; } } IType CalculateEffectiveBaseClass() { if (HasValueTypeConstraint) return this.Compilation.FindType(KnownTypeCode.ValueType); List<IType> classTypeConstraints = new List<IType>(); foreach (IType constraint in this.DirectBaseTypes) { if (constraint.Kind == TypeKind.Class) { classTypeConstraints.Add(constraint); } else if (constraint.Kind == TypeKind.TypeParameter) { IType baseClass = ((ITypeParameter)constraint).EffectiveBaseClass; if (baseClass.Kind == TypeKind.Class) classTypeConstraints.Add(baseClass); } } if (classTypeConstraints.Count == 0) return this.Compilation.FindType(KnownTypeCode.Object); // Find the derived-most type in the resulting set: IType result = classTypeConstraints[0]; for (int i = 1; i < classTypeConstraints.Count; i++) { if (classTypeConstraints[i].GetDefinition().IsDerivedFrom(result.GetDefinition())) result = classTypeConstraints[i]; } return result; } IReadOnlyCollection<IType> effectiveInterfaceSet; public IReadOnlyCollection<IType> EffectiveInterfaceSet { get { var result = LazyInit.VolatileRead(ref effectiveInterfaceSet); if (result != null) { return result; } else { // protect against cyclic type parameters using (var busyLock = BusyManager.Enter(this)) { if (!busyLock.Success) return EmptyList<IType>.Instance; // don't cache this error return LazyInit.GetOrSet(ref effectiveInterfaceSet, CalculateEffectiveInterfaceSet()); } } } } IReadOnlyCollection<IType> CalculateEffectiveInterfaceSet() { HashSet<IType> result = new HashSet<IType>(); foreach (IType constraint in this.DirectBaseTypes) { if (constraint.Kind == TypeKind.Interface) { result.Add(constraint); } else if (constraint.Kind == TypeKind.TypeParameter) { result.UnionWith(((ITypeParameter)constraint).EffectiveInterfaceSet); } } return result.ToArray(); } public abstract bool HasDefaultConstructorConstraint { get; } public abstract bool HasReferenceTypeConstraint { get; } public abstract bool HasValueTypeConstraint { get; } public abstract bool HasUnmanagedConstraint { get; } public abstract Nullability NullabilityConstraint { get; } public TypeKind Kind { get { return TypeKind.TypeParameter; } } public bool? IsReferenceType { get { if (this.HasValueTypeConstraint) return false; if (this.HasReferenceTypeConstraint) return true; // A type parameter is known to be a reference type if it has the reference type constraint // or its effective base class is not object or System.ValueType. IType effectiveBaseClass = this.EffectiveBaseClass; if (effectiveBaseClass.Kind == TypeKind.Class || effectiveBaseClass.Kind == TypeKind.Delegate) { ITypeDefinition effectiveBaseClassDef = effectiveBaseClass.GetDefinition(); if (effectiveBaseClassDef != null) { switch (effectiveBaseClassDef.KnownTypeCode) { case KnownTypeCode.Object: case KnownTypeCode.ValueType: case KnownTypeCode.Enum: return null; } } return true; } else if (effectiveBaseClass.Kind == TypeKind.Struct || effectiveBaseClass.Kind == TypeKind.Enum) { return false; } return null; } } bool IType.IsByRefLike => false; Nullability IType.Nullability => Nullability.Oblivious; public IType ChangeNullability(Nullability nullability) { if (nullability == Nullability.Oblivious) return this; else return new NullabilityAnnotatedTypeParameter(this, nullability); } IType IType.DeclaringType { get { return null; } } int IType.TypeParameterCount { get { return 0; } } IReadOnlyList<ITypeParameter> IType.TypeParameters { get { return EmptyList<ITypeParameter>.Instance; } } IReadOnlyList<IType> IType.TypeArguments { get { return EmptyList<IType>.Instance; } } public IEnumerable<IType> DirectBaseTypes { get { return TypeConstraints.Select(t => t.Type); } } public abstract IReadOnlyList<TypeConstraint> TypeConstraints { get; } public string Name { get { return name; } } string INamedElement.Namespace { get { return string.Empty; } } string INamedElement.FullName { get { return name; } } public string ReflectionName { get { return (this.OwnerType == SymbolKind.Method ? "``" : "`") + index.ToString(CultureInfo.InvariantCulture); } } ITypeDefinition IType.GetDefinition() { return null; } ITypeDefinitionOrUnknown IType.GetDefinitionOrUnknown() { return null; } public IType AcceptVisitor(TypeVisitor visitor) { return visitor.VisitTypeParameter(this); } public IType VisitChildren(TypeVisitor visitor) { return this; } 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; } public IEnumerable<IMethod> GetConstructors(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { if (this.HasDefaultConstructorConstraint || this.HasValueTypeConstraint) { var dummyCtor = FakeMethod.CreateDummyConstructor(compilation, this); if (filter == null || filter(dummyCtor)) { return new[] { dummyCtor }; } } return EmptyList<IMethod>.Instance; } else { return GetMembersHelper.GetConstructors(this, filter, options); } } public IEnumerable<IMethod> GetMethods(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList<IMethod>.Instance; else return GetMembersHelper.GetMethods(this, FilterNonStatic(filter), options); } public IEnumerable<IMethod> GetMethods(IReadOnlyList<IType> typeArguments, Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList<IMethod>.Instance; else return GetMembersHelper.GetMethods(this, typeArguments, FilterNonStatic(filter), options); } public IEnumerable<IProperty> GetProperties(Predicate<IProperty> filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList<IProperty>.Instance; else return GetMembersHelper.GetProperties(this, FilterNonStatic(filter), options); } public IEnumerable<IField> GetFields(Predicate<IField> filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList<IField>.Instance; else return GetMembersHelper.GetFields(this, FilterNonStatic(filter), options); } public IEnumerable<IEvent> GetEvents(Predicate<IEvent> filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList<IEvent>.Instance; else return GetMembersHelper.GetEvents(this, FilterNonStatic(filter), options); } public IEnumerable<IMember> GetMembers(Predicate<IMember> filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList<IMember>.Instance; else return GetMembersHelper.GetMembers(this, FilterNonStatic(filter), options); } public IEnumerable<IMethod> GetAccessors(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList<IMethod>.Instance; else return GetMembersHelper.GetAccessors(this, FilterNonStatic(filter), options); } TypeParameterSubstitution IType.GetSubstitution() { return TypeParameterSubstitution.Identity; } static Predicate<T> FilterNonStatic<T>(Predicate<T> filter) where T : class, IMember { return member => (!member.IsStatic || member.SymbolKind == SymbolKind.Operator || member.IsVirtual) && (filter == null || filter(member)); } public sealed override bool Equals(object obj) { return Equals(obj as IType); } public override int GetHashCode() { return base.GetHashCode(); } public virtual bool Equals(IType other) { return this == other; // use reference equality for type parameters } public override string ToString() { return this.ReflectionName; } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs", "repo_id": "ILSpy", "token_count": 4406 }
243
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.TypeSystem.Implementation { /// <summary> /// Cache for KnownTypeReferences. /// </summary> sealed class KnownTypeCache { readonly ICompilation compilation; readonly IType[] knownTypes = new IType[KnownTypeReference.KnownTypeCodeCount]; public KnownTypeCache(ICompilation compilation) { this.compilation = compilation; } public IType FindType(KnownTypeCode typeCode) { IType type = LazyInit.VolatileRead(ref knownTypes[(int)typeCode]); if (type != null) { return type; } return LazyInit.GetOrSet(ref knownTypes[(int)typeCode], SearchType(typeCode)); } IType SearchType(KnownTypeCode typeCode) { KnownTypeReference typeRef = KnownTypeReference.Get(typeCode); if (typeRef == null) return SpecialType.UnknownType; var typeName = new TopLevelTypeName(typeRef.Namespace, typeRef.Name, typeRef.TypeParameterCount); foreach (IModule asm in compilation.Modules) { var typeDef = asm.GetTypeDefinition(typeName); if (typeDef != null) return typeDef; } return new UnknownType(typeName); } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/KnownTypeCache.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/KnownTypeCache.cs", "repo_id": "ILSpy", "token_count": 712 }
244
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.TypeSystem.Implementation { /// <summary> /// Represents a specialized IEvent (event after type substitution). /// </summary> public class SpecializedEvent : SpecializedMember, IEvent { public static IEvent Create(IEvent ev, TypeParameterSubstitution substitution) { if (TypeParameterSubstitution.Identity.Equals(substitution) || ev.DeclaringType.TypeParameterCount == 0) { return ev; } if (substitution.MethodTypeArguments != null && substitution.MethodTypeArguments.Count > 0) substitution = new TypeParameterSubstitution(substitution.ClassTypeArguments, EmptyList<IType>.Instance); return new SpecializedEvent(ev, substitution); } readonly IEvent eventDefinition; public SpecializedEvent(IEvent eventDefinition, TypeParameterSubstitution substitution) : base(eventDefinition) { this.eventDefinition = eventDefinition; AddSubstitution(substitution); } public bool CanAdd { get { return eventDefinition.CanAdd; } } public bool CanRemove { get { return eventDefinition.CanRemove; } } public bool CanInvoke { get { return eventDefinition.CanInvoke; } } IMethod addAccessor, removeAccessor, invokeAccessor; public IMethod AddAccessor { get { return WrapAccessor(ref this.addAccessor, eventDefinition.AddAccessor); } } public IMethod RemoveAccessor { get { return WrapAccessor(ref this.removeAccessor, eventDefinition.RemoveAccessor); } } public IMethod InvokeAccessor { get { return WrapAccessor(ref this.invokeAccessor, eventDefinition.InvokeAccessor); } } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedEvent.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedEvent.cs", "repo_id": "ILSpy", "token_count": 832 }
245
// 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. #nullable enable using ICSharpCode.Decompiler.TypeSystem.Implementation; namespace ICSharpCode.Decompiler.TypeSystem { sealed class NormalizeTypeVisitor : TypeVisitor { /// <summary> /// NormalizeTypeVisitor that does not normalize type parameters, /// but performs type erasure (object->dynamic; tuple->underlying type). /// </summary> internal static readonly NormalizeTypeVisitor TypeErasure = new NormalizeTypeVisitor { ReplaceClassTypeParametersWithDummy = false, ReplaceMethodTypeParametersWithDummy = false, DynamicAndObject = true, IntPtrToNInt = true, TupleToUnderlyingType = true, RemoveModOpt = true, RemoveModReq = true, RemoveNullability = true, }; internal static readonly NormalizeTypeVisitor IgnoreNullabilityAndTuples = new NormalizeTypeVisitor { ReplaceClassTypeParametersWithDummy = false, ReplaceMethodTypeParametersWithDummy = false, DynamicAndObject = false, IntPtrToNInt = false, TupleToUnderlyingType = true, RemoveModOpt = true, RemoveModReq = true, RemoveNullability = true, }; internal static readonly NormalizeTypeVisitor IgnoreNullability = new NormalizeTypeVisitor { ReplaceClassTypeParametersWithDummy = false, ReplaceMethodTypeParametersWithDummy = false, DynamicAndObject = false, IntPtrToNInt = false, TupleToUnderlyingType = false, RemoveModOpt = true, RemoveModReq = true, RemoveNullability = true, }; public bool EquivalentTypes(IType a, IType b) { a = a.AcceptVisitor(this); b = b.AcceptVisitor(this); return a.Equals(b); } public bool RemoveModOpt = true; public bool RemoveModReq = true; public bool ReplaceClassTypeParametersWithDummy = true; public bool ReplaceMethodTypeParametersWithDummy = true; public bool DynamicAndObject = true; public bool IntPtrToNInt = true; public bool TupleToUnderlyingType = true; public bool RemoveNullability = true; public override IType VisitTypeParameter(ITypeParameter type) { if (type.OwnerType == SymbolKind.Method && ReplaceMethodTypeParametersWithDummy) { return DummyTypeParameter.GetMethodTypeParameter(type.Index); } else if (type.OwnerType == SymbolKind.TypeDefinition && ReplaceClassTypeParametersWithDummy) { return DummyTypeParameter.GetClassTypeParameter(type.Index); } else if (RemoveNullability && type is NullabilityAnnotatedTypeParameter natp) { return natp.TypeWithoutAnnotation.AcceptVisitor(this); } else { return base.VisitTypeParameter(type); } } public override IType VisitTypeDefinition(ITypeDefinition type) { switch (type.KnownTypeCode) { case KnownTypeCode.Object when DynamicAndObject: // Instead of normalizing dynamic->object, // we do this the opposite direction, so that we don't need a compilation to find the object type. if (RemoveNullability) return SpecialType.Dynamic; else return SpecialType.Dynamic.ChangeNullability(type.Nullability); case KnownTypeCode.IntPtr when IntPtrToNInt: return SpecialType.NInt; case KnownTypeCode.UIntPtr when IntPtrToNInt: return SpecialType.NUInt; } return base.VisitTypeDefinition(type); } public override IType VisitTupleType(TupleType type) { if (TupleToUnderlyingType) { return type.UnderlyingType.AcceptVisitor(this); } else { return base.VisitTupleType(type); } } public override IType VisitNullabilityAnnotatedType(NullabilityAnnotatedType type) { if (RemoveNullability) return type.TypeWithoutAnnotation.AcceptVisitor(this); else return base.VisitNullabilityAnnotatedType(type); } public override IType VisitArrayType(ArrayType type) { if (RemoveNullability) return base.VisitArrayType(type).ChangeNullability(Nullability.Oblivious); else return base.VisitArrayType(type); } public override IType VisitModOpt(ModifiedType type) { if (RemoveModOpt) { return type.ElementType.AcceptVisitor(this); } else { return base.VisitModOpt(type); } } public override IType VisitModReq(ModifiedType type) { if (RemoveModReq) { return type.ElementType.AcceptVisitor(this); } else { return base.VisitModReq(type); } } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/NormalizeTypeVisitor.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/NormalizeTypeVisitor.cs", "repo_id": "ILSpy", "token_count": 1831 }
246
// 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.Immutable; using System.Reflection.Metadata.Ecma335; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem.Implementation; using SRM = System.Reflection.Metadata; namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// Allows decoding signatures using decompiler types. /// </summary> sealed class TypeProvider : ICompilationProvider, SRM.ISignatureTypeProvider<IType, GenericContext>, SRM.ICustomAttributeTypeProvider<IType> { readonly MetadataModule module; readonly ICompilation compilation; public TypeProvider(MetadataModule module) { this.module = module; this.compilation = module.Compilation; } public TypeProvider(ICompilation compilation) { this.compilation = compilation; } public ICompilation Compilation => compilation; public IType GetArrayType(IType elementType, SRM.ArrayShape shape) { return new ArrayType(compilation, elementType, shape.Rank); } public IType GetByReferenceType(IType elementType) { return new ByReferenceType(elementType); } public IType GetFunctionPointerType(SRM.MethodSignature<IType> signature) { if (signature.Header.IsInstance) { // pointers to member functions are not supported even in C# 9 return compilation.FindType(KnownTypeCode.IntPtr); } return FunctionPointerType.FromSignature(signature, module); } public IType GetGenericInstantiation(IType genericType, ImmutableArray<IType> typeArguments) { int tpc = genericType.TypeParameterCount; if (tpc == 0 || tpc != typeArguments.Length) { // This can occur when the genericType is from another assembly, // doesn't have the typical `1 suffix, and that other assembly is not loaded. return genericType; } return new ParameterizedType(genericType, typeArguments); } public IType GetGenericMethodParameter(GenericContext genericContext, int index) { return genericContext.GetMethodTypeParameter(index); } public IType GetGenericTypeParameter(GenericContext genericContext, int index) { return genericContext.GetClassTypeParameter(index); } public IType GetModifiedType(IType modifier, IType unmodifiedType, bool isRequired) { return new ModifiedType(modifier, unmodifiedType, isRequired); } public IType GetPinnedType(IType elementType) { return new PinnedType(elementType); } public IType GetPointerType(IType elementType) { return new PointerType(elementType); } public IType GetPrimitiveType(SRM.PrimitiveTypeCode typeCode) { return compilation.FindType(typeCode.ToKnownTypeCode()); } public IType GetSystemType() { return compilation.FindType(KnownTypeCode.Type); } public IType GetSZArrayType(IType elementType) { return new ArrayType(compilation, elementType); } bool? IsReferenceType(SRM.MetadataReader reader, SRM.EntityHandle handle, byte rawTypeKind) { switch (reader.ResolveSignatureTypeKind(handle, rawTypeKind)) { case SRM.SignatureTypeKind.ValueType: return false; case SRM.SignatureTypeKind.Class: return true; default: return null; } } public IType GetTypeFromDefinition(SRM.MetadataReader reader, SRM.TypeDefinitionHandle handle, byte rawTypeKind) { ITypeDefinition td = module?.GetDefinition(handle); if (td != null) return td; bool? isReferenceType = IsReferenceType(reader, handle, rawTypeKind); return new UnknownType(handle.GetFullTypeName(reader), isReferenceType); } public IType GetTypeFromReference(SRM.MetadataReader reader, SRM.TypeReferenceHandle handle, byte rawTypeKind) { IModule resolvedModule = module?.GetDeclaringModule(handle); var fullTypeName = handle.GetFullTypeName(reader); IType type; if (resolvedModule != null) { type = resolvedModule.GetTypeDefinition(fullTypeName); } else { type = GetClassTypeReference.ResolveInAllAssemblies(compilation, in fullTypeName); } return type ?? new UnknownType(fullTypeName, IsReferenceType(reader, handle, rawTypeKind)); } public IType GetTypeFromSerializedName(string name) { if (name == null) { return null; } try { return ReflectionHelper.ParseReflectionName(name) .Resolve(module != null ? new SimpleTypeResolveContext(module) : new SimpleTypeResolveContext(compilation)); } catch (ReflectionNameParseException ex) { throw new BadImageFormatException($"Invalid type name: \"{name}\": {ex.Message}"); } } public IType GetTypeFromSpecification(SRM.MetadataReader reader, GenericContext genericContext, SRM.TypeSpecificationHandle handle, byte rawTypeKind) { return reader.GetTypeSpecification(handle).DecodeSignature<IType, GenericContext>(this, genericContext); } public SRM.PrimitiveTypeCode GetUnderlyingEnumType(IType type) { var def = type.GetEnumUnderlyingType().GetDefinition(); if (def == null) throw new EnumUnderlyingTypeResolveException(); return def.KnownTypeCode.ToPrimitiveTypeCode(); } public bool IsSystemType(IType type) { return type.IsKnownType(KnownTypeCode.Type); } } }
ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs", "repo_id": "ILSpy", "token_count": 2062 }
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. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text.RegularExpressions; namespace ICSharpCode.Decompiler.Util { #if DEBUG /// <summary> /// GraphViz graph. /// </summary> sealed class GraphVizGraph { List<GraphVizNode> nodes = new List<GraphVizNode>(); List<GraphVizEdge> edges = new List<GraphVizEdge>(); public string? rankdir; public string? Title; public void AddEdge(GraphVizEdge edge) { edges.Add(edge); } public void AddNode(GraphVizNode node) { nodes.Add(node); } public void Save(string fileName) { using (StreamWriter writer = new StreamWriter(fileName)) Save(writer); } public void Show() { Show(null); } public void Show(string? name) { if (name == null) name = Title; if (name != null) foreach (char c in Path.GetInvalidFileNameChars()) name = name.Replace(c, '-'); string fileName = name != null ? Path.Combine(Path.GetTempPath(), name) : Path.GetTempFileName(); Save(fileName + ".gv"); Process.Start("dot", "\"" + fileName + ".gv\" -Tpng -o \"" + fileName + ".png\"").WaitForExit(); Process.Start(fileName + ".png"); } static string Escape(string text) { if (Regex.IsMatch(text, @"^[\w\d]+$")) { return text; } else { return "\"" + text.Replace("\\", "\\\\").Replace("\r", "").Replace("\n", "\\n").Replace("\"", "\\\"") + "\""; } } static void WriteGraphAttribute(TextWriter writer, string name, string? value) { if (value != null) writer.WriteLine("{0}={1};", name, Escape(value)); } internal static void WriteAttribute(TextWriter writer, string name, double? value, ref bool isFirst) { if (value != null) { WriteAttribute(writer, name, value.Value.ToString(CultureInfo.InvariantCulture), ref isFirst); } } internal static void WriteAttribute(TextWriter writer, string name, bool? value, ref bool isFirst) { if (value != null) { WriteAttribute(writer, name, value.Value ? "true" : "false", ref isFirst); } } internal static void WriteAttribute(TextWriter writer, string name, string? value, ref bool isFirst) { if (value != null) { if (isFirst) isFirst = false; else writer.Write(','); writer.Write("{0}={1}", name, Escape(value)); } } public void Save(TextWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteLine("digraph G {"); writer.WriteLine("node [fontsize = 16];"); WriteGraphAttribute(writer, "rankdir", rankdir); foreach (GraphVizNode node in nodes) { node.Save(writer); } foreach (GraphVizEdge edge in edges) { edge.Save(writer); } writer.WriteLine("}"); } } sealed class GraphVizEdge { public readonly string Source, Target; /// <summary>edge stroke color</summary> public string? color; /// <summary>use edge to affect node ranking</summary> public bool? constraint; public string? label; public string? style; /// <summary>point size of label</summary> public int? fontsize; public GraphVizEdge(string source, string target) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); this.Source = source; this.Target = target; } public GraphVizEdge(int source, int target) { this.Source = source.ToString(CultureInfo.InvariantCulture); this.Target = target.ToString(CultureInfo.InvariantCulture); } public void Save(TextWriter writer) { writer.Write("{0} -> {1} [", Source, Target); bool isFirst = true; GraphVizGraph.WriteAttribute(writer, "label", label, ref isFirst); GraphVizGraph.WriteAttribute(writer, "style", style, ref isFirst); GraphVizGraph.WriteAttribute(writer, "fontsize", fontsize, ref isFirst); GraphVizGraph.WriteAttribute(writer, "color", color, ref isFirst); GraphVizGraph.WriteAttribute(writer, "constraint", constraint, ref isFirst); writer.WriteLine("];"); } } sealed class GraphVizNode { public readonly string ID; public string? label; public string? labelloc; /// <summary>point size of label</summary> public int? fontsize; /// <summary>minimum height in inches</summary> public double? height; /// <summary>space around label</summary> public string? margin; /// <summary>node shape</summary> public string? shape; public GraphVizNode(string id) { if (id == null) throw new ArgumentNullException(nameof(id)); this.ID = id; } public GraphVizNode(int id) { this.ID = id.ToString(CultureInfo.InvariantCulture); } public void Save(TextWriter writer) { writer.Write(ID); writer.Write(" ["); bool isFirst = true; GraphVizGraph.WriteAttribute(writer, "label", label, ref isFirst); GraphVizGraph.WriteAttribute(writer, "labelloc", labelloc, ref isFirst); GraphVizGraph.WriteAttribute(writer, "fontsize", fontsize, ref isFirst); GraphVizGraph.WriteAttribute(writer, "margin", margin, ref isFirst); GraphVizGraph.WriteAttribute(writer, "shape", shape, ref isFirst); writer.WriteLine("];"); } } #endif }
ILSpy/ICSharpCode.Decompiler/Util/GraphVizGraph.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Util/GraphVizGraph.cs", "repo_id": "ILSpy", "token_count": 2289 }
248
#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection.PortableExecutable; namespace ICSharpCode.Decompiler.Util { /// <summary> /// Represents win32 resources /// </summary> public static class Win32Resources { /// <summary> /// Reads win32 resource root directory /// </summary> /// <param name="pe"></param> /// <returns></returns> public static unsafe Win32ResourceDirectory? ReadWin32Resources(this PEReader pe) { if (pe == null) { throw new ArgumentNullException(nameof(pe)); } int rva = pe.PEHeaders.PEHeader?.ResourceTableDirectory.RelativeVirtualAddress ?? 0; if (rva == 0) return null; byte* pRoot = pe.GetSectionData(rva).Pointer; return new Win32ResourceDirectory(pe, pRoot, 0, new Win32ResourceName("Root")); } public static Win32ResourceDirectory? Find(this Win32ResourceDirectory root, Win32ResourceName type) { if (root is null) throw new ArgumentNullException(nameof(root)); if (!root.Name.HasName || root.Name.Name != "Root") throw new ArgumentOutOfRangeException(nameof(root)); if (type is null) throw new ArgumentNullException(nameof(type)); return root.FindDirectory(type); } public static Win32ResourceDirectory? Find(this Win32ResourceDirectory root, Win32ResourceName type, Win32ResourceName name) { if (root is null) throw new ArgumentNullException(nameof(root)); if (!root.Name.HasName || root.Name.Name != "Root") throw new ArgumentOutOfRangeException(nameof(root)); if (type is null) throw new ArgumentNullException(nameof(type)); if (name is null) throw new ArgumentNullException(nameof(name)); return root.FindDirectory(type)?.FindDirectory(name); } public static Win32ResourceData? Find(this Win32ResourceDirectory root, Win32ResourceName type, Win32ResourceName name, Win32ResourceName langId) { if (root is null) throw new ArgumentNullException(nameof(root)); if (!root.Name.HasName || root.Name.Name != "Root") throw new ArgumentOutOfRangeException(nameof(root)); if (type is null) throw new ArgumentNullException(nameof(type)); if (name is null) throw new ArgumentNullException(nameof(name)); if (langId is null) throw new ArgumentNullException(nameof(langId)); return root.FindDirectory(type)?.FindDirectory(name)?.FindData(langId); } } [DebuggerDisplay("Directory: {Name}")] public sealed class Win32ResourceDirectory { #region Structure public uint Characteristics { get; } public uint TimeDateStamp { get; } public ushort MajorVersion { get; } public ushort MinorVersion { get; } public ushort NumberOfNamedEntries { get; } public ushort NumberOfIdEntries { get; } #endregion public Win32ResourceName Name { get; } public IList<Win32ResourceDirectory> Directories { get; } public IList<Win32ResourceData> Datas { get; } internal unsafe Win32ResourceDirectory(PEReader pe, byte* pRoot, int offset, Win32ResourceName name) { var p = (IMAGE_RESOURCE_DIRECTORY*)(pRoot + offset); Characteristics = p->Characteristics; TimeDateStamp = p->TimeDateStamp; MajorVersion = p->MajorVersion; MinorVersion = p->MinorVersion; NumberOfNamedEntries = p->NumberOfNamedEntries; NumberOfIdEntries = p->NumberOfIdEntries; Name = name; Directories = new List<Win32ResourceDirectory>(); Datas = new List<Win32ResourceData>(); var pEntries = (IMAGE_RESOURCE_DIRECTORY_ENTRY*)(p + 1); int total = NumberOfNamedEntries + NumberOfIdEntries; for (int i = 0; i < total; i++) { var pEntry = pEntries + i; name = new Win32ResourceName(pRoot, pEntry); if ((pEntry->OffsetToData & 0x80000000) == 0) Datas.Add(new Win32ResourceData(pe, pRoot, (int)pEntry->OffsetToData, name)); else Directories.Add(new Win32ResourceDirectory(pe, pRoot, (int)(pEntry->OffsetToData & 0x7FFFFFFF), name)); } } static unsafe string ReadString(byte* pRoot, int offset) { var pString = (IMAGE_RESOURCE_DIRECTORY_STRING*)(pRoot + offset); return new string(pString->NameString, 0, pString->Length); } public Win32ResourceDirectory? FindDirectory(Win32ResourceName name) { foreach (var directory in Directories) { if (directory.Name == name) return directory; } return null; } public Win32ResourceData? FindData(Win32ResourceName name) { foreach (var data in Datas) { if (data.Name == name) return data; } return null; } public Win32ResourceDirectory? FirstDirectory() { return Directories.Count != 0 ? Directories[0] : null; } public Win32ResourceData? FirstData() { return Datas.Count != 0 ? Datas[0] : null; } } [DebuggerDisplay("Data: {Name}")] public sealed unsafe class Win32ResourceData { #region Structure public uint OffsetToData { get; } public uint Size { get; } public uint CodePage { get; } public uint Reserved { get; } #endregion private readonly void* _pointer; public Win32ResourceName Name { get; } public byte[] Data { get { byte[] data = new byte[Size]; fixed (void* pData = data) Buffer.MemoryCopy(_pointer, pData, Size, Size); return data; } } internal Win32ResourceData(PEReader pe, byte* pRoot, int offset, Win32ResourceName name) { var p = (IMAGE_RESOURCE_DATA_ENTRY*)(pRoot + offset); OffsetToData = p->OffsetToData; Size = p->Size; CodePage = p->CodePage; Reserved = p->Reserved; _pointer = pe.GetSectionData((int)OffsetToData).Pointer; Name = name; } } public sealed class Win32ResourceName { private readonly object _name; public bool HasName => _name is string; public bool HasId => _name is ushort; public string Name => (string)_name; public ushort Id => (ushort)_name; public Win32ResourceName(string name) { _name = name ?? throw new ArgumentNullException(nameof(name)); } public Win32ResourceName(int id) : this(checked((ushort)id)) { } public Win32ResourceName(ushort id) { _name = id; } internal unsafe Win32ResourceName(byte* pRoot, IMAGE_RESOURCE_DIRECTORY_ENTRY* pEntry) { _name = (pEntry->Name & 0x80000000) == 0 ? (object)(ushort)pEntry->Name : ReadString(pRoot, (int)(pEntry->Name & 0x7FFFFFFF)); static string ReadString(byte* pRoot, int offset) { var pString = (IMAGE_RESOURCE_DIRECTORY_STRING*)(pRoot + offset); return new string(pString->NameString, 0, pString->Length); } } public static bool operator ==(Win32ResourceName x, Win32ResourceName y) { if (x.HasName) { return y.HasName ? string.Compare(x.Name, y.Name, StringComparison.OrdinalIgnoreCase) == 0 : false; } else { return y.HasId ? x.Id == y.Id : false; } } public static bool operator !=(Win32ResourceName x, Win32ResourceName y) { return !(x == y); } public override int GetHashCode() { return _name.GetHashCode(); } public override bool Equals(object? obj) { if (!(obj is Win32ResourceName name)) return false; return this == name; } public override string ToString() { return HasName ? $"Name: {Name}" : $"Id: {Id}"; } } internal struct IMAGE_RESOURCE_DIRECTORY { public uint Characteristics; public uint TimeDateStamp; public ushort MajorVersion; public ushort MinorVersion; public ushort NumberOfNamedEntries; public ushort NumberOfIdEntries; } internal struct IMAGE_RESOURCE_DIRECTORY_ENTRY { public uint Name; public uint OffsetToData; } internal unsafe struct IMAGE_RESOURCE_DIRECTORY_STRING { public ushort Length; public fixed char NameString[1]; } internal struct IMAGE_RESOURCE_DATA_ENTRY { public uint OffsetToData; public uint Size; public uint CodePage; public uint Reserved; } }
ILSpy/ICSharpCode.Decompiler/Util/Win32Resources.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler/Util/Win32Resources.cs", "repo_id": "ILSpy", "token_count": 2904 }
249
// Copyright (c) 2022 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.ILSpyX.Extensions { public static class CollectionExtensions { public static void AddRange<T>(this ICollection<T> list, IEnumerable<T> items) { foreach (T item in items) if (!list.Contains(item)) list.Add(item); } public static T? PeekOrDefault<T>(this Stack<T> stack) { if (stack.Count == 0) return default(T); return stack.Peek(); } public static int BinarySearch<T>(this IList<T> list, T item, int start, int count, IComparer<T> comparer) { if (list == null) throw new ArgumentNullException(nameof(list)); if (start < 0 || start >= list.Count) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + (list.Count - 1)); if (count < 0 || count > list.Count - start) throw new ArgumentOutOfRangeException(nameof(count), count, "Value must be between 0 and " + (list.Count - start)); int end = start + count - 1; while (start <= end) { int pivot = (start + end) / 2; int result = comparer.Compare(item, list[pivot]); if (result == 0) return pivot; if (result < 0) end = pivot - 1; else start = pivot + 1; } return ~start; } public static int BinarySearch<T, TKey>(this IList<T> instance, TKey itemKey, Func<T, TKey> keySelector) where TKey : IComparable<TKey>, IComparable { if (instance == null) throw new ArgumentNullException(nameof(instance)); if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); int start = 0; int end = instance.Count - 1; while (start <= end) { int m = (start + end) / 2; TKey key = keySelector(instance[m]); int result = key.CompareTo(itemKey); if (result == 0) return m; if (result < 0) start = m + 1; else end = m - 1; } return ~start; } public static void InsertSorted<T>(this IList<T> list, T item, IComparer<T> comparer) { if (list == null) throw new ArgumentNullException(nameof(list)); if (comparer == null) throw new ArgumentNullException(nameof(comparer)); if (list.Count == 0) { list.Add(item); } else { int index = list.BinarySearch(item, 0, list.Count, comparer); list.Insert(index < 0 ? ~index : index, item); } } internal static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } internal static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T>? inst) => inst ?? Enumerable.Empty<T>(); internal static IEnumerable EmptyIfNull(this IEnumerable? inst) => inst ?? Enumerable.Empty<object>(); internal static IList<T> EmptyIfNull<T>(this IList<T>? inst) => inst ?? EmptyList<T>.Instance; internal static IList EmptyIfNull(this IList? inst) => inst ?? Array.Empty<object>(); } }
ILSpy/ICSharpCode.ILSpyX/Extensions/CollectionExtensions.cs/0
{ "file_path": "ILSpy/ICSharpCode.ILSpyX/Extensions/CollectionExtensions.cs", "repo_id": "ILSpy", "token_count": 1478 }
250
// 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.Threading; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpyX.Abstractions; namespace ICSharpCode.ILSpyX.Search { public class MemberSearchStrategy : AbstractEntitySearchStrategy { readonly MemberSearchKind searchKind; public MemberSearchStrategy(ILanguage language, ApiVisibility apiVisibility, SearchRequest searchRequest, IProducerConsumerCollection<SearchResult> resultQueue, MemberSearchKind searchKind = MemberSearchKind.All) : base(language, apiVisibility, searchRequest, resultQueue) { this.searchKind = searchKind; } public override void Search(PEFile module, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var metadata = module.Metadata; var typeSystem = module.GetTypeSystemWithDecompilerSettingsOrNull(searchRequest.DecompilerSettings); if (typeSystem == null) return; if (searchKind == MemberSearchKind.All || searchKind == MemberSearchKind.Type) { foreach (var handle in metadata.TypeDefinitions) { cancellationToken.ThrowIfCancellationRequested(); string languageSpecificName = language.GetEntityName(module, handle, fullNameSearch, omitGenerics); if (languageSpecificName != null && !IsMatch(languageSpecificName)) continue; var type = ((MetadataModule)typeSystem.MainModule).GetDefinition(handle); if (!CheckVisibility(type) || !IsInNamespaceOrAssembly(type)) continue; OnFoundResult(type); } } if (searchKind == MemberSearchKind.All || searchKind == MemberSearchKind.Member || searchKind == MemberSearchKind.Method) { foreach (var handle in metadata.MethodDefinitions) { cancellationToken.ThrowIfCancellationRequested(); string languageSpecificName = language.GetEntityName(module, handle, fullNameSearch, omitGenerics); if (languageSpecificName != null && !IsMatch(languageSpecificName)) continue; var method = ((MetadataModule)typeSystem.MainModule).GetDefinition(handle); if (!CheckVisibility(method) || !IsInNamespaceOrAssembly(method)) continue; OnFoundResult(method); } } if (searchKind == MemberSearchKind.All || searchKind == MemberSearchKind.Member || searchKind == MemberSearchKind.Field) { foreach (var handle in metadata.FieldDefinitions) { cancellationToken.ThrowIfCancellationRequested(); string languageSpecificName = language.GetEntityName(module, handle, fullNameSearch, omitGenerics); if (languageSpecificName != null && !IsMatch(languageSpecificName)) continue; var field = ((MetadataModule)typeSystem.MainModule).GetDefinition(handle); if (!CheckVisibility(field) || !IsInNamespaceOrAssembly(field)) continue; OnFoundResult(field); } } if (searchKind == MemberSearchKind.All || searchKind == MemberSearchKind.Member || searchKind == MemberSearchKind.Property) { foreach (var handle in metadata.PropertyDefinitions) { cancellationToken.ThrowIfCancellationRequested(); string languageSpecificName = language.GetEntityName(module, handle, fullNameSearch, omitGenerics); if (languageSpecificName != null && !IsMatch(languageSpecificName)) continue; var property = ((MetadataModule)typeSystem.MainModule).GetDefinition(handle); if (!CheckVisibility(property) || !IsInNamespaceOrAssembly(property)) continue; OnFoundResult(property); } } if (searchKind == MemberSearchKind.All || searchKind == MemberSearchKind.Member || searchKind == MemberSearchKind.Event) { foreach (var handle in metadata.EventDefinitions) { cancellationToken.ThrowIfCancellationRequested(); string languageSpecificName = language.GetEntityName(module, handle, fullNameSearch, omitGenerics); if (!IsMatch(languageSpecificName)) continue; var @event = ((MetadataModule)typeSystem.MainModule).GetDefinition(handle); if (!CheckVisibility(@event) || !IsInNamespaceOrAssembly(@event)) continue; OnFoundResult(@event); } } } } public enum MemberSearchKind { All, Type, Member, Field, Property, Event, Method } }
ILSpy/ICSharpCode.ILSpyX/Search/MemberSearchStrategy.cs/0
{ "file_path": "ILSpy/ICSharpCode.ILSpyX/Search/MemberSearchStrategy.cs", "repo_id": "ILSpy", "token_count": 1755 }
251
using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.IO; using System.Linq; using Microsoft.VisualStudio.Shell; using Mono.Cecil; using DTEConstants = EnvDTE.Constants; namespace ICSharpCode.ILSpy.AddIn.Commands { public class DetectedReference { public DetectedReference(string name, string assemblyFile, bool isProjectReference) { this.Name = name; this.AssemblyFile = assemblyFile; this.IsProjectReference = isProjectReference; } public string Name { get; private set; } public string AssemblyFile { get; private set; } public bool IsProjectReference { get; private set; } } abstract class ILSpyCommand { protected ILSpyAddInPackage owner; protected ILSpyCommand(ILSpyAddInPackage owner, uint id) { ThreadHelper.ThrowIfNotOnUIThread(); this.owner = owner; CommandID menuCommandID = new CommandID(GuidList.guidILSpyAddInCmdSet, (int)id); OleMenuCommand menuItem = new OleMenuCommand(OnExecute, menuCommandID); menuItem.BeforeQueryStatus += OnBeforeQueryStatus; owner.MenuService.AddCommand(menuItem); } protected virtual void OnBeforeQueryStatus(object sender, EventArgs e) { } protected abstract void OnExecute(object sender, EventArgs e); protected void OpenAssembliesInILSpy(ILSpyParameters parameters) { ThreadHelper.ThrowIfNotOnUIThread(); if (parameters == null) return; foreach (string assemblyFileName in parameters.AssemblyFileNames) { if (!File.Exists(assemblyFileName)) { owner.ShowMessage("Could not find assembly '{0}', please ensure the project and all references were built correctly!", assemblyFileName); return; } } var ilspyExe = new ILSpyInstance(parameters); ilspyExe.Start(); } protected Dictionary<string, DetectedReference> GetReferences(Microsoft.CodeAnalysis.Project parentProject) { ThreadHelper.ThrowIfNotOnUIThread(); var dict = new Dictionary<string, DetectedReference>(); foreach (var reference in parentProject.MetadataReferences) { using (var assemblyDef = AssemblyDefinition.ReadAssembly(reference.Display)) { string assemblyName = assemblyDef.Name.Name; string resolvedAssemblyFile = AssemblyFileFinder.FindAssemblyFile(assemblyDef, reference.Display); dict.Add(assemblyName, new DetectedReference(assemblyName, resolvedAssemblyFile, false)); } } foreach (var projectReference in parentProject.ProjectReferences) { var roslynProject = owner.Workspace.CurrentSolution.GetProject(projectReference.ProjectId); if (roslynProject != null) { var project = FindProject(owner.DTE.Solution.Projects.OfType<EnvDTE.Project>(), roslynProject.FilePath); if (project != null) { dict.Add(roslynProject.AssemblyName, new DetectedReference(roslynProject.AssemblyName, Utils.GetProjectOutputAssembly(project, roslynProject), true)); } } } return dict; } protected EnvDTE.Project FindProject(IEnumerable<EnvDTE.Project> projects, string projectFile) { ThreadHelper.ThrowIfNotOnUIThread(); foreach (var project in projects) { switch (project.Kind) { case DTEConstants.vsProjectKindSolutionItems: // This is a solution folder -> search in sub-projects var subProject = FindProject( project.ProjectItems.OfType<EnvDTE.ProjectItem>().Select(pi => pi.SubProject).OfType<EnvDTE.Project>(), projectFile); if (subProject != null) return subProject; break; case DTEConstants.vsProjectKindUnmodeled: // Skip unloaded projects completely break; default: // Match by project's file name if (project.FileName == projectFile) return project; break; } } return null; } } class OpenILSpyCommand : ILSpyCommand { static OpenILSpyCommand instance; public OpenILSpyCommand(ILSpyAddInPackage owner) : base(owner, PkgCmdIDList.cmdidOpenILSpy) { ThreadHelper.ThrowIfNotOnUIThread(); } protected override void OnExecute(object sender, EventArgs e) { new ILSpyInstance().Start(); } internal static void Register(ILSpyAddInPackage owner) { ThreadHelper.ThrowIfNotOnUIThread(); instance = new OpenILSpyCommand(owner); } } }
ILSpy/ILSpy.AddIn.Shared/Commands/OpenILSpyCommand.cs/0
{ "file_path": "ILSpy/ILSpy.AddIn.Shared/Commands/OpenILSpyCommand.cs", "repo_id": "ILSpy", "token_count": 1541 }
252
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <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" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </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> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="110" xml:space="preserve"> <value>ILSpy.AddIn</value> </data> <data name="112" xml:space="preserve"> <value>Integration of the ILSpy Decompiler into Visual Studio.</value> </data> </root>
ILSpy/ILSpy.AddIn.Shared/VSPackage.en-US.resx/0
{ "file_path": "ILSpy/ILSpy.AddIn.Shared/VSPackage.en-US.resx", "repo_id": "ILSpy", "token_count": 2462 }
253
<UserControl x:Class="BamlTest.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:bamltest="clr-namespace:BamlTest"> <FrameworkElement.Resources> <ResourceDictionary> <Style x:Key="baseStyle" TargetType="{x:Type Control}" /> </ResourceDictionary> </FrameworkElement.Resources> <Grid> <FrameworkElement.ContextMenu> <ContextMenu> <FrameworkElement.Resources> <ResourceDictionary> <Style x:Key="{x:Type Control}" BasedOn="{StaticResource baseStyle}" TargetType="{x:Type Control}" /> </ResourceDictionary> </FrameworkElement.Resources> </ContextMenu> </FrameworkElement.ContextMenu> </Grid> </UserControl>
ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue445.xaml/0
{ "file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue445.xaml", "repo_id": "ILSpy", "token_count": 277 }
254
<?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> <EnableDefaultItems>false</EnableDefaultItems> <UseWpf>true</UseWpf> <ExtrasEnableDefaultPageItems>false</ExtrasEnableDefaultPageItems> <ExtrasEnableDefaultResourceItems>false</ExtrasEnableDefaultResourceItems> <AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects> <EnableWindowsTargeting>true</EnableWindowsTargeting> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' == 'Debug'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' == 'Release'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="NUnit" /> <PackageReference Include="NUnit3TestAdapter" /> <PackageReference Include="FluentAssertions" /> <PackageReference Include="JunitXml.TestLogger" /> <PackageReference Include="coverlet.collector" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\ICSharpCode.Decompiler.Tests\ICSharpCode.Decompiler.Tests.csproj" /> <ProjectReference Include="..\ILSpy.BamlDecompiler\ILSpy.BamlDecompiler.csproj" /> <ProjectReference Include="..\ILSpy\ILSpy.csproj" /> <ProjectReference Include="..\SharpTreeView\ICSharpCode.TreeView.csproj" /> </ItemGroup> <ItemGroup> <Compile Include="BamlTestRunner.cs" /> <Compile Include="Cases\AttachedEvent.xaml.cs"> <DependentUpon>AttachedEvent.xaml</DependentUpon> </Compile> <Compile Include="Cases\CustomControl.cs" /> <Compile Include="Cases\Issue1547.xaml.cs" /> <Compile Include="Cases\Issue2097.xaml.cs" /> <Compile Include="Cases\Issue2116.xaml.cs" /> <Compile Include="Cases\MyControl.xaml.cs"> <DependentUpon>MyControl.xaml</DependentUpon> </Compile> <Compile Include="Cases\ReadonlyProperty.xaml.cs" /> <Compile Include="Cases\Resources.xaml.cs"> <DependentUpon>Resources.xaml</DependentUpon> </Compile> <Compile Include="Cases\Simple.xaml.cs"> <DependentUpon>Simple.xaml</DependentUpon> </Compile> <Compile Include="Cases\SimpleNames.xaml.cs"> <DependentUpon>SimpleNames.xaml</DependentUpon> </Compile> <Compile Include="Mocks\AvalonDock.cs" /> </ItemGroup> <ItemGroup> <Page Include="Cases\AttachedEvent.xaml" /> <Page Include="Cases\AvalonDockBrushes.xaml" /> <Page Include="Cases\AvalonDockCommon.xaml" /> <Page Include="Cases\EscapeSequence.xaml"> <SubType>Designer</SubType> <Generator>MSBuild:Compile</Generator> </Page> <Page Include="Cases\Issue1435.xaml"> <Generator>MSBuild:Compile</Generator> </Page> <Page Include="Cases\Issue1546.xaml"> <Generator>MSBuild:Compile</Generator> </Page> <Page Include="Cases\Issue1547.xaml"> <Generator>MSBuild:Compile</Generator> </Page> <Page Include="Cases\Issue2052.xaml"> <Generator>MSBuild:Compile</Generator> </Page> <Page Include="Cases\Issue2097.xaml"> <Generator>MSBuild:Compile</Generator> </Page> <Page Include="Cases\Issue2116.xaml"> <Generator>MSBuild:Compile</Generator> </Page> <Page Include="Cases\Issue775.xaml"> <SubType>Designer</SubType> </Page> <Page Include="Cases\MarkupExtension.xaml" /> <Page Include="Cases\MyControl.xaml" /> <Page Include="Cases\NamespacePrefix.xaml" /> <Page Include="Cases\ReadonlyProperty.xaml"> <Generator>MSBuild:Compile</Generator> </Page> <Page Include="Cases\Resources.xaml" /> <Page Include="Cases\Simple.xaml"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Page> <Page Include="Cases\SimpleDictionary.xaml" /> <Page Include="Cases\SimpleNames.xaml" /> <Page Include="Cases\SimplePropertyElement.xaml" /> <Page Include="Cases\Dictionary1.xaml" /> <Page Include="Cases\Issue445.xaml" /> </ItemGroup> </Project>
ILSpy/ILSpy.BamlDecompiler.Tests/ILSpy.BamlDecompiler.Tests.csproj/0
{ "file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/ILSpy.BamlDecompiler.Tests.csproj", "repo_id": "ILSpy", "token_count": 1707 }
255
{ "solution": { "path": "ILSpy.sln", "projects": [ "ICSharpCode.ILSpyCmd\\ICSharpCode.ILSpyCmd.csproj", "ICSharpCode.Decompiler.PowerShell\\ICSharpCode.Decompiler.PowerShell.csproj", "ICSharpCode.Decompiler.TestRunner\\ICSharpCode.Decompiler.TestRunner.csproj", "ICSharpCode.Decompiler.Tests\\ICSharpCode.Decompiler.Tests.csproj", "ICSharpCode.Decompiler\\ICSharpCode.Decompiler.csproj", "ICSharpCode.ILSpyX\\ICSharpCode.ILSpyX.csproj" ] } }
ILSpy/ILSpy.XPlat.slnf/0
{ "file_path": "ILSpy/ILSpy.XPlat.slnf", "repo_id": "ILSpy", "token_count": 210 }
256
// 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.Diagnostics; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.ILSpy.Analyzers.Builtin { /// <summary> /// Shows members from all corresponding interfaces the selected member implements. /// </summary> [ExportAnalyzer(Header = "Implements", Order = 40)] class MemberImplementsInterfaceAnalyzer : IAnalyzer { public IEnumerable<ISymbol> Analyze(ISymbol analyzedSymbol, AnalyzerContext context) { Debug.Assert(analyzedSymbol is IMember); var member = (IMember)analyzedSymbol; Debug.Assert(!member.IsStatic); var baseMembers = InheritanceHelper.GetBaseMembers(member, includeImplementedInterfaces: true); return baseMembers.Where(m => m.DeclaringTypeDefinition.Kind == TypeKind.Interface); } public bool Show(ISymbol symbol) { switch (symbol?.SymbolKind) { case SymbolKind.Event: case SymbolKind.Indexer: case SymbolKind.Method: case SymbolKind.Property: var member = (IMember)symbol; var type = member.DeclaringTypeDefinition; return !member.IsStatic && type is not null && (type.Kind == TypeKind.Class || type.Kind == TypeKind.Struct); default: return false; } } } }
ILSpy/ILSpy/Analyzers/Builtin/MemberImplementsInterfaceAnalyzer.cs/0
{ "file_path": "ILSpy/ILSpy/Analyzers/Builtin/MemberImplementsInterfaceAnalyzer.cs", "repo_id": "ILSpy", "token_count": 719 }
257
// 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.Threading; using ICSharpCode.Decompiler; using ICSharpCode.ILSpy.Options; using ICSharpCode.ILSpyX; namespace ICSharpCode.ILSpy { /// <summary> /// Options passed to the decompiler. /// </summary> public class DecompilationOptions { /// <summary> /// Gets whether a full decompilation (all members recursively) is desired. /// If this option is false, language bindings are allowed to show the only headers of the decompiled element's children. /// </summary> public bool FullDecompilation { get; set; } /// <summary> /// Gets/Sets the directory into which the project is saved. /// </summary> public string SaveAsProjectDirectory { get; set; } /// <summary> /// Gets/sets whether invalid identifiers should be escaped (and therefore the code be made compilable). /// This setting is ignored in case <see cref="SaveAsProjectDirectory"/> is set. /// </summary> public bool EscapeInvalidIdentifiers { get; set; } /// <summary> /// Gets the cancellation token that is used to abort the decompiler. /// </summary> /// <remarks> /// Decompilers should regularly call <c>options.CancellationToken.ThrowIfCancellationRequested();</c> /// to allow for cooperative cancellation of the decompilation task. /// </remarks> public CancellationToken CancellationToken { get; set; } /// <summary> /// Gets the progress reporter. /// </summary> /// <remarks> /// If decompilers do not implement progress reporting, an indeterminate wait bar is displayed. /// </remarks> public IProgress<DecompilationProgress> Progress { get; set; } /// <summary> /// Gets the settings for the decompiler. /// </summary> public Decompiler.DecompilerSettings DecompilerSettings { get; private set; } /// <summary> /// Gets/sets an optional state of a decompiler text view. /// </summary> /// <remarks> /// This state is used to restore test view's state when decompilation is started by Go Back/Forward action. /// </remarks> public TextView.DecompilerTextViewState TextViewState { get; set; } /// <summary> /// Used internally for debugging. /// </summary> internal int StepLimit = int.MaxValue; internal bool IsDebug = false; public DecompilationOptions(LanguageVersion version, Decompiler.DecompilerSettings settings, DisplaySettingsViewModel displaySettings) { if (!Enum.TryParse(version?.Version, out Decompiler.CSharp.LanguageVersion languageVersion)) languageVersion = Decompiler.CSharp.LanguageVersion.Latest; var newSettings = this.DecompilerSettings = settings.Clone(); newSettings.SetLanguageVersion(languageVersion); newSettings.ExpandMemberDefinitions = displaySettings.ExpandMemberDefinitions; newSettings.ExpandUsingDeclarations = displaySettings.ExpandUsingDeclarations; newSettings.FoldBraces = displaySettings.FoldBraces; newSettings.ShowDebugInfo = displaySettings.ShowDebugInfo; newSettings.CSharpFormattingOptions.IndentationString = GetIndentationString(displaySettings); } private string GetIndentationString(DisplaySettingsViewModel displaySettings) { if (displaySettings.IndentationUseTabs) { int numberOfTabs = displaySettings.IndentationSize / displaySettings.IndentationTabSize; int numberOfSpaces = displaySettings.IndentationSize % displaySettings.IndentationTabSize; return new string('\t', numberOfTabs) + new string(' ', numberOfSpaces); } return new string(' ', displaySettings.IndentationSize); } } }
ILSpy/ILSpy/DecompilationOptions.cs/0
{ "file_path": "ILSpy/ILSpy/DecompilationOptions.cs", "repo_id": "ILSpy", "token_count": 1353 }
258
<!-- This file was generated by the AiToXaml tool.--> <!-- Tool Version: 14.0.22307.0 --> <DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <DrawingGroup.Children> <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" /> <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M15,10L13,10 13,12 11,12 11,14 2,14 2,5 4,5 4,3 6,3 6,1 15,1z" /> <GeometryDrawing Brush="#FF424242" Geometry="F1M9,7L4,7 4,12 9,12z M10,13L3,13 3,6 10,6z M5,4L5,5 6,5 11,5 11,10 11,11 12,11 12,4z M14,2L14,9 13,9 13,8 13,3 8,3 7,3 7,2z" /> <GeometryDrawing Brush="#FFF0EFF1" Geometry="F1M8,10L5,10 5,9 8,9z M4,12L9,12 9,7 4,7z" /> <GeometryDrawing Brush="#FF00539C" Geometry="F1M8,10L5,10 5,8.969 8,9z" /> </DrawingGroup.Children> </DrawingGroup>
ILSpy/ILSpy/Images/CollapseAll.xaml/0
{ "file_path": "ILSpy/ILSpy/Images/CollapseAll.xaml", "repo_id": "ILSpy", "token_count": 385 }
259
<DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ClipGeometry="M0,0 V16 H16 V0 H0 Z"> <DrawingGroup.Transform> <TranslateTransform X="12.444443702697754" Y="12.444443702697754" /> </DrawingGroup.Transform> <DrawingGroup Opacity="1" Transform="0.5625,0,0,1,7,12.444445"> <GeometryDrawing Geometry="F1 M16,16z M0,0z M16,-12.444444L16,3.5555556 -12.444444,3.5555556 -12.444444,-12.444444z"> <GeometryDrawing.Brush> <SolidColorBrush Color="#FFF6F6F6" Opacity="0" /> </GeometryDrawing.Brush> </GeometryDrawing> </DrawingGroup> <DrawingGroup Opacity="1" Transform="0.5625,0,0,0.5625,7,7"> <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1 M16,16z M0,0z M5.793,0.879L8.621,3.707 7.328,5 10.5,5C13.533,5 16,7.467 16,10.5 16,13.532 13.533,16 10.5,16L9.5,16 9.5,12 10.5,12C11.327,12 12,11.327 12,10.5 12,9.673 11.327,9 10.5,9L7.328,9 8.621,10.293 5.793,13.121 0,7.328 0,6.672z" /> </DrawingGroup> <DrawingGroup Opacity="1" Transform="0.5625,0,0,0.5625,7,7"> <GeometryDrawing Brush="#FF00539C" Geometry="F1 M16,16z M0,0z M5.793,2.293L7.207,3.707 4.914,6 10.5,6C12.981,6 15,8.019 15,10.5 15,12.981 12.981,15 10.5,15L10.5,13C11.878,13 13,11.879 13,10.5 13,9.121 11.878,8 10.5,8L4.914,8 7.207,10.293 5.793,11.707 1.086,7z" /> </DrawingGroup> </DrawingGroup>
ILSpy/ILSpy/Images/ExportOverlay.xaml/0
{ "file_path": "ILSpy/ILSpy/Images/ExportOverlay.xaml", "repo_id": "ILSpy", "token_count": 678 }
260
<!-- 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="F1M1,16L15,16 15,0 1,0z" /> <GeometryDrawing Brush="#FF424242" Geometry="F1M12,9L4,9 4,8 12,8z M12,11L4,11 4,10 12,10z M12,13L4,13 4,12 12,12z M13,14L3,14 3,2 13,2z M2,15L14,15 14,1 2,1z" /> <GeometryDrawing Brush="#FFF0EFF1" Geometry="F1M12,3L4,3 4,6 12,6z M12,8L4,8 4,9 12,9z M12,10L4,10 4,11 12,11z M12,12L4,12 4,13 12,13z M13,14L3,14 3,2 13,2z M11,5L5,5 5,4 11,4z" /> <GeometryDrawing Brush="#FF1BA1E2" Geometry="F1M11,5L5,5 5,4 11,4z M12,3L4,3 4,6 12,6z" /> </DrawingGroup.Children> </DrawingGroup>
ILSpy/ILSpy/Images/Header.xaml/0
{ "file_path": "ILSpy/ILSpy/Images/Header.xaml", "repo_id": "ILSpy", "token_count": 427 }
261
// 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 ICSharpCode.AvalonEdit.Highlighting; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.CSharp.OutputVisitor; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.IL; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpyX.Extensions; namespace ICSharpCode.ILSpy { class CSharpHighlightingTokenWriter : DecoratingTokenWriter { HighlightingColor visibilityKeywordsColor; HighlightingColor namespaceKeywordsColor; HighlightingColor structureKeywordsColor; HighlightingColor gotoKeywordsColor; HighlightingColor queryKeywordsColor; HighlightingColor exceptionKeywordsColor; HighlightingColor checkedKeywordColor; HighlightingColor unsafeKeywordsColor; HighlightingColor valueTypeKeywordsColor; HighlightingColor referenceTypeKeywordsColor; HighlightingColor operatorKeywordsColor; HighlightingColor parameterModifierColor; HighlightingColor modifiersColor; HighlightingColor accessorKeywordsColor; HighlightingColor attributeKeywordsColor; HighlightingColor referenceTypeColor; HighlightingColor valueTypeColor; HighlightingColor interfaceTypeColor; HighlightingColor enumerationTypeColor; HighlightingColor typeParameterTypeColor; HighlightingColor delegateTypeColor; HighlightingColor methodCallColor; HighlightingColor methodDeclarationColor; HighlightingColor fieldDeclarationColor; HighlightingColor fieldAccessColor; HighlightingColor propertyDeclarationColor; HighlightingColor propertyAccessColor; HighlightingColor eventDeclarationColor; HighlightingColor eventAccessColor; HighlightingColor variableColor; HighlightingColor parameterColor; HighlightingColor valueKeywordColor; HighlightingColor thisKeywordColor; HighlightingColor trueKeywordColor; HighlightingColor typeKeywordsColor; public RichTextModel HighlightingModel { get; } = new RichTextModel(); public CSharpHighlightingTokenWriter(TokenWriter decoratedWriter, ISmartTextOutput textOutput = null, ILocatable locatable = null) : base(decoratedWriter) { var highlighting = HighlightingManager.Instance.GetDefinition("C#"); this.locatable = locatable; this.textOutput = textOutput; this.visibilityKeywordsColor = highlighting.GetNamedColor("Visibility"); this.namespaceKeywordsColor = highlighting.GetNamedColor("NamespaceKeywords"); this.structureKeywordsColor = highlighting.GetNamedColor("Keywords"); this.gotoKeywordsColor = highlighting.GetNamedColor("GotoKeywords"); this.queryKeywordsColor = highlighting.GetNamedColor("QueryKeywords"); this.exceptionKeywordsColor = highlighting.GetNamedColor("ExceptionKeywords"); this.checkedKeywordColor = highlighting.GetNamedColor("CheckedKeyword"); this.unsafeKeywordsColor = highlighting.GetNamedColor("UnsafeKeywords"); this.valueTypeKeywordsColor = highlighting.GetNamedColor("ValueTypeKeywords"); this.referenceTypeKeywordsColor = highlighting.GetNamedColor("ReferenceTypeKeywords"); this.operatorKeywordsColor = highlighting.GetNamedColor("OperatorKeywords"); this.parameterModifierColor = highlighting.GetNamedColor("ParameterModifiers"); this.modifiersColor = highlighting.GetNamedColor("Modifiers"); this.accessorKeywordsColor = highlighting.GetNamedColor("GetSetAddRemove"); this.referenceTypeColor = highlighting.GetNamedColor("ReferenceTypes"); this.valueTypeColor = highlighting.GetNamedColor("ValueTypes"); this.interfaceTypeColor = highlighting.GetNamedColor("InterfaceTypes"); this.enumerationTypeColor = highlighting.GetNamedColor("EnumTypes"); this.typeParameterTypeColor = highlighting.GetNamedColor("TypeParameters"); this.delegateTypeColor = highlighting.GetNamedColor("DelegateTypes"); this.methodDeclarationColor = highlighting.GetNamedColor("MethodDeclaration"); this.methodCallColor = highlighting.GetNamedColor("MethodCall"); this.fieldDeclarationColor = highlighting.GetNamedColor("FieldDeclaration"); this.fieldAccessColor = highlighting.GetNamedColor("FieldAccess"); this.propertyDeclarationColor = highlighting.GetNamedColor("PropertyDeclaration"); this.propertyAccessColor = highlighting.GetNamedColor("PropertyAccess"); this.eventDeclarationColor = highlighting.GetNamedColor("EventDeclaration"); this.eventAccessColor = highlighting.GetNamedColor("EventAccess"); this.variableColor = highlighting.GetNamedColor("Variable"); this.parameterColor = highlighting.GetNamedColor("Parameter"); this.valueKeywordColor = highlighting.GetNamedColor("NullOrValueKeywords"); this.thisKeywordColor = highlighting.GetNamedColor("ThisOrBaseReference"); this.trueKeywordColor = highlighting.GetNamedColor("TrueFalse"); this.typeKeywordsColor = highlighting.GetNamedColor("TypeKeywords"); this.attributeKeywordsColor = highlighting.GetNamedColor("AttributeKeywords"); //this.externAliasKeywordColor = ...; } public override void WriteKeyword(Role role, string keyword) { HighlightingColor color = null; switch (keyword) { case "namespace": case "using": if (role == UsingStatement.UsingKeywordRole) color = structureKeywordsColor; else color = namespaceKeywordsColor; break; case "this": case "base": color = thisKeywordColor; break; case "true": case "false": color = trueKeywordColor; break; case "public": case "internal": case "protected": case "private": color = visibilityKeywordsColor; break; case "if": case "else": case "switch": case "case": case "default": case "while": case "do": case "for": case "foreach": case "lock": case "await": color = structureKeywordsColor; break; case "where": if (nodeStack.PeekOrDefault() is QueryClause) color = queryKeywordsColor; else color = structureKeywordsColor; break; case "in": if (nodeStack.PeekOrDefault() is ForeachStatement) color = structureKeywordsColor; else if (nodeStack.PeekOrDefault() is QueryClause) color = queryKeywordsColor; else color = parameterModifierColor; break; case "as": case "is": case "new": case "sizeof": case "typeof": case "nameof": case "stackalloc": color = typeKeywordsColor; break; case "with": if (role == WithInitializerExpression.WithKeywordRole) color = typeKeywordsColor; break; case "try": case "throw": case "catch": case "finally": color = exceptionKeywordsColor; break; case "when": if (role == CatchClause.WhenKeywordRole) color = exceptionKeywordsColor; break; case "get": case "set": case "add": case "remove": case "init": if (role == PropertyDeclaration.GetKeywordRole || role == PropertyDeclaration.SetKeywordRole || role == PropertyDeclaration.InitKeywordRole || role == CustomEventDeclaration.AddKeywordRole || role == CustomEventDeclaration.RemoveKeywordRole) color = accessorKeywordsColor; break; case "abstract": case "const": case "event": case "extern": case "override": case "sealed": case "static": case "virtual": case "volatile": case "async": case "partial": color = modifiersColor; break; case "readonly": if (role == ComposedType.ReadonlyRole) color = parameterModifierColor; else color = modifiersColor; break; case "checked": case "unchecked": color = checkedKeywordColor; break; case "fixed": case "unsafe": color = unsafeKeywordsColor; break; case "enum": case "struct": color = valueTypeKeywordsColor; break; case "class": case "interface": case "delegate": color = referenceTypeKeywordsColor; break; case "record": color = role == Roles.RecordKeyword ? referenceTypeKeywordsColor : valueTypeKeywordsColor; break; case "select": case "group": case "by": case "into": case "from": case "orderby": case "let": case "join": case "on": case "equals": if (nodeStack.PeekOrDefault() is QueryClause) color = queryKeywordsColor; break; case "ascending": case "descending": if (nodeStack.PeekOrDefault() is QueryOrdering) color = queryKeywordsColor; break; case "explicit": case "implicit": case "operator": color = operatorKeywordsColor; break; case "params": case "ref": case "out": case "scoped": color = parameterModifierColor; break; case "break": case "continue": case "goto": case "yield": case "return": color = gotoKeywordsColor; break; } if (nodeStack.PeekOrDefault() is AttributeSection) color = attributeKeywordsColor; if (color != null) { BeginSpan(color); } base.WriteKeyword(role, keyword); if (color != null) { EndSpan(); } } public override void WritePrimitiveType(string type) { HighlightingColor color = null; switch (type) { case "new": case "notnull": // Not sure if reference type or value type color = referenceTypeKeywordsColor; break; case "bool": case "byte": case "char": case "decimal": case "double": case "enum": case "float": case "int": case "long": case "sbyte": case "short": case "struct": case "uint": case "ushort": case "ulong": case "unmanaged": case "nint": case "nuint": color = valueTypeKeywordsColor; break; case "class": case "object": case "string": case "void": case "dynamic": color = referenceTypeKeywordsColor; break; } if (color != null) { BeginSpan(color); } base.WritePrimitiveType(type); if (color != null) { EndSpan(); } } public override void WriteIdentifier(Identifier identifier) { HighlightingColor color = null; if (identifier.Parent?.GetResolveResult() is ILVariableResolveResult rr) { if (rr.Variable.Kind == VariableKind.Parameter) { if (identifier.Name == "value" && identifier.Ancestors.OfType<Accessor>().FirstOrDefault() is { } accessor && accessor.Role != PropertyDeclaration.GetterRole) { color = valueKeywordColor; } else { color = parameterColor; } } else { color = variableColor; } } if (identifier.Parent is AstType) { switch (identifier.Name) { case "var": color = queryKeywordsColor; break; case "global": color = structureKeywordsColor; break; } } switch (GetCurrentDefinition()) { case ITypeDefinition t: ApplyTypeColor(t, ref color); break; case IMethod: color = methodDeclarationColor; break; case IField: color = fieldDeclarationColor; break; case IProperty: color = propertyDeclarationColor; break; case IEvent: color = eventDeclarationColor; break; } switch (GetCurrentMemberReference()) { case IType t: ApplyTypeColor(t, ref color); break; case IMethod m: color = methodCallColor; if (m.IsConstructor) ApplyTypeColor(m.DeclaringType, ref color); break; case IField: color = fieldAccessColor; break; case IProperty: color = propertyAccessColor; break; case IEvent: color = eventAccessColor; break; } if (color != null) { BeginSpan(color); } base.WriteIdentifier(identifier); if (color != null) { EndSpan(); } } void ApplyTypeColor(IType type, ref HighlightingColor color) { switch (type?.Kind) { case TypeKind.Delegate: color = delegateTypeColor; break; case TypeKind.Class: color = referenceTypeColor; break; case TypeKind.Interface: color = interfaceTypeColor; break; case TypeKind.Enum: color = enumerationTypeColor; break; case TypeKind.Struct: color = valueTypeColor; break; } } public override void WritePrimitiveValue(object value, Decompiler.CSharp.Syntax.LiteralFormat format) { HighlightingColor color = null; if (value is null) { color = valueKeywordColor; } if (value is true || value is false) { color = trueKeywordColor; } if (color != null) { BeginSpan(color); } base.WritePrimitiveValue(value, format); if (color != null) { EndSpan(); } } ISymbol GetCurrentDefinition() { if (nodeStack == null || nodeStack.Count == 0) return null; var node = nodeStack.Peek(); if (node is Identifier) node = node.Parent; if (Decompiler.TextTokenWriter.IsDefinition(ref node)) return node.GetSymbol(); return null; } ISymbol GetCurrentMemberReference() { if (nodeStack == null || nodeStack.Count == 0) return null; AstNode node = nodeStack.Peek(); var symbol = node.GetSymbol(); if (symbol == null && node.Role == Roles.TargetExpression && node.Parent is InvocationExpression) { symbol = node.Parent.GetSymbol(); } if (symbol != null && node.Parent is ObjectCreateExpression) { symbol = node.Parent.GetSymbol(); } if (node is IdentifierExpression && node.Role == Roles.TargetExpression && node.Parent is InvocationExpression && symbol is IMember member) { var declaringType = member.DeclaringType; if (declaringType != null && declaringType.Kind == TypeKind.Delegate) return null; } return symbol; } readonly Stack<AstNode> nodeStack = new Stack<AstNode>(); public override void StartNode(AstNode node) { nodeStack.Push(node); base.StartNode(node); } public override void EndNode(AstNode node) { base.EndNode(node); nodeStack.Pop(); } readonly Stack<HighlightingColor> colorStack = new Stack<HighlightingColor>(); HighlightingColor currentColor = new HighlightingColor(); int currentColorBegin = -1; readonly ILocatable locatable; readonly ISmartTextOutput textOutput; private void BeginSpan(HighlightingColor highlightingColor) { if (textOutput != null) { textOutput.BeginSpan(highlightingColor); return; } if (currentColorBegin > -1) HighlightingModel.SetHighlighting(currentColorBegin, locatable.Length - currentColorBegin, currentColor); colorStack.Push(currentColor); currentColor = currentColor.Clone(); currentColorBegin = locatable.Length; currentColor.MergeWith(highlightingColor); currentColor.Freeze(); } private void EndSpan() { if (textOutput != null) { textOutput.EndSpan(); return; } HighlightingModel.SetHighlighting(currentColorBegin, locatable.Length - currentColorBegin, currentColor); currentColor = colorStack.Pop(); currentColorBegin = locatable.Length; } } }
ILSpy/ILSpy/Languages/CSharpHighlightingTokenWriter.cs/0
{ "file_path": "ILSpy/ILSpy/Languages/CSharpHighlightingTokenWriter.cs", "repo_id": "ILSpy", "token_count": 6092 }
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.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; namespace ICSharpCode.ILSpy.Metadata { class CustomAttributeTableTreeNode : MetadataTableTreeNode { public CustomAttributeTableTreeNode(MetadataFile metadataFile) : base(HandleKind.CustomAttribute, metadataFile) { } public override object Text => $"0C CustomAttribute ({metadataFile.Metadata.GetTableRowCount(TableIndex.CustomAttribute)})"; 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<CustomAttributeEntry>(); CustomAttributeEntry scrollTargetEntry = default; foreach (var row in metadata.CustomAttributes) { CustomAttributeEntry entry = new CustomAttributeEntry(metadataFile, row); if (scrollTarget == MetadataTokens.GetRowNumber(row)) { scrollTargetEntry = entry; } list.Add(entry); } view.ItemsSource = list; tabPage.Content = view; if (scrollTargetEntry.RID > 0) { ScrollItemIntoView(view, scrollTargetEntry); } return true; } struct CustomAttributeEntry { readonly MetadataFile metadataFile; readonly CustomAttributeHandle handle; readonly CustomAttribute customAttr; public int RID => MetadataTokens.GetRowNumber(handle); public int Token => MetadataTokens.GetToken(handle); public int Offset => metadataFile.MetadataOffset + metadataFile.Metadata.GetTableMetadataOffset(TableIndex.CustomAttribute) + metadataFile.Metadata.GetTableRowSize(TableIndex.CustomAttribute) * (RID - 1); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Parent => MetadataTokens.GetToken(customAttr.Parent); public void OnParentClick() { MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, customAttr.Parent, protocol: "metadata")); } string parentTooltip; public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, customAttr.Parent); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Constructor => MetadataTokens.GetToken(customAttr.Constructor); public void OnConstructorClick() { MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, customAttr.Constructor, protocol: "metadata")); } string constructorTooltip; public string ConstructorTooltip => GenerateTooltip(ref constructorTooltip, metadataFile, customAttr.Constructor); [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Value => MetadataTokens.GetHeapOffset(customAttr.Value); public string ValueTooltip { get { return null; } } public CustomAttributeEntry(MetadataFile metadataFile, CustomAttributeHandle handle) { this.metadataFile = metadataFile; this.handle = handle; this.customAttr = metadataFile.Metadata.GetCustomAttribute(handle); this.parentTooltip = null; this.constructorTooltip = null; } } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, "CustomAttributes"); } } }
ILSpy/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs", "repo_id": "ILSpy", "token_count": 1401 }
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. #nullable enable using System.Reflection.PortableExecutable; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.ILSpy.TreeNodes; namespace ICSharpCode.ILSpy.Metadata { sealed class DebugDirectoryEntryTreeNode : ILSpyTreeNode { readonly PEFile module; readonly PEReader reader; readonly DebugDirectoryEntry entry; public DebugDirectoryEntryTreeNode(PEFile module, DebugDirectoryEntry entry) { this.module = module; this.reader = module.Reader; this.entry = entry; } override public object Text => entry.Type.ToString(); public override object Icon => Images.MetadataTable; public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, Text.ToString()); if (entry.DataSize > 0) { language.WriteCommentLine(output, $"Raw Data ({entry.DataSize}):"); int dataOffset = module.Reader.IsLoadedImage ? entry.DataRelativeVirtualAddress : entry.DataPointer; var data = module.Reader.GetEntireImage().GetContent(dataOffset, entry.DataSize); language.WriteCommentLine(output, data.ToHexString(data.Length)); } else { language.WriteCommentLine(output, $"(no data)"); } } } }
ILSpy/ILSpy/Metadata/DebugDirectory/DebugDirectoryEntryTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/DebugDirectory/DebugDirectoryEntryTreeNode.cs", "repo_id": "ILSpy", "token_count": 721 }
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.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Data; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.ILSpy.Metadata { /// <summary> /// Interaction logic for FlagsTooltip.xaml /// </summary> public partial class FlagsTooltip : IEnumerable<FlagGroup> { public FlagsTooltip(int value = 0, Type flagsType = null) { InitializeComponent(); } public void Add(FlagGroup group) { Groups.Add(group); } public IEnumerator<FlagGroup> GetEnumerator() { return Groups.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return Groups.GetEnumerator(); } public List<FlagGroup> Groups { get; } = new List<FlagGroup>(); } class FlagActiveConverter : DependencyObject, IValueConverter { public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(FlagActiveConverter), new PropertyMetadata(0)); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return Value == (int)value || ((int)value & Value) != 0; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public readonly struct Flag { public string Name { get; } public int Value { get; } public bool IsSelected { get; } public Flag(string name, int value, bool isSelected) { this.Name = name; this.Value = value; this.IsSelected = isSelected; } } public abstract class FlagGroup { public static MultipleChoiceGroup CreateMultipleChoiceGroup(Type flagsType, string header = null, int mask = -1, int selectedValue = 0, bool includeAll = true) { MultipleChoiceGroup group = new MultipleChoiceGroup(GetFlags(flagsType, mask, selectedValue, includeAll ? "<All>" : null)); group.Header = header; group.SelectedFlags = selectedValue; return group; } public static SingleChoiceGroup CreateSingleChoiceGroup(Type flagsType, string header = null, int mask = -1, int selectedValue = 0, Flag defaultFlag = default, bool includeAny = true) { var group = new SingleChoiceGroup(GetFlags(flagsType, mask, selectedValue, includeAny ? "<Any>" : null)); group.Header = header; group.SelectedFlag = group.Flags.SingleOrDefault(f => f.Value == selectedValue); if (group.SelectedFlag.Name == null) { group.SelectedFlag = defaultFlag; } return group; } public static IEnumerable<Flag> GetFlags(Type flagsType, int mask = -1, int selectedValues = 0, string neutralItem = null) { if (neutralItem != null) yield return new Flag(neutralItem, -1, false); foreach (var item in flagsType.GetFields(BindingFlags.Static | BindingFlags.Public)) { if (item.Name.EndsWith("Mask", StringComparison.Ordinal)) continue; int value = (int)CSharpPrimitiveCast.Cast(TypeCode.Int32, item.GetRawConstantValue(), false); if ((value & mask) == 0) continue; yield return new Flag($"{item.Name} ({value:X4})", value, (selectedValues & value) != 0); } } public string Header { get; set; } public IList<Flag> Flags { get; protected set; } } public class MultipleChoiceGroup : FlagGroup { public MultipleChoiceGroup(IEnumerable<Flag> flags) { this.Flags = flags.ToList(); } public int SelectedFlags { get; set; } } public class SingleChoiceGroup : FlagGroup { public SingleChoiceGroup(IEnumerable<Flag> flags) { this.Flags = flags.ToList(); } public Flag SelectedFlag { get; set; } } class NullVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return Visibility.Collapsed; return Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
ILSpy/ILSpy/Metadata/FlagsTooltip.xaml.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/FlagsTooltip.xaml.cs", "repo_id": "ILSpy", "token_count": 1714 }
265
// 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.Globalization; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Windows.Data; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpy.ViewModels; namespace ICSharpCode.ILSpy.Metadata { class MetadataTreeNode : ILSpyTreeNode { private readonly MetadataFile metadataFile; private readonly string title; public MetadataTreeNode(MetadataFile module, string title) { this.metadataFile = module; this.title = title; this.LazyLoading = true; } public override object Text => title; public override object Icon => Images.Metadata; public override bool View(TabPageModel tabPage) { tabPage.Title = Text.ToString(); tabPage.SupportsLanguageSwitching = false; return false; } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, title); DumpMetadataInfo(language, output, this.metadataFile.Metadata); } internal static void DumpMetadataInfo(Language language, ITextOutput output, MetadataReader metadata) { language.WriteCommentLine(output, "MetadataKind: " + metadata.MetadataKind); language.WriteCommentLine(output, "MetadataVersion: " + metadata.MetadataVersion); if (metadata.DebugMetadataHeader is { } header) { output.WriteLine(); language.WriteCommentLine(output, "Header:"); language.WriteCommentLine(output, "Id: " + header.Id.ToHexString(header.Id.Length)); language.WriteCommentLine(output, "EntryPoint: " + MetadataTokens.GetToken(header.EntryPoint).ToString("X8")); } output.WriteLine(); language.WriteCommentLine(output, "Tables:"); foreach (var table in Enum.GetValues<TableIndex>()) { int count = metadata.GetTableRowCount(table); if (count > 0) { language.WriteCommentLine(output, $"{(byte)table:X2} {table}: {count} rows"); } } } protected override void LoadChildren() { if (metadataFile is PEFile module) { this.Children.Add(new DosHeaderTreeNode(module)); this.Children.Add(new CoffHeaderTreeNode(module)); this.Children.Add(new OptionalHeaderTreeNode(module)); this.Children.Add(new DataDirectoriesTreeNode(module)); this.Children.Add(new DebugDirectoryTreeNode(module)); } this.Children.Add(new MetadataTablesTreeNode(metadataFile)); this.Children.Add(new StringHeapTreeNode(metadataFile)); this.Children.Add(new UserStringHeapTreeNode(metadataFile)); this.Children.Add(new GuidHeapTreeNode(metadataFile)); this.Children.Add(new BlobHeapTreeNode(metadataFile)); } public MetadataTableTreeNode FindNodeByHandleKind(HandleKind kind) { return this.Children.OfType<MetadataTablesTreeNode>().Single() .Children.OfType<MetadataTableTreeNode>().SingleOrDefault(x => x.Kind == kind); } } class Entry { public string Member { get; } public int Offset { get; } public int Size { get; } public object Value { get; } public string Meaning { get; } public IList<BitEntry> RowDetails { get; } public Entry(int offset, object value, int size, string member, string meaning, IList<BitEntry> rowDetails = null) { this.Member = member; this.Offset = offset; this.Size = size; this.Value = value; this.Meaning = meaning; this.RowDetails = rowDetails; } } class BitEntry { public bool Value { get; } public string Meaning { get; } public BitEntry(bool value, string meaning) { this.Value = value; this.Meaning = meaning; } } class ByteWidthConverter : IValueConverter { public static readonly ByteWidthConverter Instance = new ByteWidthConverter(); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return string.Format("{0:X" + 2 * ((Entry)value).Size + "}", ((Entry)value).Value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
ILSpy/ILSpy/Metadata/MetadataTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/MetadataTreeNode.cs", "repo_id": "ILSpy", "token_count": 1723 }
266
#region Using directives using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ILSpy")] [assembly: AssemblyDescription(".NET assembly inspector and decompiler")] [assembly: AssemblyCompany("ic#code")] [assembly: AssemblyProduct("ILSpy")] [assembly: AssemblyCopyright("Copyright 2011-2023 AlphaSierraPapa for the SharpDevelop Team")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // This sets the default COM visibility of types in the assembly to invisible. // If you need to expose a type to COM, use [ComVisible(true)] on that type. [assembly: ComVisible(false)] [assembly: AssemblyVersion(DecompilerVersionInfo.Major + "." + DecompilerVersionInfo.Minor + "." + DecompilerVersionInfo.Build + "." + DecompilerVersionInfo.Revision)] [assembly: AssemblyInformationalVersion(DecompilerVersionInfo.FullVersionWithShortCommitHash)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: SupportedOSPlatform("Windows7.0")] [assembly: TargetPlatform("Windows10.0")] [assembly: InternalsVisibleTo("ILSpy.AddIn, PublicKey=0024000004800000940000000602000000240000525341310004000001000100653c4a319be4f524972c3c5bba5fd243330f8e900287d9022d7821a63fd0086fd3801e3683dbe9897f2ecc44727023e9b40adcf180730af70c81c54476b3e5ba8b0f07f5132b2c3cc54347a2c1a9d64ebaaaf3cbffc1a18c427981e2a51d53d5ab02536b7550e732f795121c38a0abfdb38596353525d034baf9e6f1fd8ac4ac")] [assembly: InternalsVisibleTo("ILSpy.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004dcf3979c4e902efa4dd2163a039701ed5822e6f1134d77737296abbb97bf0803083cfb2117b4f5446a217782f5c7c634f9fe1fc60b4c11d62c5b3d33545036706296d31903ddcf750875db38a8ac379512f51620bb948c94d0831125fbc5fe63707cbb93f48c1459c4d1749eb7ac5e681a2f0d6d7c60fa527a3c0b8f92b02bf")] [assembly: SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Justification = "AssemblyInformationalVersion does not need to be a parsable version")]
ILSpy/ILSpy/Properties/AssemblyInfo.cs/0
{ "file_path": "ILSpy/ILSpy/Properties/AssemblyInfo.cs", "repo_id": "ILSpy", "token_count": 821 }
267
<?xml version="1.0"?> <SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"> <!-- This is a variant of the AvalonEdit C# highlighting that has several constructs disabled. The disabled constructs (e.g. contextual keywords) are highlighted using the CSharpLanguage.HighlightingTokenWriter instead. --> <!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment --> <Color name="Comment" foreground="Green" exampleText="// comment" /> <Color name="String" foreground="Blue" exampleText="string text = &quot;Hello, World!&quot;"/> <Color name="StringInterpolation" foreground="Black" exampleText="string text = $&quot;Hello, {name}!&quot;"/> <Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/> <Color name="Preprocessor" foreground="Green" exampleText="#region Title" /> <Color name="Punctuation" exampleText="a(b.c);" /> <Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" /> <Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" /> <Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/> <Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/> <Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/> <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/> <Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/> <Color name="QueryKeywords" foreground="Navy" exampleText="from x in y select z;"/> <Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/> <Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/> <Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/> <Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/> <Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/> <Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/> <Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/> <Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/> <Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/> <Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" /> <Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/> <Color name="AttributeKeywords" foreground="Navy" exampleText="[assembly: AssemblyVersion(&quot;1.0.0.*&quot;)]" /> <!-- Colors used for semantic highlighting --> <Color name="ReferenceTypes" foreground="#004085" exampleText="System.#{#Uri#}# uri;"/> <Color name="InterfaceTypes" foreground="#004085" exampleText="System.#{#IDisposable#}# obj;"/> <Color name="TypeParameters" foreground="#004085" exampleText="class MyList&lt;#{#T#}#&gt; { }"/> <Color name="DelegateTypes" foreground="#004085" exampleText="System.#{#Action#}#; action;"/> <Color name="ValueTypes" fontWeight="bold" foreground="#004085" exampleText="System.#{#DateTime#}# date;"/> <Color name="EnumTypes" fontWeight="bold" foreground="#004085" exampleText="System.#{#ConsoleKey#}# key;"/> <Color name="MethodDeclaration" exampleText="override string #{#ToString#}#() { }"/> <Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.#{#ToString#}#();"/> <Color name="FieldDeclaration" exampleText="private int #{#name#}#;"/> <Color name="FieldAccess" fontStyle="italic" exampleText="return this.#{#name#}#;"/> <Color name="PropertyDeclaration" exampleText="private int #{#name#}# { get; set; }"/> <Color name="PropertyAccess" exampleText="return this.#{#name#}#;"/> <Color name="EventDeclaration" exampleText="private event Action #{#name#}#;"/> <Color name="EventAccess" exampleText="this.#{#name#}#?.Invoke();"/> <Color name="Variable" exampleText="var #{#name#}# = 42;"/> <Color name="Parameter" exampleText="void Method(string #{#name#}#) { }"/> <Color name="InactiveCode" foreground="Gray" exampleText="#{#Deactivated by #if#}#"/> <Color name="SemanticError" foreground="DarkRed" exampleText="o.#{#MissingMethod#}#()"/> <Property name="DocCommentMarker" value="///" /> <RuleSet name="CommentMarkerSet"> <Keywords fontWeight="bold" foreground="Red"> <Word>TODO</Word> <Word>FIXME</Word> </Keywords> <Keywords fontWeight="bold" foreground="#E0E000"> <Word>HACK</Word> <Word>UNDONE</Word> </Keywords> </RuleSet> <!-- This is the main ruleset. --> <RuleSet> <Span color="Preprocessor"> <Begin>\#</Begin> <RuleSet name="PreprocessorSet"> <Span> <!-- preprocessor directives that allow comments --> <Begin fontWeight="bold"> (define|undef|if|elif|else|endif|line)\b </Begin> <RuleSet> <Span color="Comment" ruleSet="CommentMarkerSet"> <Begin>//</Begin> </Span> </RuleSet> </Span> <Span> <!-- preprocessor directives that don't allow comments --> <Begin fontWeight="bold"> (region|endregion|error|warning|pragma)\b </Begin> </Span> </RuleSet> </Span> <Span color="Comment"> <Begin color="XmlDoc/DocComment">///(?!/)</Begin> <RuleSet> <Import ruleSet="XmlDoc/DocCommentSet"/> <Import ruleSet="CommentMarkerSet"/> </RuleSet> </Span> <Span color="Comment" ruleSet="CommentMarkerSet"> <Begin>//</Begin> </Span> <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true"> <Begin>/\*</Begin> <End>\*/</End> </Span> <Span color="String"> <Begin>"</Begin> <End>"</End> <RuleSet> <!-- span for escape sequences --> <Span begin="\\" end="."/> </RuleSet> </Span> <Span color="Char"> <Begin>'</Begin> <End>'</End> <RuleSet> <!-- span for escape sequences --> <Span begin="\\" end="."/> </RuleSet> </Span> <Span color="String" multiline="true"> <Begin color="String">@"</Begin> <End>"</End> <RuleSet> <!-- span for escape sequences --> <Span begin='""' end=""/> </RuleSet> </Span> <Span color="String"> <Begin>\$"</Begin> <End>"</End> <RuleSet> <!-- span for escape sequences --> <Span begin="\\" end="."/> <Span begin="\{\{" end=""/> <!-- string interpolation --> <Span begin="{" end="}" color="StringInterpolation" ruleSet=""/> </RuleSet> </Span> <!-- Digits --> <Rule color="NumberLiteral"> \b0[xX][0-9a-fA-F]+ # hex number | ( \b\d+(\.[0-9]+)? #number with optional floating point | \.[0-9]+ #or just starting with floating point ) ([eE][+-]?[0-9]+)? # optional exponent </Rule> </RuleSet> </SyntaxDefinition>
ILSpy/ILSpy/TextView/CSharp-Mode.xshd/0
{ "file_path": "ILSpy/ILSpy/TextView/CSharp-Mode.xshd", "repo_id": "ILSpy", "token_count": 2594 }
268
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:styles="urn:TomsToolbox.Wpf.Styles" xmlns:themes="clr-namespace:ICSharpCode.ILSpy.Themes"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/AvalonDock.Themes.VS2013;component/lighttheme.xaml" /> </ResourceDictionary.MergedDictionaries> <SolidColorBrush x:Key="{x:Static themes:ResourceKeys.TextBackgroundBrush}" Color="White" /> <SolidColorBrush x:Key="{x:Static themes:ResourceKeys.TextForegroundBrush}" Color="Black" /> <SolidColorBrush x:Key="{x:Static themes:ResourceKeys.SearchResultBackgroundBrush}" Color="LightGreen" /> <SolidColorBrush x:Key="{x:Static themes:ResourceKeys.LineNumbersForegroundBrush}" Color="Gray" /> <SolidColorBrush x:Key="{x:Static themes:ResourceKeys.CurrentLineBackgroundBrush}" Color="#1614DCE0" /> <Pen x:Key="{x:Static themes:ResourceKeys.CurrentLineBorderPen}" Brush="#3400FF6E" Thickness="1" /> <SolidColorBrush x:Key="{x:Static themes:ResourceKeys.BracketHighlightBackgroundBrush}" Color="#160000FF" /> <Pen x:Key="{x:Static themes:ResourceKeys.BracketHighlightBorderPen}" Brush="#340000FF" Thickness="1" /> <Color x:Key="{x:Static SystemColors.ControlLightLightColorKey}">#FCFCFC</Color> <Color x:Key="{x:Static SystemColors.ControlLightColorKey}">#D8D8E0</Color> <Color x:Key="{x:Static SystemColors.ControlColorKey}">#F5F5F5</Color> <Color x:Key="{x:Static SystemColors.ControlDarkColorKey}">#C2C3C9</Color> <Color x:Key="{x:Static SystemColors.ControlDarkDarkColorKey}">#686868</Color> <Color x:Key="{x:Static SystemColors.ControlTextColorKey}">#1E1E1E</Color> <Color x:Key="{x:Static SystemColors.GrayTextColorKey}">#717171</Color> <Color x:Key="{x:Static SystemColors.HighlightColorKey}">#3399FF</Color> <Color x:Key="{x:Static SystemColors.HighlightTextColorKey}">#FFFFFF</Color> <Color x:Key="{x:Static SystemColors.MenuColorKey}">#F6F6F6</Color> <Color x:Key="{x:Static SystemColors.MenuBarColorKey}">#F6F6F6</Color> <Color x:Key="{x:Static SystemColors.MenuTextColorKey}">#1E1E1E</Color> <Color x:Key="{x:Static SystemColors.WindowColorKey}">#FFFFFF</Color> <Color x:Key="{x:Static SystemColors.WindowTextColorKey}">#1E1E1E</Color> <Color x:Key="{x:Static SystemColors.ActiveCaptionColorKey}">#EEEEF2</Color> <Color x:Key="{x:Static SystemColors.ActiveBorderColorKey}">#71BDE2</Color> <Color x:Key="{x:Static SystemColors.ActiveCaptionTextColorKey}">#1E1E1E</Color> <Color x:Key="{x:Static SystemColors.InactiveCaptionColorKey}">#EEEEF2</Color> <Color x:Key="{x:Static SystemColors.InactiveBorderColorKey}">#CCCEDB</Color> <Color x:Key="{x:Static SystemColors.InactiveCaptionTextColorKey}">#808080</Color> <SolidColorBrush x:Key="{x:Static SystemColors.ControlLightLightBrushKey}" Color="#FCFCFC" /> <SolidColorBrush x:Key="{x:Static SystemColors.ControlLightBrushKey}" Color="#D8D8E0" /> <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#F5F5F5" /> <SolidColorBrush x:Key="{x:Static SystemColors.ControlDarkBrushKey}" Color="#C2C3C9" /> <SolidColorBrush x:Key="{x:Static SystemColors.ControlDarkDarkBrushKey}" Color="#686868" /> <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="#1E1E1E" /> <SolidColorBrush x:Key="{x:Static SystemColors.GrayTextBrushKey}" Color="#717171" /> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#3399FF" /> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="#FFFFFF" /> <SolidColorBrush x:Key="{x:Static SystemColors.MenuBrushKey}" Color="#F6F6F6" /> <SolidColorBrush x:Key="{x:Static SystemColors.MenuBarBrushKey}" Color="#F6F6F6" /> <SolidColorBrush x:Key="{x:Static SystemColors.MenuTextBrushKey}" Color="#1E1E1E" /> <SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="#FFFFFF" /> <SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}" Color="#1E1E1E" /> <SolidColorBrush x:Key="{x:Static SystemColors.ActiveCaptionBrushKey}" Color="#EEEEF2" /> <SolidColorBrush x:Key="{x:Static SystemColors.ActiveBorderBrushKey}" Color="#71BDE2" /> <SolidColorBrush x:Key="{x:Static SystemColors.ActiveCaptionTextBrushKey}" Color="#1E1E1E" /> <SolidColorBrush x:Key="{x:Static SystemColors.InactiveCaptionBrushKey}" Color="#EEEEF2" /> <SolidColorBrush x:Key="{x:Static SystemColors.InactiveBorderBrushKey}" Color="#CCCEDB" /> <SolidColorBrush x:Key="{x:Static SystemColors.InactiveCaptionTextBrushKey}" Color="#808080" /> <SolidColorBrush x:Key="{x:Static styles:ResourceKeys.BorderBrush}" Color="#CCCEDB" /> <SolidColorBrush x:Key="{x:Static styles:ResourceKeys.DisabledBrush}" Color="#EEEEF2" /> </ResourceDictionary>
ILSpy/ILSpy/Themes/Base.Light.xaml/0
{ "file_path": "ILSpy/ILSpy/Themes/Base.Light.xaml", "repo_id": "ILSpy", "token_count": 1833 }
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.Reflection.Metadata; using System.Windows.Media; using ICSharpCode.Decompiler; namespace ICSharpCode.ILSpy.TreeNodes { using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpyX; /// <summary> /// Represents a property in the TreeView. /// </summary> public sealed class PropertyTreeNode : ILSpyTreeNode, IMemberTreeNode { readonly bool isIndexer; public PropertyTreeNode(IProperty property) { this.PropertyDefinition = property ?? throw new ArgumentNullException(nameof(property)); this.isIndexer = property.IsIndexer; if (property.CanGet) this.Children.Add(new MethodTreeNode(property.Getter)); if (property.CanSet) this.Children.Add(new MethodTreeNode(property.Setter)); /*foreach (var m in property.OtherMethods) this.Children.Add(new MethodTreeNode(m));*/ } public IProperty PropertyDefinition { get; } public override object Text => GetText(GetPropertyDefinition(), Language) + GetSuffixString(PropertyDefinition); private IProperty GetPropertyDefinition() { return ((MetadataModule)PropertyDefinition.ParentModule.PEFile ?.GetTypeSystemWithCurrentOptionsOrNull() ?.MainModule)?.GetDefinition((PropertyDefinitionHandle)PropertyDefinition.MetadataToken) ?? PropertyDefinition; } public static object GetText(IProperty property, Language language) { return language.PropertyToString(property, false, false, false); } public override object Icon => GetIcon(GetPropertyDefinition()); public static ImageSource GetIcon(IProperty property) { return Images.GetIcon(property.IsIndexer ? MemberIcon.Indexer : MemberIcon.Property, MethodTreeNode.GetOverlayIcon(property.Accessibility), property.IsStatic); } public override FilterResult Filter(FilterSettings settings) { if (settings.ShowApiLevel == ApiVisibility.PublicOnly && !IsPublicAPI) return FilterResult.Hidden; if (settings.SearchTermMatches(PropertyDefinition.Name) && (settings.ShowApiLevel == ApiVisibility.All || settings.Language.ShowMember(PropertyDefinition))) return FilterResult.Match; else return FilterResult.Hidden; } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.DecompileProperty(PropertyDefinition, output, options); } public override bool IsPublicAPI { get { switch (GetPropertyDefinition().Accessibility) { case Accessibility.Public: case Accessibility.ProtectedOrInternal: case Accessibility.Protected: return true; default: return false; } } } IEntity IMemberTreeNode.Member => PropertyDefinition; public override string ToString() { return Languages.ILLanguage.PropertyToString(PropertyDefinition, false, false, false); } } }
ILSpy/ILSpy/TreeNodes/PropertyTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/TreeNodes/PropertyTreeNode.cs", "repo_id": "ILSpy", "token_count": 1191 }
270
<UserControl x:Class="ICSharpCode.ILSpy.DebugSteps" 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:local="clr-namespace:ICSharpCode.ILSpy" xmlns:properties="clr-namespace:ICSharpCode.ILSpy.Properties" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <DockPanel> <StackPanel DockPanel.Dock="Top" Orientation="Horizontal"> <CheckBox Margin="3" Content="{x:Static properties:Resources.UseFieldSugar}" IsChecked="{Binding UseFieldSugar, Source={x:Static local:DebugSteps.Options}}" /> <CheckBox Margin="3" Content="{x:Static properties:Resources.UseLogicOperationSugar}" IsChecked="{Binding UseLogicOperationSugar, Source={x:Static local:DebugSteps.Options}}" /> <CheckBox Margin="3" Content="{x:Static properties:Resources.ShowILRanges}" IsChecked="{Binding ShowILRanges, Source={x:Static local:DebugSteps.Options}}" /> <CheckBox Margin="3" Content="{x:Static properties:Resources.ShowChildIndexInBlock}" IsChecked="{Binding ShowChildIndexInBlock, Source={x:Static local:DebugSteps.Options}}" /> </StackPanel> <TreeView Name="tree" MouseDoubleClick="ShowStateAfter_Click" KeyDown="tree_KeyDown"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Children}"> <TextBlock Text="{Binding Description}" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> <TreeView.ContextMenu> <ContextMenu> <MenuItem Header="{x:Static properties:Resources.ShowStateBeforeThisStep}" Click="ShowStateBefore_Click" InputGestureText="Shift+Enter" /> <MenuItem Header="{x:Static properties:Resources.ShowStateAfterThisStep}" Click="ShowStateAfter_Click" InputGestureText="Enter" /> <MenuItem Header="{x:Static properties:Resources.DebugThisStep}" Click="DebugStep_Click" /> </ContextMenu> </TreeView.ContextMenu> </TreeView> </DockPanel> </UserControl>
ILSpy/ILSpy/Views/DebugSteps.xaml/0
{ "file_path": "ILSpy/ILSpy/Views/DebugSteps.xaml", "repo_id": "ILSpy", "token_count": 814 }
271
// 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.Diagnostics; using System.Windows; using System.Windows.Media; namespace ICSharpCode.TreeView { class LinesRenderer : FrameworkElement { static LinesRenderer() { pen = new Pen(Brushes.LightGray, 1); pen.Freeze(); } static Pen pen; SharpTreeNodeView NodeView { get { return TemplatedParent as SharpTreeNodeView; } } protected override void OnRender(DrawingContext dc) { if (NodeView.Node == null) { // This seems to happen sometimes with DataContext==DisconnectedItem, // though I'm not sure why WPF would call OnRender() on a disconnected node Debug.WriteLine($"LinesRenderer.OnRender() called with DataContext={NodeView.DataContext}"); return; } var indent = NodeView.CalculateIndent(); var p = new Point(indent + 4.5, 0); if (!NodeView.Node.IsRoot || NodeView.ParentTreeView.ShowRootExpander) { dc.DrawLine(pen, new Point(p.X, ActualHeight / 2), new Point(p.X + 10, ActualHeight / 2)); } if (NodeView.Node.IsRoot) return; if (NodeView.Node.IsLast) { dc.DrawLine(pen, p, new Point(p.X, ActualHeight / 2)); } else { dc.DrawLine(pen, p, new Point(p.X, ActualHeight)); } var current = NodeView.Node; while (true) { p.X -= 19; current = current.Parent; if (p.X < 0) break; if (!current.IsLast) { dc.DrawLine(pen, p, new Point(p.X, ActualHeight)); } } } } }
ILSpy/SharpTreeView/LinesRenderer.cs/0
{ "file_path": "ILSpy/SharpTreeView/LinesRenderer.cs", "repo_id": "ILSpy", "token_count": 892 }
272
// 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.Runtime.InteropServices; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEngine.U2D; using Unity.Collections.LowLevel.Unsafe; using Unity.Collections; namespace UnityEditor.U2D { [UsedByNativeCode] public abstract class ScriptablePacker : ScriptableObject { public enum PackTransform { None = 0, FlipHorizontal = 1, FlipVertical = 2, Rotate180 = 3, } [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] public struct SpritePack { public int x; public int y; public int page; public PackTransform rot; }; [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] public struct SpriteData { public int guid; public int texIndex; public int indexCount; public int vertexCount; public int indexOffset; public int vertexOffset; public RectInt rect; public SpritePack output; }; [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] public struct TextureData { public int width; public int height; public int bufferOffset; }; [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] internal struct PackerDataInternal { public int colorCount; public IntPtr colorData; public int spriteCount; public IntPtr spriteData; public int textureCount; public IntPtr textureData; public int indexCount; public IntPtr indexData; public int vertexCount; public IntPtr vertexData; }; [StructLayout(LayoutKind.Sequential)] public struct PackerData { public NativeArray<Color32> colorData; public NativeArray<SpriteData> spriteData; public NativeArray<TextureData> textureData; public NativeArray<int> indexData; public NativeArray<Vector2> vertexData; }; // Public function to pack. public abstract bool Pack(SpriteAtlasPackingSettings config, SpriteAtlasTextureSettings setting, PackerData input); // Internal Glue function. [RequiredByNativeCode] internal bool PackInternal(SpriteAtlasPackingSettings config, SpriteAtlasTextureSettings setting, PackerDataInternal packerData) { var input = new PackerData(); unsafe { input.colorData = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Color32>((void*)packerData.colorData, packerData.colorCount, Allocator.None); input.spriteData = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<SpriteData>((void*)packerData.spriteData, packerData.spriteCount, Allocator.None); input.textureData = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<TextureData>((void*)packerData.textureData, packerData.textureCount, Allocator.None); input.indexData = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>((void*)packerData.indexData, packerData.indexCount, Allocator.None); input.vertexData = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vector2>((void*)packerData.vertexData, packerData.vertexCount, Allocator.None); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref input.colorData, AtomicSafetyHandle.GetTempMemoryHandle()); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref input.spriteData, AtomicSafetyHandle.GetTempMemoryHandle()); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref input.textureData, AtomicSafetyHandle.GetTempMemoryHandle()); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref input.indexData, AtomicSafetyHandle.GetTempMemoryHandle()); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref input.vertexData, AtomicSafetyHandle.GetTempMemoryHandle()); } return Pack(config, setting, input); } }; // SpriteAtlas Importer lets you modify [[SpriteAtlas]] [NativeHeader("Editor/Src/2D/SpriteAtlas/SpriteAtlasAsset.h")] [NativeType(Header = "Editor/Src/2D/SpriteAtlas/SpriteAtlasAsset.h")] public class SpriteAtlasAsset : UnityEngine.Object { public SpriteAtlasAsset() { Internal_Create(this); } extern private static void Internal_Create([Writable] SpriteAtlasAsset self); extern public bool isVariant { [NativeMethod("GetIsVariant")] get; } extern public void SetIsVariant(bool value); extern public void SetMasterAtlas(SpriteAtlas atlas); extern public SpriteAtlas GetMasterAtlas(); extern internal UnityEngine.Object GetPacker(); extern internal void SetPacker(UnityEngine.Object obj); extern public void Add(UnityEngine.Object[] objects); extern public void Remove(UnityEngine.Object[] objects); public void SetScriptablePacker(ScriptablePacker obj) { SetPacker(obj); } extern internal void RemoveAt(int index); [Obsolete("SetVariantScale is no longer supported and will be removed. Use SpriteAtlasImporter.SetVariantScale instead.")] public void SetVariantScale(float value) { } [Obsolete("SetIncludeInBuild is no longer supported and will be removed. Use SpriteAtlasImporter.SetIncludeInBuild instead.")] public void SetIncludeInBuild(bool value) { } [Obsolete("IsIncludeInBuild is no longer supported and will be removed. Use SpriteAtlasImporter.IsIncludeInBuild instead.")] public bool IsIncludeInBuild() { return true; } [Obsolete("SetPlatformSettings is no longer supported and will be removed. Use SpriteAtlasImporter.SetPlatformSettings instead.")] public void SetPlatformSettings(TextureImporterPlatformSettings src) { } [Obsolete("SetTextureSettings is no longer supported and will be removed. Use SpriteAtlasImporter.SetTextureSettings instead.")] public void SetTextureSettings(SpriteAtlasTextureSettings src) { } [Obsolete("SetPackingSettings is no longer supported and will be removed. Use SpriteAtlasImporter.SetPackingSettings instead.")] public void SetPackingSettings(SpriteAtlasPackingSettings src) { } [Obsolete("GetPackingSettings is no longer supported and will be removed. Use SpriteAtlasImporter.GetPackingSettings instead.")] public SpriteAtlasPackingSettings GetPackingSettings() { return new SpriteAtlasPackingSettings(); } [Obsolete("GetTextureSettings is no longer supported and will be removed. Use SpriteAtlasImporter.GetTextureSettings instead.")] public SpriteAtlasTextureSettings GetTextureSettings() { return new SpriteAtlasTextureSettings(); } [Obsolete("GetPlatformSettings is no longer supported and will be removed. Use SpriteAtlasImporter.GetPlatformSettingss instead.")] public TextureImporterPlatformSettings GetPlatformSettings(string buildTarget) { return new TextureImporterPlatformSettings(); } // Load SpriteAtlasAsset public static SpriteAtlasAsset Load(string assetPath) { var objs = UnityEditorInternal.InternalEditorUtility.LoadSerializedFileAndForget(assetPath); return (objs.Length > 0) ? objs[0] as SpriteAtlasAsset : null; } public static void Save(SpriteAtlasAsset asset, string assetPath) { if (asset == null) throw new ArgumentNullException("Parameter asset is null"); var objs = new UnityEngine.Object[] { asset }; UnityEditorInternal.InternalEditorUtility.SaveToSerializedFileAndForget(objs, assetPath, UnityEditor.EditorSettings.serializationMode != UnityEditor.SerializationMode.ForceBinary); } } };
UnityCsReference/Editor/Mono/2D/SpriteAtlas/SpriteAtlasAsset.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/2D/SpriteAtlas/SpriteAtlasAsset.bindings.cs", "repo_id": "UnityCsReference", "token_count": 3129 }
273
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEditor; using Object = UnityEngine.Object; namespace UnityEditorInternal { [Serializable] internal class AnimationClipSelectionItem : AnimationWindowSelectionItem { public static AnimationClipSelectionItem Create(AnimationClip animationClip, Object sourceObject = null) { var selectionItem = new AnimationClipSelectionItem { gameObject = sourceObject as GameObject, scriptableObject = sourceObject as ScriptableObject, animationClip = animationClip, id = 0 }; return selectionItem; } public override bool canPreview { get { return false; } } public override bool canRecord { get { return false; } } public override bool canChangeAnimationClip { get { return false; } } public override bool canSyncSceneSelection { get { return false; } } } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationClipSelectionItem.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationClipSelectionItem.cs", "repo_id": "UnityCsReference", "token_count": 415 }
274
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Collections; using Object = UnityEngine.Object; namespace UnityEditorInternal { [System.Serializable] internal class AnimationWindowKeySelection : ScriptableObject, ISerializationCallbackReceiver { private HashSet<int> m_SelectedKeyHashes; [SerializeField] private List<int> m_SelectedKeyHashesSerialized; public HashSet<int> selectedKeyHashes { get { return m_SelectedKeyHashes ?? (m_SelectedKeyHashes = new HashSet<int>()); } set { m_SelectedKeyHashes = value; } } public void SaveSelection(string undoLabel) { Undo.RegisterCompleteObjectUndo(this, undoLabel); } public void OnBeforeSerialize() { m_SelectedKeyHashesSerialized = m_SelectedKeyHashes.ToList(); } public void OnAfterDeserialize() { m_SelectedKeyHashes = new HashSet<int>(m_SelectedKeyHashesSerialized); } } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeySelection.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeySelection.cs", "repo_id": "UnityCsReference", "token_count": 493 }
275
// 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; using System.Collections.Generic; namespace UnityEditor { internal class BoolCurveRenderer : NormalCurveRenderer { public BoolCurveRenderer(AnimationCurve curve) : base(curve) { } public override float ClampedValue(float value) { return value != 0.0f ? 1.0f : 0.0f; } public override float EvaluateCurveSlow(float time) { return ClampedValue(GetCurve().Evaluate(time)); } } } // namespace
UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveRenderer/BoolCurveRenderer.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveRenderer/BoolCurveRenderer.cs", "repo_id": "UnityCsReference", "token_count": 309 }
276
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { interface IAnimationWindowController { void OnCreate(AnimationWindow animationWindow, UnityEngine.Component component); void OnDestroy(); void OnSelectionChanged(); float time { get; set; } int frame { get; set; } bool canPlay { get; } bool playing { get; set; } bool PlaybackUpdate(); bool canPreview { get; } bool previewing { get; set; } bool canRecord { get; } bool recording { get; set; } void ResampleAnimation(); void ProcessCandidates(); void ClearCandidates(); EditorCurveBinding[] GetAnimatableBindings(GameObject gameObject); EditorCurveBinding[] GetAnimatableBindings(); System.Type GetValueType(EditorCurveBinding binding); float GetFloatValue(EditorCurveBinding binding); int GetIntValue(EditorCurveBinding binding); UnityEngine.Object GetObjectReferenceValue(EditorCurveBinding binding); } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/IAnimationWindowController.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/IAnimationWindowController.cs", "repo_id": "UnityCsReference", "token_count": 437 }
277
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { // NOTE: do _not_ use GUILayout to get the rectangle for zoomable area, // will not work and will start failing miserably (mouse events not hitting it, etc.). // That's because ZoomableArea is using GUILayout itself, and needs an actual // physical rectangle. [System.Serializable] internal class ZoomableArea { // Global state private static Vector2 m_MouseDownPosition = new Vector2(-1000000, -1000000); // in transformed space private static int zoomableAreaHash = "ZoomableArea".GetHashCode(); // Range lock settings [SerializeField] private bool m_HRangeLocked; [SerializeField] private bool m_VRangeLocked; public bool hRangeLocked { get { return m_HRangeLocked; } set { m_HRangeLocked = value; } } public bool vRangeLocked { get { return m_VRangeLocked; } set { m_VRangeLocked = value; } } // Zoom lock settings public bool hZoomLockedByDefault = false; public bool vZoomLockedByDefault = false; [SerializeField] private float m_HBaseRangeMin = 0; [SerializeField] private float m_HBaseRangeMax = 1; [SerializeField] private float m_VBaseRangeMin = 0; [SerializeField] private float m_VBaseRangeMax = 1; public float hBaseRangeMin { get { return m_HBaseRangeMin; } set { m_HBaseRangeMin = value; } } public float hBaseRangeMax { get { return m_HBaseRangeMax; } set { m_HBaseRangeMax = value; } } public float vBaseRangeMin { get { return m_VBaseRangeMin; } set { m_VBaseRangeMin = value; } } public float vBaseRangeMax { get { return m_VBaseRangeMax; } set { m_VBaseRangeMax = value; } } [SerializeField] private bool m_HAllowExceedBaseRangeMin = true; [SerializeField] private bool m_HAllowExceedBaseRangeMax = true; [SerializeField] private bool m_VAllowExceedBaseRangeMin = true; [SerializeField] private bool m_VAllowExceedBaseRangeMax = true; public bool hAllowExceedBaseRangeMin { get { return m_HAllowExceedBaseRangeMin; } set { m_HAllowExceedBaseRangeMin = value; } } public bool hAllowExceedBaseRangeMax { get { return m_HAllowExceedBaseRangeMax; } set { m_HAllowExceedBaseRangeMax = value; } } public bool vAllowExceedBaseRangeMin { get { return m_VAllowExceedBaseRangeMin; } set { m_VAllowExceedBaseRangeMin = value; } } public bool vAllowExceedBaseRangeMax { get { return m_VAllowExceedBaseRangeMax; } set { m_VAllowExceedBaseRangeMax = value; } } public float hRangeMin { get { return (hAllowExceedBaseRangeMin ? Mathf.NegativeInfinity : hBaseRangeMin); } set { SetAllowExceed(ref m_HBaseRangeMin, ref m_HAllowExceedBaseRangeMin, value); } } public float hRangeMax { get { return (hAllowExceedBaseRangeMax ? Mathf.Infinity : hBaseRangeMax); } set { SetAllowExceed(ref m_HBaseRangeMax, ref m_HAllowExceedBaseRangeMax, value); } } public float vRangeMin { get { return (vAllowExceedBaseRangeMin ? Mathf.NegativeInfinity : vBaseRangeMin); } set { SetAllowExceed(ref m_VBaseRangeMin, ref m_VAllowExceedBaseRangeMin, value); } } public float vRangeMax { get { return (vAllowExceedBaseRangeMax ? Mathf.Infinity : vBaseRangeMax); } set { SetAllowExceed(ref m_VBaseRangeMax, ref m_VAllowExceedBaseRangeMax, value); } } private void SetAllowExceed(ref float rangeEnd, ref bool allowExceed, float value) { if (value == Mathf.NegativeInfinity || value == Mathf.Infinity) { rangeEnd = (value == Mathf.NegativeInfinity ? 0 : 1); allowExceed = true; } else { rangeEnd = value; allowExceed = false; } } private const float kMinScale = 0.00001f; private const float kMaxScale = 100000.0f; private float m_HScaleMin = kMinScale; private float m_HScaleMax = kMaxScale; private float m_VScaleMin = kMinScale; private float m_VScaleMax = kMaxScale; private float m_MinWidth = 0.05f; private const float kMinHeight = 0.05f; private const float k_ScrollStepSize = 10f; // mirrors GUI scrollstepsize as there is no global const for this. public float minWidth { get { return m_MinWidth; } set { if (value > 0) m_MinWidth = value; else { Debug.LogWarning("Zoomable area width cannot have a value of " + "or below 0. Reverting back to a default value of 0.05f"); m_MinWidth = 0.05f; } } } public float hScaleMin { get { return m_HScaleMin; } set { m_HScaleMin = Mathf.Clamp(value, kMinScale, kMaxScale); styles.enableSliderZoomHorizontal = allowSliderZoomHorizontal; } } public float hScaleMax { get { return m_HScaleMax; } set { m_HScaleMax = Mathf.Clamp(value, kMinScale, kMaxScale); styles.enableSliderZoomHorizontal = allowSliderZoomHorizontal; } } public float vScaleMin { get { return m_VScaleMin; } set { m_VScaleMin = Mathf.Clamp(value, kMinScale, kMaxScale); styles.enableSliderZoomVertical = allowSliderZoomVertical; } } public float vScaleMax { get { return m_VScaleMax; } set { m_VScaleMax = Mathf.Clamp(value, kMinScale, kMaxScale); styles.enableSliderZoomVertical = allowSliderZoomVertical; } } // Window resize settings [SerializeField] private bool m_ScaleWithWindow = false; public bool scaleWithWindow { get { return m_ScaleWithWindow; } set { m_ScaleWithWindow = value; } } // Slider settings [SerializeField] private bool m_HSlider = true; [SerializeField] private bool m_VSlider = true; public bool hSlider { get { return m_HSlider; } set { Rect r = rect; m_HSlider = value; rect = r; } } public bool vSlider { get { return m_VSlider; } set { Rect r = rect; m_VSlider = value; rect = r; } } [SerializeField] private bool m_IgnoreScrollWheelUntilClicked = false; public bool ignoreScrollWheelUntilClicked { get { return m_IgnoreScrollWheelUntilClicked; } set { m_IgnoreScrollWheelUntilClicked = value; } } [SerializeField] private bool m_EnableMouseInput = true; public bool enableMouseInput { get { return m_EnableMouseInput; } set { m_EnableMouseInput = value; } } [SerializeField] private bool m_EnableSliderZoomHorizontal = true; [SerializeField] private bool m_EnableSliderZoomVertical = true; // if the min and max scaling does not allow for actual zooming, there is no point in allowing it protected bool allowSliderZoomHorizontal { get { return m_EnableSliderZoomHorizontal && m_HScaleMin < m_HScaleMax; } } protected bool allowSliderZoomVertical { get { return m_EnableSliderZoomVertical && m_VScaleMin < m_VScaleMax; } } public bool m_UniformScale; public bool uniformScale { get { return m_UniformScale; } set { m_UniformScale = value; } } // This is optional now, but used to be default behaviour because ZoomableAreas are mostly graphs with +Y being up public enum YDirection { Positive, Negative } [SerializeField] private YDirection m_UpDirection = YDirection.Positive; public YDirection upDirection { get { return m_UpDirection; } set { if (m_UpDirection != value) { m_UpDirection = value; m_Scale.y = -m_Scale.y; } } } // View and drawing settings [SerializeField] private Rect m_DrawArea = new Rect(0, 0, 100, 100); internal void SetDrawRectHack(Rect r) { m_DrawArea = r; } [SerializeField] internal Vector2 m_Scale = new Vector2(1, -1); [SerializeField] internal Vector2 m_Translation = new Vector2(0, 0); [SerializeField] private float m_MarginLeft, m_MarginRight, m_MarginTop, m_MarginBottom; [SerializeField] private Rect m_LastShownAreaInsideMargins = new Rect(0, 0, 100, 100); public Vector2 scale { get { return m_Scale; } } public Vector2 translation { get { return m_Translation; } } public float margin { set { m_MarginLeft = m_MarginRight = m_MarginTop = m_MarginBottom = value; } } public float leftmargin { get { return m_MarginLeft; } set { m_MarginLeft = value; } } public float rightmargin { get { return m_MarginRight; } set { m_MarginRight = value; } } public float topmargin { get { return m_MarginTop; } set { m_MarginTop = value; } } public float bottommargin { get { return m_MarginBottom; } set { m_MarginBottom = value; } } public float vSliderWidth { get { return vSlider ? styles.sliderWidth : 0f; } } public float hSliderHeight { get { return hSlider ? styles.sliderWidth : 0f; } } // IDs for controls internal int areaControlID; int verticalScrollbarID, horizontalScrollbarID; [SerializeField] bool m_MinimalGUI; public class Styles { public GUIStyle horizontalScrollbar; public GUIStyle horizontalMinMaxScrollbarThumb { get { return GetSliderAxisStyle(enableSliderZoomHorizontal).horizontal; } } public GUIStyle horizontalScrollbarLeftButton; public GUIStyle horizontalScrollbarRightButton; public GUIStyle verticalScrollbar; public GUIStyle verticalMinMaxScrollbarThumb { get { return GetSliderAxisStyle(enableSliderZoomVertical).vertical; } } public GUIStyle verticalScrollbarUpButton; public GUIStyle verticalScrollbarDownButton; public bool enableSliderZoomHorizontal; public bool enableSliderZoomVertical; public float sliderWidth; public float visualSliderWidth; private bool minimalGUI; private SliderTypeStyles.SliderAxisStyles GetSliderAxisStyle(bool enableSliderZoom) { if (minimalGUI) return enableSliderZoom ? minimalSliderStyles.minMaxSliders : minimalSliderStyles.scrollbar; else return enableSliderZoom ? normalSliderStyles.minMaxSliders : normalSliderStyles.scrollbar; } private static SliderTypeStyles minimalSliderStyles; private static SliderTypeStyles normalSliderStyles; private class SliderTypeStyles { public SliderAxisStyles scrollbar; public SliderAxisStyles minMaxSliders; public class SliderAxisStyles { public GUIStyle horizontal; public GUIStyle vertical; } } public Styles(bool minimalGUI) { if (minimalGUI) { visualSliderWidth = 0; sliderWidth = 13; } else { visualSliderWidth = 13; sliderWidth = 13; } } public void InitGUIStyles(bool minimalGUI, bool enableSliderZoom) { InitGUIStyles(minimalGUI, enableSliderZoom, enableSliderZoom); } public void InitGUIStyles(bool minimalGUI, bool enableSliderZoomHorizontal, bool enableSliderZoomVertical) { this.minimalGUI = minimalGUI; this.enableSliderZoomHorizontal = enableSliderZoomHorizontal; this.enableSliderZoomVertical = enableSliderZoomVertical; if (minimalGUI) { if (minimalSliderStyles == null) { minimalSliderStyles = new SliderTypeStyles() { scrollbar = new SliderTypeStyles.SliderAxisStyles() { horizontal = "MiniSliderhorizontal", vertical = "MiniSliderVertical" }, minMaxSliders = new SliderTypeStyles.SliderAxisStyles() { horizontal = "MiniMinMaxSliderHorizontal", vertical = "MiniMinMaxSlidervertical" }, }; } horizontalScrollbarLeftButton = GUIStyle.none; horizontalScrollbarRightButton = GUIStyle.none; horizontalScrollbar = GUIStyle.none; verticalScrollbarUpButton = GUIStyle.none; verticalScrollbarDownButton = GUIStyle.none; verticalScrollbar = GUIStyle.none; } else { if (normalSliderStyles == null) { normalSliderStyles = new SliderTypeStyles() { scrollbar = new SliderTypeStyles.SliderAxisStyles() { horizontal = "horizontalscrollbarthumb", vertical = "verticalscrollbarthumb" }, minMaxSliders = new SliderTypeStyles.SliderAxisStyles() { horizontal = "horizontalMinMaxScrollbarThumb", vertical = "verticalMinMaxScrollbarThumb" }, }; } horizontalScrollbarLeftButton = "horizontalScrollbarLeftbutton"; horizontalScrollbarRightButton = "horizontalScrollbarRightbutton"; horizontalScrollbar = GUI.skin.horizontalScrollbar; verticalScrollbarUpButton = "verticalScrollbarUpbutton"; verticalScrollbarDownButton = "verticalScrollbarDownbutton"; verticalScrollbar = GUI.skin.verticalScrollbar; } } } private Styles m_Styles; protected Styles styles { get { if (m_Styles == null) m_Styles = new Styles(m_MinimalGUI); return m_Styles; } } public Rect rect { get { return new Rect(drawRect.x, drawRect.y, drawRect.width + (m_VSlider ? styles.visualSliderWidth : 0), drawRect.height + (m_HSlider ? styles.visualSliderWidth : 0)); } set { Rect newDrawArea = new Rect(value.x, value.y, value.width - (m_VSlider ? styles.visualSliderWidth : 0), value.height - (m_HSlider ? styles.visualSliderWidth : 0)); if (newDrawArea != m_DrawArea) { if (m_ScaleWithWindow) { m_DrawArea = newDrawArea; shownAreaInsideMargins = m_LastShownAreaInsideMargins; } else { m_Translation += new Vector2((newDrawArea.width - m_DrawArea.width) / 2, (newDrawArea.height - m_DrawArea.height) / 2); m_DrawArea = newDrawArea; } } EnforceScaleAndRange(); } } public Rect drawRect { get { return m_DrawArea; } } public void SetShownHRangeInsideMargins(float min, float max) { float widthInsideMargins = drawRect.width - leftmargin - rightmargin; if (widthInsideMargins < m_MinWidth) widthInsideMargins = m_MinWidth; float denum = max - min; if (denum < m_MinWidth) denum = m_MinWidth; m_Scale.x = widthInsideMargins / denum; m_Translation.x = -min * m_Scale.x + leftmargin; EnforceScaleAndRange(); } public void SetShownHRange(float min, float max) { float denum = max - min; if (denum < m_MinWidth) denum = m_MinWidth; m_Scale.x = drawRect.width / denum; m_Translation.x = -min * m_Scale.x; EnforceScaleAndRange(); } public void SetShownVRangeInsideMargins(float min, float max) { float heightInsideMargins = drawRect.height - topmargin - bottommargin; if (heightInsideMargins < kMinHeight) heightInsideMargins = kMinHeight; float denum = max - min; if (denum < kMinHeight) denum = kMinHeight; if (m_UpDirection == YDirection.Positive) { m_Scale.y = -heightInsideMargins / denum; m_Translation.y = drawRect.height - min * m_Scale.y - topmargin; } else { m_Scale.y = heightInsideMargins / denum; m_Translation.y = -min * m_Scale.y - bottommargin; } EnforceScaleAndRange(); } public void SetShownVRange(float min, float max) { float denum = max - min; if (denum < kMinHeight) denum = kMinHeight; if (m_UpDirection == YDirection.Positive) { m_Scale.y = -drawRect.height / denum; m_Translation.y = drawRect.height - min * m_Scale.y; } else { m_Scale.y = drawRect.height / denum; m_Translation.y = -min * m_Scale.y; } EnforceScaleAndRange(); } // ShownArea is in curve space public Rect shownArea { set { float width = (value.width < m_MinWidth) ? m_MinWidth : value.width; float height = (value.height < kMinHeight) ? kMinHeight : value.height; if (m_UpDirection == YDirection.Positive) { m_Scale.x = drawRect.width / width; m_Scale.y = -drawRect.height / height; m_Translation.x = -value.x * m_Scale.x; m_Translation.y = drawRect.height - value.y * m_Scale.y; } else { m_Scale.x = drawRect.width / width; m_Scale.y = drawRect.height / height; m_Translation.x = -value.x * m_Scale.x; m_Translation.y = -value.y * m_Scale.y; } EnforceScaleAndRange(); } get { if (m_UpDirection == YDirection.Positive) { return new Rect( -m_Translation.x / m_Scale.x, -(m_Translation.y - drawRect.height) / m_Scale.y, drawRect.width / m_Scale.x, drawRect.height / -m_Scale.y ); } else { return new Rect( -m_Translation.x / m_Scale.x, -m_Translation.y / m_Scale.y, drawRect.width / m_Scale.x, drawRect.height / m_Scale.y ); } } } public Rect shownAreaInsideMargins { set { shownAreaInsideMarginsInternal = value; EnforceScaleAndRange(); } get { return shownAreaInsideMarginsInternal; } } private Rect shownAreaInsideMarginsInternal { set { float width = (value.width < m_MinWidth) ? m_MinWidth : value.width; float height = (value.height < kMinHeight) ? kMinHeight : value.height; float widthInsideMargins = drawRect.width - leftmargin - rightmargin; if (widthInsideMargins < m_MinWidth) widthInsideMargins = m_MinWidth; float heightInsideMargins = drawRect.height - topmargin - bottommargin; if (heightInsideMargins < kMinHeight) heightInsideMargins = kMinHeight; if (m_UpDirection == YDirection.Positive) { m_Scale.x = widthInsideMargins / width; m_Scale.y = -heightInsideMargins / height; m_Translation.x = -value.x * m_Scale.x + leftmargin; m_Translation.y = drawRect.height - value.y * m_Scale.y - topmargin; } else { m_Scale.x = widthInsideMargins / width; m_Scale.y = heightInsideMargins / height; m_Translation.x = -value.x * m_Scale.x + leftmargin; m_Translation.y = -value.y * m_Scale.y + topmargin; } } get { float leftmarginRel = leftmargin / m_Scale.x; float rightmarginRel = rightmargin / m_Scale.x; float topmarginRel = topmargin / m_Scale.y; float bottommarginRel = bottommargin / m_Scale.y; Rect area = shownArea; area.x += leftmarginRel; area.y -= topmarginRel; area.width -= leftmarginRel + rightmarginRel; area.height += topmarginRel + bottommarginRel; return area; } } float GetWidthInsideMargins(float widthWithMargins, bool substractSliderWidth = false) { float width = (widthWithMargins < m_MinWidth) ? m_MinWidth : widthWithMargins; float widthInsideMargins = width - leftmargin - rightmargin - (substractSliderWidth ? (m_VSlider ? styles.visualSliderWidth : 0) : 0); return Mathf.Max(widthInsideMargins, m_MinWidth); } float GetHeightInsideMargins(float heightWithMargins, bool substractSliderHeight = false) { float height = (heightWithMargins < kMinHeight) ? kMinHeight : heightWithMargins; float heightInsideMargins = height - topmargin - bottommargin - (substractSliderHeight ? (m_HSlider ? styles.visualSliderWidth : 0) : 0); return Mathf.Max(heightInsideMargins, kMinHeight); } public virtual Bounds drawingBounds { get { return new Bounds( new Vector3((hBaseRangeMin + hBaseRangeMax) * 0.5f, (vBaseRangeMin + vBaseRangeMax) * 0.5f, 0), new Vector3(hBaseRangeMax - hBaseRangeMin, vBaseRangeMax - vBaseRangeMin, 1) ); } } // Utility transform functions public Matrix4x4 drawingToViewMatrix { get { return Matrix4x4.TRS(m_Translation, Quaternion.identity, new Vector3(m_Scale.x, m_Scale.y, 1)); } } public Vector2 DrawingToViewTransformPoint(Vector2 lhs) { return new Vector2(lhs.x * m_Scale.x + m_Translation.x, lhs.y * m_Scale.y + m_Translation.y); } public Vector3 DrawingToViewTransformPoint(Vector3 lhs) { return new Vector3(lhs.x * m_Scale.x + m_Translation.x, lhs.y * m_Scale.y + m_Translation.y, 0); } public Vector2 ViewToDrawingTransformPoint(Vector2 lhs) { return new Vector2((lhs.x - m_Translation.x) / m_Scale.x , (lhs.y - m_Translation.y) / m_Scale.y); } public Vector3 ViewToDrawingTransformPoint(Vector3 lhs) { return new Vector3((lhs.x - m_Translation.x) / m_Scale.x , (lhs.y - m_Translation.y) / m_Scale.y, 0); } public Vector2 DrawingToViewTransformVector(Vector2 lhs) { return new Vector2(lhs.x * m_Scale.x, lhs.y * m_Scale.y); } public Vector3 DrawingToViewTransformVector(Vector3 lhs) { return new Vector3(lhs.x * m_Scale.x, lhs.y * m_Scale.y, 0); } public Vector2 ViewToDrawingTransformVector(Vector2 lhs) { return new Vector2(lhs.x / m_Scale.x, lhs.y / m_Scale.y); } public Vector3 ViewToDrawingTransformVector(Vector3 lhs) { return new Vector3(lhs.x / m_Scale.x, lhs.y / m_Scale.y, 0); } public Vector2 mousePositionInDrawing { get { return ViewToDrawingTransformPoint(Event.current.mousePosition); } } public Vector2 NormalizeInViewSpace(Vector2 vec) { vec = Vector2.Scale(vec, m_Scale); vec /= vec.magnitude; return Vector2.Scale(vec, new Vector2(1 / m_Scale.x, 1 / m_Scale.y)); } // Utility mouse event functions private bool IsZoomEvent() { return ( (Event.current.button == 1 && Event.current.alt) // right+alt drag //|| (Event.current.button == 0 && Event.current.command) // left+commend drag //|| (Event.current.button == 2 && Event.current.command) // middle+command drag ); } private bool IsPanEvent() { return ( (Event.current.button == 0 && Event.current.alt) // left+alt drag || (Event.current.button == 2 && !Event.current.command) // middle drag ); } public ZoomableArea() { m_MinimalGUI = false; } public ZoomableArea(bool minimalGUI) { m_MinimalGUI = minimalGUI; } public ZoomableArea(bool minimalGUI, bool enableSliderZoom) : this(minimalGUI, enableSliderZoom, enableSliderZoom) {} public ZoomableArea(bool minimalGUI, bool enableSliderZoomHorizontal, bool enableSliderZoomVertical) { m_MinimalGUI = minimalGUI; m_EnableSliderZoomHorizontal = enableSliderZoomHorizontal; m_EnableSliderZoomVertical = enableSliderZoomVertical; } public void BeginViewGUI() { if (styles.horizontalScrollbar == null) styles.InitGUIStyles(m_MinimalGUI, allowSliderZoomHorizontal, allowSliderZoomVertical); if (enableMouseInput) HandleZoomAndPanEvents(m_DrawArea); horizontalScrollbarID = GUIUtility.GetControlID(EditorGUIExt.s_MinMaxSliderHash, FocusType.Passive); verticalScrollbarID = GUIUtility.GetControlID(EditorGUIExt.s_MinMaxSliderHash, FocusType.Passive); if (!m_MinimalGUI || Event.current.type != EventType.Repaint) SliderGUI(); } public void HandleZoomAndPanEvents(Rect area) { GUILayout.BeginArea(area); area.x = 0; area.y = 0; int id = GUIUtility.GetControlID(zoomableAreaHash, FocusType.Passive, area); areaControlID = id; switch (Event.current.GetTypeForControl(id)) { case EventType.MouseDown: if (area.Contains(Event.current.mousePosition)) { // Catch keyboard control when clicked inside zoomable area // (used to restrict scrollwheel) GUIUtility.keyboardControl = id; if (IsZoomEvent() || IsPanEvent()) { GUIUtility.hotControl = id; m_MouseDownPosition = mousePositionInDrawing; Event.current.Use(); } } break; case EventType.MouseUp: //Debug.Log("mouse-up!"); if (GUIUtility.hotControl == id) { GUIUtility.hotControl = 0; // If we got the mousedown, the mouseup is ours as well // (no matter if the click was in the area or not) m_MouseDownPosition = new Vector2(-1000000, -1000000); //Event.current.Use(); } break; case EventType.MouseDrag: if (GUIUtility.hotControl != id) break; if (IsZoomEvent()) { // Zoom in around mouse down position HandleZoomEvent(m_MouseDownPosition, false); Event.current.Use(); } else if (IsPanEvent()) { // Pan view Pan(); Event.current.Use(); } break; case EventType.ScrollWheel: if (!area.Contains(Event.current.mousePosition)) { HandleScrolling(area); break; } if (m_IgnoreScrollWheelUntilClicked && GUIUtility.keyboardControl != id) break; // Zoom in around cursor position HandleZoomEvent(mousePositionInDrawing, true); Event.current.Use(); break; } GUILayout.EndArea(); } void HandleScrolling(Rect area) { if (m_MinimalGUI) return; if (m_VSlider && new Rect(area.x + area.width, area.y + GUI.skin.verticalScrollbarUpButton.fixedHeight, vSliderWidth, area.height - (GUI.skin.verticalScrollbarDownButton.fixedHeight + hSliderHeight)).Contains(Event.current.mousePosition)) { SetTransform(new Vector2(m_Translation.x, m_Translation.y - (Event.current.delta.y * k_ScrollStepSize)), m_Scale); Event.current.Use(); return; } if (m_HSlider && new Rect(area.x + GUI.skin.horizontalScrollbarLeftButton.fixedWidth, area.y + area.height, area.width - (GUI.skin.horizontalScrollbarRightButton.fixedWidth + vSliderWidth), hSliderHeight).Contains(Event.current.mousePosition)) { SetTransform(new Vector2(m_Translation.x + (Event.current.delta.y * k_ScrollStepSize), m_Translation.y), m_Scale); Event.current.Use(); } } public void EndViewGUI() { if (m_MinimalGUI && Event.current.type == EventType.Repaint) SliderGUI(); } void SliderGUI() { if (!m_HSlider && !m_VSlider) return; using (new EditorGUI.DisabledScope(!enableMouseInput)) { Bounds editorBounds = drawingBounds; Rect area = shownAreaInsideMargins; float min, max; float inset = styles.sliderWidth - styles.visualSliderWidth; float otherInset = (vSlider && hSlider) ? inset : 0; Vector2 scaleDelta = m_Scale; // Horizontal range slider if (m_HSlider) { Rect hRangeSliderRect = new Rect(drawRect.x + 1, drawRect.yMax - inset, drawRect.width - otherInset, styles.sliderWidth); float shownXRange = area.width; float shownXMin = area.xMin; if (allowSliderZoomHorizontal) { EditorGUIExt.MinMaxScroller(hRangeSliderRect, horizontalScrollbarID, ref shownXMin, ref shownXRange, editorBounds.min.x, editorBounds.max.x, Mathf.NegativeInfinity, Mathf.Infinity, styles.horizontalScrollbar, styles.horizontalMinMaxScrollbarThumb, styles.horizontalScrollbarLeftButton, styles.horizontalScrollbarRightButton, true); } else { shownXMin = GUI.Scroller(hRangeSliderRect, shownXMin, shownXRange, editorBounds.min.x, editorBounds.max.x, styles.horizontalScrollbar, styles.horizontalMinMaxScrollbarThumb, styles.horizontalScrollbarLeftButton, styles.horizontalScrollbarRightButton, true); } min = shownXMin; max = shownXMin + shownXRange; float rectWidthWithinMargins = GetWidthInsideMargins(rect.width, true); if (min > area.xMin) min = Mathf.Min(min, max - rectWidthWithinMargins / m_HScaleMax); if (max < area.xMax) max = Mathf.Max(max, min + rectWidthWithinMargins / m_HScaleMax); SetShownHRangeInsideMargins(min, max); } // Vertical range slider // Reverse y values since y increses upwards for the draw area but downwards for the slider if (m_VSlider) { if (m_UpDirection == YDirection.Positive) { Rect vRangeSliderRect = new Rect(drawRect.xMax - inset, drawRect.y, styles.sliderWidth, drawRect.height - otherInset); float shownYRange = area.height; float shownYMin = -area.yMax; if (allowSliderZoomVertical) { EditorGUIExt.MinMaxScroller(vRangeSliderRect, verticalScrollbarID, ref shownYMin, ref shownYRange, -editorBounds.max.y, -editorBounds.min.y, Mathf.NegativeInfinity, Mathf.Infinity, styles.verticalScrollbar, styles.verticalMinMaxScrollbarThumb, styles.verticalScrollbarUpButton, styles.verticalScrollbarDownButton, false); } else { shownYMin = GUI.Scroller(vRangeSliderRect, shownYMin, shownYRange, -editorBounds.max.y, -editorBounds.min.y, styles.verticalScrollbar, styles.verticalMinMaxScrollbarThumb, styles.verticalScrollbarUpButton, styles.verticalScrollbarDownButton, false); } min = -(shownYMin + shownYRange); max = -shownYMin; float rectHeightWithinMargins = GetHeightInsideMargins(rect.height, true); if (min > area.yMin) min = Mathf.Min(min, max - rectHeightWithinMargins / m_VScaleMax); if (max < area.yMax) max = Mathf.Max(max, min + rectHeightWithinMargins / m_VScaleMax); SetShownVRangeInsideMargins(min, max); } else { Rect vRangeSliderRect = new Rect(drawRect.xMax - inset, drawRect.y, styles.sliderWidth, drawRect.height - otherInset); float shownYRange = area.height; float shownYMin = area.yMin; if (allowSliderZoomVertical) { EditorGUIExt.MinMaxScroller(vRangeSliderRect, verticalScrollbarID, ref shownYMin, ref shownYRange, editorBounds.min.y, editorBounds.max.y, Mathf.NegativeInfinity, Mathf.Infinity, styles.verticalScrollbar, styles.verticalMinMaxScrollbarThumb, styles.verticalScrollbarUpButton, styles.verticalScrollbarDownButton, false); } else { shownYMin = GUI.Scroller(vRangeSliderRect, shownYMin, shownYRange, editorBounds.min.y, editorBounds.max.y, styles.verticalScrollbar, styles.verticalMinMaxScrollbarThumb, styles.verticalScrollbarUpButton, styles.verticalScrollbarDownButton, false); } min = shownYMin; max = shownYMin + shownYRange; float rectHeightWithinMargins = GetHeightInsideMargins(rect.height, true); if (min > area.yMin) min = Mathf.Min(min, max - rectHeightWithinMargins / m_VScaleMax); if (max < area.yMax) max = Mathf.Max(max, min + rectHeightWithinMargins / m_VScaleMax); SetShownVRangeInsideMargins(min, max); } } if (uniformScale) { float aspect = drawRect.width / drawRect.height; scaleDelta -= m_Scale; var delta = new Vector2(-scaleDelta.y * aspect, -scaleDelta.x / aspect); m_Scale -= delta; m_Translation.x -= scaleDelta.y / 2; m_Translation.y -= scaleDelta.x / 2; EnforceScaleAndRange(); } } } private void Pan() { if (!m_HRangeLocked) m_Translation.x += Event.current.delta.x; if (!m_VRangeLocked) m_Translation.y += Event.current.delta.y; EnforceScaleAndRange(); } private void HandleZoomEvent(Vector2 zoomAround, bool scrollwhell) { // Get delta (from scroll wheel or mouse pad) // Add x and y delta to cover all cases // (scrool view has only y or only x when shift is pressed, // while mouse pad has both x and y at all times) float delta = Event.current.delta.x + Event.current.delta.y; if (scrollwhell) delta = -delta; // Scale multiplier. Don't allow scale of zero or below! float scale = Mathf.Max(0.01F, 1 + delta * 0.01F); // Cap scale when at min width to not "glide" away when zooming closer float width = shownAreaInsideMargins.width; if (width / scale <= m_MinWidth) return; SetScaleFocused(zoomAround, scale * m_Scale, Event.current.shift, EditorGUI.actionKey); } // Sets a new scale, keeping focalPoint in the same relative position public void SetScaleFocused(Vector2 focalPoint, Vector2 newScale) { SetScaleFocused(focalPoint, newScale, false, false); } public void SetScaleFocused(Vector2 focalPoint, Vector2 newScale, bool lockHorizontal, bool lockVertical) { if (uniformScale) lockHorizontal = lockVertical = false; else { // if an axis is locked by default, it is as if that modifier key is permanently held down // actually pressing the key then lifts the lock. In other words, LockedByDefault acts like an inversion. if (hZoomLockedByDefault) lockHorizontal = !lockHorizontal; if (hZoomLockedByDefault) lockVertical = !lockVertical; } if (!m_HRangeLocked && !lockHorizontal) { // Offset to make zoom centered around cursor position m_Translation.x -= focalPoint.x * (newScale.x - m_Scale.x); // Apply zooming m_Scale.x = newScale.x; } if (!m_VRangeLocked && !lockVertical) { // Offset to make zoom centered around cursor position m_Translation.y -= focalPoint.y * (newScale.y - m_Scale.y); // Apply zooming m_Scale.y = newScale.y; } EnforceScaleAndRange(); } public void SetTransform(Vector2 newTranslation, Vector2 newScale) { m_Scale = newScale; m_Translation = newTranslation; EnforceScaleAndRange(); } public void EnforceScaleAndRange() { Rect oldArea = m_LastShownAreaInsideMargins; Rect newArea = shownAreaInsideMargins; if (newArea == oldArea) return; float minChange = 0.01f; if (!Mathf.Approximately(newArea.width, oldArea.width)) { float constrainedWidth = newArea.width; if (newArea.width < oldArea.width) { // The shown area decreasing in size means the scale is increasing. This happens e.g. while zooming in. // Only the max scale restricts the shown area size here, range has no influence. constrainedWidth = GetWidthInsideMargins(drawRect.width / m_HScaleMax, false); } else { constrainedWidth = GetWidthInsideMargins(drawRect.width / m_HScaleMin, false); if (hRangeMax != Mathf.Infinity && hRangeMin != Mathf.NegativeInfinity) { // range only has an influence if it is enforced, i.e. not infinity float denum = hRangeMax - hRangeMin; if (denum < m_MinWidth) denum = m_MinWidth; constrainedWidth = Mathf.Min(constrainedWidth, denum); } } float xLerp = Mathf.InverseLerp(oldArea.width, newArea.width, constrainedWidth); float newWidth = Mathf.Lerp(oldArea.width, newArea.width, xLerp); float widthChange = Mathf.Abs(newWidth - newArea.width); newArea = new Rect( // only affect the position if there was any significant change in width // this fixes an issue where if width was only different due to rounding issues, position changes are ignored as xLerp comes back 0 (or very nearly 0) widthChange > minChange ? Mathf.Lerp(oldArea.x, newArea.x, xLerp) : newArea.x, newArea.y, newWidth, newArea.height ); } if (!Mathf.Approximately(newArea.height, oldArea.height)) { float constrainedHeight = newArea.height; if (newArea.height < oldArea.height) { // The shown area decreasing in size means the scale is increasing. This happens e.g. while zooming in. // Only the max scale restricts the shown area size here, range has no influence. constrainedHeight = GetHeightInsideMargins(drawRect.height / m_VScaleMax, false); } else { constrainedHeight = GetHeightInsideMargins(drawRect.height / m_VScaleMin, false); if (vRangeMax != Mathf.Infinity && vRangeMin != Mathf.NegativeInfinity) { // range only has an influence if it is enforced, i.e. not infinity float denum = vRangeMax - vRangeMin; if (denum < kMinHeight) denum = kMinHeight; constrainedHeight = Mathf.Min(constrainedHeight, denum); } } float yLerp = Mathf.InverseLerp(oldArea.height, newArea.height, constrainedHeight); float newHeight = Mathf.Lerp(oldArea.height, newArea.height, yLerp); float heightChange = Mathf.Abs(newHeight - newArea.height); newArea = new Rect( newArea.x, // only affect the position if there was any significant change in height // this fixes an issue where if height was only different due to rounding issues, position changes are ignored as yLerp comes back 0 (or very nearly 0) heightChange > minChange ? Mathf.Lerp(oldArea.y, newArea.y, yLerp) : newArea.y, newArea.width, newHeight ); } // Enforce ranges if (newArea.xMin < hRangeMin) newArea.x = hRangeMin; if (newArea.xMax > hRangeMax) newArea.x = hRangeMax - newArea.width; if (newArea.yMin < vRangeMin) newArea.y = vRangeMin; if (newArea.yMax > vRangeMax) newArea.y = vRangeMax - newArea.height; shownAreaInsideMarginsInternal = newArea; m_LastShownAreaInsideMargins = shownAreaInsideMargins; } public float PixelToTime(float pixelX, Rect rect) { Rect area = shownArea; return ((pixelX - rect.x) * area.width / rect.width + area.x); } public float TimeToPixel(float time, Rect rect) { Rect area = shownArea; return (time - area.x) / area.width * rect.width + rect.x; } public float PixelDeltaToTime(Rect rect) { return shownArea.width / rect.width; } public void UpdateZoomScale(float fMaxScaleValue, float fMinScaleValue) { // Update/reset the values of the scale to new zoom range, if the current values do not fall in the range of the new resolution if (m_Scale.y > fMaxScaleValue || m_Scale.y < fMinScaleValue) { m_Scale.y = m_Scale.y > fMaxScaleValue ? fMaxScaleValue : fMinScaleValue; } if (m_Scale.x > fMaxScaleValue || m_Scale.x < fMinScaleValue) { m_Scale.x = m_Scale.x > fMaxScaleValue ? fMaxScaleValue : fMinScaleValue; } } } } // namespace
UnityCsReference/Editor/Mono/Animation/ZoomableArea.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/ZoomableArea.cs", "repo_id": "UnityCsReference", "token_count": 24092 }
278
// 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.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Mono.Cecil; using Unity.IO.LowLevel.Unsafe; using UnityEditor.Scripting.ScriptCompilation; using UnityEngine.Scripting; namespace UnityEditor { static class AssemblyValidation { // Keep in sync with AssemblyValidationFlags in MonoManager.cpp [Flags] public enum ErrorFlags { None = 0, ReferenceHasErrors = (1 << 0), UnresolvableReference = (1 << 1), IncompatibleWithEditor = (1 << 2), AsmdefPluginConflict = (1 << 3) } [StructLayout(LayoutKind.Sequential)] public struct Error { public ErrorFlags flags; public string message; public string assemblyPath; public void Add(ErrorFlags newFlags, string newMessage) { flags |= newFlags; if (message == null) { message = newMessage; } else { message += string.Format("\n{0}", newMessage); } } public bool HasFlag(ErrorFlags testFlags) { return (flags & testFlags) == testFlags; } public void ClearFlags(ErrorFlags clearFlags) { flags &= ~clearFlags; } } public struct AssemblyAndReferences { public int assemblyIndex; public int[] referenceIndicies; } class AssemblyResolver : BaseAssemblyResolver { readonly IDictionary<string, AssemblyDefinition> cache; public AssemblyResolver() { cache = new Dictionary<string, AssemblyDefinition>(StringComparer.Ordinal); } public override AssemblyDefinition Resolve(AssemblyNameReference name) { if (name == null) throw new ArgumentNullException("name"); AssemblyDefinition assembly; if (cache.TryGetValue(name.Name, out assembly)) return assembly; assembly = base.Resolve(name); cache[name.Name] = assembly; return assembly; } public void RegisterAssembly(AssemblyDefinition assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); var name = assembly.Name.Name; if (cache.ContainsKey(name)) return; cache[name] = assembly; } protected override void Dispose(bool disposing) { foreach (var assembly in cache.Values) assembly.Dispose(); cache.Clear(); base.Dispose(disposing); } } [RequiredByNativeCode] public static Error[] ValidateAssemblies(string[] assemblyPaths, bool enableLogging) { var searchPaths = AssemblyHelper.GetDefaultAssemblySearchPaths(); var assemblyDefinitions = LoadAssemblyDefinitions(assemblyPaths, searchPaths); if (enableLogging) { // Prints assemblies and their references to the Editor.log PrintAssemblyDefinitions(assemblyDefinitions); foreach (var searchPath in searchPaths) { Console.WriteLine("[AssemblyValidation] Search Path: '" + searchPath + "'"); } } var errors = ValidateAssemblyDefinitions(assemblyPaths, assemblyDefinitions); return errors; } [RequiredByNativeCode] internal static Error[] ValidateRoslynAnalyzers(string[] analyzerPaths) { var readerParameters = new ReaderParameters { ReadingMode = ReadingMode.Deferred }; List<Error> errors = new List<Error>(); foreach(var analyzer in analyzerPaths) { using (var analyzerDefinition = AssemblyDefinition.ReadAssembly(analyzer, readerParameters)) { var netstandardVersion = analyzerDefinition.MainModule.AssemblyReferences.Where(r => r.Name == "netstandard").FirstOrDefault(); if (netstandardVersion != null && netstandardVersion.Version >= new Version(2, 1)) { errors.Add(new Error { assemblyPath = analyzer, flags = ErrorFlags.ReferenceHasErrors, message = $"{analyzerDefinition.Name.Name} references {netstandardVersion}. A roslyn analyzer should reference netstandard version 2.0" }); } } } return errors.ToArray(); } [RequiredByNativeCode] public static Error[] ValidateAssemblyDefinitionFiles() { var customScriptAssemblies = EditorCompilationInterface.Instance.GetCustomScriptAssemblies(); if (customScriptAssemblies.Length == 0) return null; var pluginImporters = PluginImporter.GetAllImporters(); if (pluginImporters == null || pluginImporters.Length == 0) return null; var pluginFilenameToAssetPath = new Dictionary<string, string>(); foreach (var pluginImporter in pluginImporters) { var pluginAssetPath = pluginImporter.assetPath; var lowerPluginFilename = AssetPath.GetFileName(pluginAssetPath).ToLower(CultureInfo.InvariantCulture); pluginFilenameToAssetPath[lowerPluginFilename] = pluginAssetPath; } var errors = new List<Error>(); foreach (var customScriptAssembly in customScriptAssemblies) { var lowerAsmdefFilename = $"{customScriptAssembly.Name.ToLower(CultureInfo.InvariantCulture)}.dll"; string pluginPath; if (pluginFilenameToAssetPath.TryGetValue(lowerAsmdefFilename, out pluginPath)) { var error = new Error() { message = $"Plugin '{pluginPath}' has the same filename as Assembly Definition File '{customScriptAssembly.FilePath}'. Rename the assemblies to avoid hard to diagnose issues and crashes.", flags = ErrorFlags.AsmdefPluginConflict, assemblyPath = pluginPath }; errors.Add(error); } } return errors.ToArray(); } public static bool ShouldValidateReferences(string path, Dictionary<string, PrecompiledAssembly> allPrecompiledAssemblies) { if (!allPrecompiledAssemblies.TryGetValue(path, out var precompiledAssembly)) return true; return precompiledAssembly.Flags.HasFlag(AssemblyFlags.ValidateAssembly); } public static void PrintAssemblyDefinitions(AssemblyDefinition[] assemblyDefinitions) { foreach (var assemblyDefinition in assemblyDefinitions) { Console.WriteLine("[AssemblyValidation] Assembly: " + assemblyDefinition.Name); var assemblyReferences = GetAssemblyNameReferences(assemblyDefinition); foreach (var reference in assemblyReferences) { Console.WriteLine("[AssemblyValidation] Reference: " + reference); } } } public static Error[] ValidateAssembliesInternal(string[] assemblyPaths, string[] searchPaths) { var assemblyDefinitions = LoadAssemblyDefinitions(assemblyPaths, searchPaths); return ValidateAssemblyDefinitions(assemblyPaths, assemblyDefinitions); } public static Error[] ValidateAssemblyDefinitions(string[] assemblyPaths, AssemblyDefinition[] assemblyDefinitions) { var errors = new Error[assemblyPaths.Length]; CheckAssemblyReferences(assemblyPaths, errors, assemblyDefinitions); return errors; } public static AssemblyDefinition[] LoadAssemblyDefinitions(string[] assemblyPaths, string[] searchPaths) { var assemblyResolver = new AssemblyResolver(); foreach (var asmpath in searchPaths) assemblyResolver.AddSearchDirectory(asmpath); var readerParameters = new ReaderParameters { AssemblyResolver = assemblyResolver }; var assemblyDefinitions = new AssemblyDefinition[assemblyPaths.Length]; for (int i = 0; i < assemblyPaths.Length; ++i) { assemblyDefinitions[i] = AssemblyDefinition.ReadAssembly(assemblyPaths[i], readerParameters); // Cecil tries to resolve references by filename, since Unity force loads // assemblies, then assembly reference will resolve even if the assembly name // does not match the assembly filename. So we register all assemblies in // in the resolver. assemblyResolver.RegisterAssembly(assemblyDefinitions[i]); } return assemblyDefinitions; } public static void CheckAssemblyReferences(string[] assemblyPaths, Error[] errors, AssemblyDefinition[] assemblyDefinitions) { var assemblyDefinitionNameToIndex = new Dictionary<string, int>(); var assembliesAndReferencesArray = new AssemblyAndReferences[assemblyPaths.Length]; for (int i = 0; i < assemblyDefinitions.Length; ++i) { assemblyDefinitionNameToIndex[assemblyDefinitions[i].Name.Name] = i; assembliesAndReferencesArray[i] = new AssemblyAndReferences { assemblyIndex = i, referenceIndicies = new int[0] }; } var precompiledAssemblies = EditorCompilationInterface.Instance .PrecompiledAssemblyProvider.GetAllPrecompiledAssemblies() .Where(x => x.Flags.HasFlag(AssemblyFlags.UserAssembly)); var allPrecompiledAssemblies = precompiledAssemblies.ToDictionary(x => AssetPath.ReplaceSeparators(VirtualFileSystem.ToLogicalPath(x.Path))); for (int i = 0; i < assemblyPaths.Length; ++i) { if (errors[i].HasFlag(ErrorFlags.IncompatibleWithEditor)) continue; var assemblyPath = assemblyPaths[i]; // Check if "Validate References" option is enabled // in the PluginImporter if (!ShouldValidateReferences(AssetPath.ReplaceSeparators(assemblyPath), allPrecompiledAssemblies)) continue; ResolveAndSetupReferences(i, errors, assemblyDefinitions, assemblyDefinitionNameToIndex, assembliesAndReferencesArray, assemblyPath); } // Check assemblies for references to assemblies with errors int referenceErrorCount; do { referenceErrorCount = 0; foreach (var assemblyAndReferences in assembliesAndReferencesArray) { var assemblyIndex = assemblyAndReferences.assemblyIndex; foreach (var referenceIndex in assemblyAndReferences.referenceIndicies) { var referenceError = errors[referenceIndex]; if (errors[assemblyIndex].flags == ErrorFlags.None && referenceError.flags != ErrorFlags.None) { if (referenceError.HasFlag(ErrorFlags.IncompatibleWithEditor)) { errors[assemblyIndex].Add(ErrorFlags.ReferenceHasErrors | ErrorFlags.IncompatibleWithEditor, string.Format("Reference '{0}' is incompatible with the editor.", assemblyDefinitions[referenceIndex].Name.Name)); } else { errors[assemblyIndex].Add(ErrorFlags.ReferenceHasErrors | referenceError.flags, string.Format("Reference has errors '{0}'.", assemblyDefinitions[referenceIndex].Name.Name)); } referenceErrorCount++; } } } } while (referenceErrorCount > 0); } public static void ResolveAndSetupReferences(int index, Error[] errors, AssemblyDefinition[] assemblyDefinitions, Dictionary<string, int> assemblyDefinitionNameToIndex, AssemblyAndReferences[] assemblyAndReferences, string assemblyPath) { var assemblyDefinition = assemblyDefinitions[index]; var assemblyResolver = assemblyDefinition.MainModule.AssemblyResolver; var assemblyReferences = GetAssemblyNameReferences(assemblyDefinition); var referenceIndieces = new List<int> { Capacity = assemblyReferences.Length }; bool isReferencingUnityAssemblies = false; foreach (var reference in assemblyReferences) { if (!isReferencingUnityAssemblies && (Utility.FastStartsWith(reference.Name, "UnityEngine", "unityengine") || Utility.FastStartsWith(reference.Name, "UnityEditor", "unityeditor"))) { isReferencingUnityAssemblies = true; } try { var referenceAssemblyDefinition = assemblyResolver.Resolve(reference); if (reference.Name == assemblyDefinition.Name.Name) { errors[index].Add(ErrorFlags.ReferenceHasErrors, $"{reference.Name} references itself."); } if (assemblyDefinitionNameToIndex.TryGetValue(referenceAssemblyDefinition.Name.Name, out int referenceAssemblyDefinitionIndex)) { referenceIndieces.Add(referenceAssemblyDefinitionIndex); } } catch (AssemblyResolutionException) { errors[index].Add(ErrorFlags.UnresolvableReference, string.Format("Unable to resolve reference '{0}'. Is the assembly missing or incompatible with the current platform?\nReference validation can be disabled in the Plugin Inspector.", reference.Name)); } } if (isReferencingUnityAssemblies) { var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assemblyPath); if (assemblyDefinitions[index].Name.Name != fileNameWithoutExtension) { errors[index].Add(ErrorFlags.ReferenceHasErrors, $"Assembly name '{assemblyDefinitions[index].Name.Name}' does not match file name '{fileNameWithoutExtension}'"); } } assemblyAndReferences[index].referenceIndicies = referenceIndieces.ToArray(); } private static bool IsInSameFolder(AssemblyDefinition first, AssemblyDefinition second) { var firstAssemblyPath = Path.GetDirectoryName(first.MainModule.FileName); var secondAssemblyPath = Path.GetDirectoryName(second.MainModule.FileName); return firstAssemblyPath.Equals(secondAssemblyPath, StringComparison.Ordinal); } private static bool IsSigned(AssemblyNameReference reference) { //Bug in Cecil where HasPublicKey is always false foreach (var publicTokenByte in reference.PublicKeyToken) { if (publicTokenByte != 0) { return true; } } return false; } public static AssemblyNameReference[] GetAssemblyNameReferences(AssemblyDefinition assemblyDefinition) { List<AssemblyNameReference> result = new List<AssemblyNameReference> { Capacity = 16 }; foreach (ModuleDefinition module in assemblyDefinition.Modules) { var references = module.AssemblyReferences; foreach (var reference in references) { result.Add(reference); } } return result.ToArray(); } } }
UnityCsReference/Editor/Mono/AssemblyValidation.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssemblyValidation.cs", "repo_id": "UnityCsReference", "token_count": 8338 }
279
// 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.Runtime.InteropServices; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEditor.AssetImporters { [RequiredByNativeCode] [NativeHeader("Editor/Src/AssetPipeline/ModelImporting/CameraDescription.h")] public class CameraDescription : IDisposable { internal IntPtr m_Ptr; public CameraDescription() { m_Ptr = Internal_Create(); } ~CameraDescription() { Destroy(); } public void Dispose() { Destroy(); GC.SuppressFinalize(this); } void Destroy() { if (m_Ptr != IntPtr.Zero) { Internal_Destroy(m_Ptr); m_Ptr = IntPtr.Zero; } } public bool TryGetProperty(string propertyName, out float value) => TryGetFloatProperty(propertyName, out value); public bool TryGetProperty(string propertyName, out Vector4 value) => TryGetVector4Property(propertyName, out value); public bool TryGetProperty(string propertyName, out string value) => TryGetStringProperty(propertyName, out value); public bool TryGetProperty(string propertyName, out int value) => TryGetIntProperty(propertyName, out value); public extern void GetVector4PropertyNames(List<string> names); public extern void GetFloatPropertyNames(List<string> names); public extern void GetStringPropertyNames(List<string> names); public extern void GetIntPropertyNames(List<string> names); extern bool TryGetVector4Property(string propertyName, out Vector4 value); extern bool TryGetFloatProperty(string propertyName, out float value); extern bool TryGetStringProperty(string propertyName, out string value); extern bool TryGetIntProperty(string propertyName, out int value); public bool TryGetAnimationCurve(string clipName, string propertyName, out AnimationCurve value) { value = TryGetAnimationCurve(clipName, propertyName); return value != null; } public extern bool HasAnimationCurveInClip(string clipName, string propertyName); public extern bool HasAnimationCurve(string propertyName); extern AnimationCurve TryGetAnimationCurve(string clipName, string propertyName); static extern IntPtr Internal_Create(); static extern void Internal_Destroy(IntPtr ptr); internal static class BindingsMarshaller { public static IntPtr ConvertToNative(CameraDescription desc) => desc.m_Ptr; } } }
UnityCsReference/Editor/Mono/AssetPipeline/CameraDescription.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetPipeline/CameraDescription.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1065 }
280
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System.Collections.Generic; namespace UnityEditor.SpeedTree.Importer { internal class SpeedTreeImporterOutputData : ScriptableObject { /// <summary> /// The main object of the asset. /// </summary> public GameObject mainObject; /// <summary> /// Contains the materials data and materials are assigned per LOD with an index. /// </summary> public LODMaterials lodMaterials = new LODMaterials(); /// <summary> /// The materials metadata used for the materials extraction code. /// </summary> public List<AssetIdentifier> materialsIdentifiers = new List<AssetIdentifier>(); /// <summary> /// Represents the wind configuration parameters. /// </summary> public SpeedTreeWindConfig9 m_WindConfig = new SpeedTreeWindConfig9(); /// <summary> /// Determines if the current asset has embedded materials or not. /// </summary> public bool hasEmbeddedMaterials = false; /// <summary> /// Determines if the current Shader supports alpha clip threshold. /// </summary> public bool hasAlphaClipThreshold = false; /// <summary> /// Determines if the current Shader supports transmision scale. /// </summary> public bool hasTransmissionScale = false; /// <summary> /// Determines if the current asset has a biilboard or not. /// </summary> public bool hasBillboard = false; /// <summary> /// Create an instance of SpeedTreeImporterOutputData with default settings. /// </summary> /// <returns>The newly created SpeedTreeImporterOutputData instance.</returns> static public SpeedTreeImporterOutputData Create() { SpeedTreeImporterOutputData outputImporterData = CreateInstance<SpeedTreeImporterOutputData>(); outputImporterData.name = "ImporterOutputData"; // Ideally, we should use this flag so the file is not visible in the asset prefab. // Though, it breaks the 'AssetDatabase.LoadAssetAtPath' function (the file is not loaded anymore). // outputImporterData.hideFlags = HideFlags.HideInHierarchy; return outputImporterData; } } }
UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTreeImporterOutputData.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTreeImporterOutputData.cs", "repo_id": "UnityCsReference", "token_count": 899 }
281
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License /* * Simple recursive descending JSON parser and * JSON string builder. * * Jonas Drewsen - (C) Unity3d.com - 2010 * * JSONParser parser = new JSONParser(" { \"hello\" : 42.3 } "); * JSONValue value = parser.Parse(); * * bool is_it_float = value.isFloat(); * float the_float = value.asFloat(); * */ using System.Collections.Generic; using System; using System.Globalization; using UnityEngine; namespace UnityEditorInternal { /* * JSON value structure * * Example: * JSONValue v = JSONValue.NewDict(); * v["hello"] = JSONValue.NewString("world"); * asset(v["hello"].AsString() == "world"); * */ internal struct JSONValue { public JSONValue(object o) { data = o; } public bool IsString() { return data is string; } public bool IsFloat() { return data is float; } public bool IsList() { return data is List<JSONValue>; } public bool IsDict() { return data is Dictionary<string, JSONValue>; } public bool IsBool() { return data is bool; } public bool IsNull() { return data == null; } public static implicit operator JSONValue(string s) { return new JSONValue(s); } public static implicit operator JSONValue(float s) { return new JSONValue(s); } public static implicit operator JSONValue(bool s) { return new JSONValue(s); } public static implicit operator JSONValue(int s) { return new JSONValue((float)s); } public object AsObject() { return data; } public string AsString(bool nothrow) { if (data is string) return (string)data; if (!nothrow) throw new JSONTypeException("Tried to read non-string json value as string"); return ""; } public string AsString() { return AsString(false); } public float AsFloat(bool nothrow) { if (data is float) return (float)data; if (!nothrow) throw new JSONTypeException("Tried to read non-float json value as float"); return 0.0f; } public float AsFloat() { return AsFloat(false); } public bool AsBool(bool nothrow) { if (data is bool) return (bool)data; if (!nothrow) throw new JSONTypeException("Tried to read non-bool json value as bool"); return false; } public bool AsBool() { return AsBool(false); } public List<JSONValue> AsList(bool nothrow) { if (data is List<JSONValue>) return (List<JSONValue>)data; if (!nothrow) throw new JSONTypeException("Tried to read " + data.GetType().Name + " json value as list"); return null; } public List<JSONValue> AsList() { return AsList(false); } public Dictionary<string, JSONValue> AsDict(bool nothrow) { if (data is Dictionary<string, JSONValue>) return (Dictionary<string, JSONValue>)data; if (!nothrow) throw new JSONTypeException("Tried to read non-dictionary json value as dictionary"); return null; } public Dictionary<string, JSONValue> AsDict() { return AsDict(false); } public static JSONValue NewString(string val) { return new JSONValue(val); } public static JSONValue NewFloat(float val) { return new JSONValue(val); } public static JSONValue NewDict() { return new JSONValue(new Dictionary<string, JSONValue>()); } public static JSONValue NewList() { return new JSONValue(new List<JSONValue>()); } public static JSONValue NewBool(bool val) { return new JSONValue(val); } public static JSONValue NewNull() { return new JSONValue(null); } public JSONValue this[string index] { get { Dictionary<string, JSONValue> dict = AsDict(); return dict[index]; } set { if (data == null) data = new Dictionary<string, JSONValue>(); Dictionary<string, JSONValue> dict = AsDict(); dict[index] = value; } } public bool ContainsKey(string index) { if (!IsDict()) return false; return AsDict().ContainsKey(index); } // Get the specified field in a dict or null json value if // no such field exists. The key can point to a nested structure // e.g. key1.key2 in { key1 : { key2 : 32 } } public JSONValue Get(string key) { if (!IsDict()) return new JSONValue(null); JSONValue value = this; foreach (string part in key.Split('.')) { if (!value.ContainsKey(part)) return new JSONValue(null); value = value[part]; } return value; } // Convenience dict value setting public void Set(string key, string value) { if (value == null) { this[key] = NewNull(); return; } this[key] = NewString(value); } // Convenience dict value setting public void Set(string key, float value) { this[key] = NewFloat(value); } // Convenience dict value setting public void Set(string key, bool value) { this[key] = NewBool(value); } // Convenience list value add public void Add(string value) { List<JSONValue> list = AsList(); if (value == null) { list.Add(NewNull()); return; } list.Add(NewString(value)); } // Convenience list value add public void Add(float value) { List<JSONValue> list = AsList(); list.Add(NewFloat(value)); } // Convenience list value add public void Add(bool value) { List<JSONValue> list = AsList(); list.Add(NewBool(value)); } /* * Serialize a JSON value to string. * This will recurse down through dicts and list type JSONValues. */ public override string ToString() { if (IsString()) { return "\"" + EncodeString(AsString()) + "\""; } else if (IsFloat()) { return AsFloat().ToString(); } else if (IsList()) { string res = "["; string delim = ""; foreach (JSONValue i in AsList()) { res += delim + i; delim = ", "; } return res + "]"; } else if (IsDict()) { string res = "{"; string delim = ""; foreach (KeyValuePair<string, JSONValue> kv in AsDict()) { res += delim + '"' + EncodeString(kv.Key) + "\" : " + kv.Value; delim = ", "; } return res + "}"; } else if (IsBool()) { return AsBool() ? "true" : "false"; } else if (IsNull()) { return "null"; } else { throw new JSONTypeException("Cannot serialize json value of unknown type"); } } // Encode a string into a json string private static string EncodeString(string str) { str = str.Replace("\"", "\\\""); str = str.Replace("\\", "\\\\"); str = str.Replace("\b", "\\b"); str = str.Replace("\f", "\\f"); str = str.Replace("\n", "\\n"); str = str.Replace("\r", "\\r"); str = str.Replace("\t", "\\t"); // We do not use \uXXXX specifier but direct unicode in the string. return str; } object data; } class JSONParseException : Exception { public JSONParseException(string msg) : base(msg) { } } class JSONTypeException : Exception { public JSONTypeException(string msg) : base(msg) { } } /* * Top down recursive JSON parser * * Example: * string json = "{ \"hello\" : \"world\", \"age\" : 100000, "sister" : null }"; * JSONValue val = JSONParser.SimpleParse(json); * asset( val["hello"].AsString() == "world" ); * */ class JSONParser { private string json; private int line; private int linechar; private int len; private int idx; private int pctParsed; private char cur; public static JSONValue SimpleParse(string jsondata) { var parser = new JSONParser(jsondata); try { return parser.Parse(); } catch (JSONParseException ex) { Debug.LogError(ex.Message); } return new JSONValue(null); } /* * Setup a parse to be ready for parsing the given string */ public JSONParser(string jsondata) { // TODO: fix that parser needs trailing spaces; json = jsondata + " "; line = 1; linechar = 1; len = json.Length; idx = 0; pctParsed = 0; } /* * Parse the entire json data string into a JSONValue structure hierarchy */ public JSONValue Parse() { cur = json[idx]; return ParseValue(); } private char Next() { if (cur == '\n') { line++; linechar = 0; } idx++; if (idx >= len) throw new JSONParseException("End of json while parsing at " + PosMsg()); linechar++; int newPct = (int)((float)idx * 100f / (float)len); if (newPct != pctParsed) { pctParsed = newPct; } cur = json[idx]; return cur; } private void SkipWs() { string ws = " \n\t\r"; while (ws.IndexOf(cur) != -1) Next(); } private string PosMsg() { return "line " + line + ", column " + linechar; } private JSONValue ParseValue() { // Skip spaces SkipWs(); switch (cur) { case '[': return ParseArray(); case '{': return ParseDict(); case '"': return ParseString(); case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return ParseNumber(); case 't': case 'f': case 'n': return ParseConstant(); default: throw new JSONParseException("Cannot parse json value starting with '" + json.Substring(idx, 5) + "' at " + PosMsg()); } } private JSONValue ParseArray() { Next(); SkipWs(); List<JSONValue> arr = new List<JSONValue>(); while (cur != ']') { arr.Add(ParseValue()); SkipWs(); if (cur == ',') { Next(); SkipWs(); } } Next(); return new JSONValue(arr); } private JSONValue ParseDict() { Next(); SkipWs(); Dictionary<string, JSONValue> dict = new Dictionary<string, JSONValue>(); while (cur != '}') { JSONValue key = ParseValue(); if (!key.IsString()) throw new JSONParseException("Key not string type at " + PosMsg()); SkipWs(); if (cur != ':') throw new JSONParseException("Missing dict entry delimiter ':' at " + PosMsg()); Next(); dict.Add(key.AsString(), ParseValue()); SkipWs(); if (cur == ',') { Next(); SkipWs(); } } Next(); return new JSONValue(dict); } static char[] endcodes = new char[] { '\\', '"' }; private JSONValue ParseString() { string res = ""; Next(); while (idx < len) { int endidx = json.IndexOfAny(endcodes, idx); if (endidx < 0) throw new JSONParseException("missing '\"' to end string at " + PosMsg()); res += json.Substring(idx, endidx - idx); if (json[endidx] == '"') { cur = json[endidx]; idx = endidx; break; } endidx++; // get escape code if (endidx >= len) throw new JSONParseException("End of json while parsing while parsing string at " + PosMsg()); // char at endidx is \ char ncur = json[endidx]; switch (ncur) { case '"': goto case '/'; case '\\': goto case '/'; case '/': res += ncur; break; case 'b': res += '\b'; break; case 'f': res += '\f'; break; case 'n': res += '\n'; break; case 'r': res += '\r'; break; case 't': res += '\t'; break; case 'u': // Unicode char specified by 4 hex digits string digit = ""; if (endidx + 4 >= len) throw new JSONParseException("End of json while parsing while parsing unicode char near " + PosMsg()); digit += json[endidx + 1]; digit += json[endidx + 2]; digit += json[endidx + 3]; digit += json[endidx + 4]; try { int d = System.Int32.Parse(digit, System.Globalization.NumberStyles.AllowHexSpecifier); res += (char)d; } catch (FormatException) { throw new JSONParseException("Invalid unicode escape char near " + PosMsg()); } endidx += 4; break; default: throw new JSONParseException("Invalid escape char '" + ncur + "' near " + PosMsg()); } idx = endidx + 1; } if (idx >= len) throw new JSONParseException("End of json while parsing while parsing string near " + PosMsg()); cur = json[idx]; Next(); return new JSONValue(res); } private JSONValue ParseNumber() { string resstr = ""; if (cur == '-') { resstr = "-"; Next(); } while (cur >= '0' && cur <= '9') { resstr += cur; Next(); } if (cur == '.') { Next(); resstr += '.'; while (cur >= '0' && cur <= '9') { resstr += cur; Next(); } } if (cur == 'e' || cur == 'E') { resstr += "e"; Next(); if (cur != '-' && cur != '+') { // throw new JSONParseException("Missing - or + in 'e' potent specifier at " + PosMsg()); resstr += cur; Next(); } while (cur >= '0' && cur <= '9') { resstr += cur; Next(); } } try { float f = System.Convert.ToSingle(resstr, CultureInfo.InvariantCulture); return new JSONValue(f); } catch (Exception) { throw new JSONParseException("Cannot convert string to float : '" + resstr + "' at " + PosMsg()); } } private JSONValue ParseConstant() { string c = ""; c = "" + cur + Next() + Next() + Next(); Next(); if (c == "true") { return new JSONValue(true); } else if (c == "fals") { if (cur == 'e') { Next(); return new JSONValue(false); } } else if (c == "null") { return new JSONValue(null); } throw new JSONParseException("Invalid token at " + PosMsg()); } } }
UnityCsReference/Editor/Mono/AssetStore/Json.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetStore/Json.cs", "repo_id": "UnityCsReference", "token_count": 10847 }
282
// 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; namespace UnityEditor { [NativeHeader("Editor/Mono/Audio/Bindings/AudioUtil.bindings.h")] [StaticAccessor("AudioUtilScriptBindings", StaticAccessorType.DoubleColon)] internal class AudioUtil { [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static bool resetAllAudioClipPlayCountsOnPlay { get; set; } [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static void PlayPreviewClip([NotNull] AudioClip clip, int startSample = 0, bool loop = false); [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static void PausePreviewClip(); [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static void ResumePreviewClip(); [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static void LoopPreviewClip(bool on); [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static bool IsPreviewClipPlaying(); [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static void StopAllPreviewClips(); [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static float GetPreviewClipPosition(); [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static int GetPreviewClipSamplePosition(); [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] extern public static void SetPreviewClipSamplePosition([NotNull] AudioClip clip, int iSamplePosition); extern public static int GetSampleCount(AudioClip clip); extern public static int GetChannelCount(AudioClip clip); extern public static int GetBitRate(AudioClip clip); extern public static int GetBitsPerSample(AudioClip clip); extern public static int GetFrequency(AudioClip clip); extern public static int GetSoundSize(AudioClip clip); extern public static AudioCompressionFormat GetSoundCompressionFormat(AudioClip clip); extern public static AudioCompressionFormat GetTargetPlatformSoundCompressionFormat(AudioClip clip); extern public static bool canUseSpatializerEffect { [FreeFunction(Name = "GetAudioManager().CanUseSpatializerEffect")] get; } extern public static string[] GetAmbisonicDecoderPluginNames(); extern public static bool HasPreview(AudioClip clip); extern public static AudioImporter GetImporterFromClip(AudioClip clip); extern public static float[] GetMinMaxData(AudioImporter importer); extern public static double GetDuration(AudioClip clip); [FreeFunction(Name = "GetAudioManager().GetMemoryAllocated")] extern public static int GetFMODMemoryAllocated(); [FreeFunction(Name = "GetAudioManager().GetCPUUsage")] extern public static float GetFMODCPUUsage(); extern public static bool IsTrackerFile(AudioClip clip); extern public static int GetMusicChannelCount(AudioClip clip); extern public static AnimationCurve GetLowpassCurve(AudioLowPassFilter lowPassFilter); extern public static Vector3 GetListenerPos(); extern public static void UpdateAudio(); extern public static void SetListenerTransform(Transform t); extern public static bool HasAudioCallback(MonoBehaviour behaviour); extern public static int GetCustomFilterChannelCount(MonoBehaviour behaviour); extern public static int GetCustomFilterProcessTime(MonoBehaviour behaviour); extern public static float GetCustomFilterMaxIn(MonoBehaviour behaviour, int channel); extern public static float GetCustomFilterMaxOut(MonoBehaviour behaviour, int channel); extern internal static void SetProfilerShowAllGroups(bool value); } }
UnityCsReference/Editor/Mono/Audio/Bindings/AudioUtil.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/Bindings/AudioUtil.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1393 }
283
// 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.IO; using System; using UnityEditorInternal; using UnityEditor.Audio; namespace UnityEditor { class AudioMixerExposedParameterView { private ReorderableListWithRenameAndScrollView m_ReorderableListWithRenameAndScrollView; private AudioMixerController m_Controller; private SerializedObject m_ControllerSerialized; ReorderableListWithRenameAndScrollView.State m_State; private float height { get { return m_ReorderableListWithRenameAndScrollView.list.GetHeight(); } } public AudioMixerExposedParameterView(ReorderableListWithRenameAndScrollView.State state) { m_State = state; } public void OnMixerControllerChanged(AudioMixerController controller) { m_Controller = controller; if (m_Controller) m_Controller.ChangedExposedParameter += new ChangedExposedParameterHandler(RecreateListControl); RecreateListControl(); } public void RecreateListControl() { if (m_Controller != null) { m_ControllerSerialized = new SerializedObject(m_Controller); var exposedParams = m_ControllerSerialized.FindProperty("m_ExposedParameters"); System.Diagnostics.Debug.Assert(exposedParams != null); ReorderableList reorderableList = new ReorderableList(m_ControllerSerialized, exposedParams, false, false, false, false); reorderableList.onReorderCallback = EndDragChild; reorderableList.drawElementCallback += DrawElement; reorderableList.elementHeight = 18; reorderableList.headerHeight = 0; reorderableList.footerHeight = 0; reorderableList.showDefaultBackground = false; m_ReorderableListWithRenameAndScrollView = new ReorderableListWithRenameAndScrollView(reorderableList, m_State); m_ReorderableListWithRenameAndScrollView.onNameChangedAtIndex += NameChanged; m_ReorderableListWithRenameAndScrollView.onDeleteItemAtIndex += Delete; m_ReorderableListWithRenameAndScrollView.onGetNameAtIndex += GetNameOfElement; } } public void OnGUI(Rect rect) { if (m_Controller == null) return; m_ReorderableListWithRenameAndScrollView.OnGUI(rect); } public void OnContextClick(int itemIndex) { GenericMenu pm = new GenericMenu(); pm.AddItem( EditorGUIUtility.TrTextContent("Unexpose"), false, delegate(object data) { Delete((int)data); }, itemIndex); pm.AddItem( EditorGUIUtility.TrTextContent("Rename"), false, delegate(object data) { m_ReorderableListWithRenameAndScrollView.BeginRename((int)data, 0f); }, itemIndex); pm.ShowAsContext(); } void DrawElement(Rect rect, int index, bool isActive, bool isFocused) { Event evt = Event.current; if (evt.type == EventType.ContextClick && rect.Contains(evt.mousePosition)) { OnContextClick(index); evt.Use(); } if (Event.current.type != EventType.Repaint) return; // The left side of the text is drawn by the reorderable list, now draw the additional right aligned text using (new EditorGUI.DisabledScope(true)) { m_ReorderableListWithRenameAndScrollView.elementStyleRightAligned.Draw(rect, GetInfoString(index), false, false, false, false); } } public Vector2 CalcSize() { if (m_ReorderableListWithRenameAndScrollView.list.count != m_Controller.exposedParameters.Length) { RecreateListControl(); } float maxWidth = 0; for (int index = 0; index < m_ReorderableListWithRenameAndScrollView.list.count; index++) { var width = WidthOfRow(index, m_ReorderableListWithRenameAndScrollView.elementStyle, m_ReorderableListWithRenameAndScrollView.elementStyleRightAligned); if (width > maxWidth) maxWidth = width; } return new Vector2(maxWidth, height); } string GetInfoString(int index) { ExposedAudioParameter exposedParam = m_Controller.exposedParameters[index]; return m_Controller.ResolveExposedParameterPath(exposedParam.guid, false); } private float WidthOfRow(int index, GUIStyle leftStyle, GUIStyle rightStyle) { const float kMinSpacing = 25f; string infoString = GetInfoString(index); Vector2 infoSize = rightStyle.CalcSize(GUIContent.Temp(infoString)); Vector2 size = leftStyle.CalcSize(GUIContent.Temp(GetNameOfElement(index))); float width = size.x + infoSize.x + kMinSpacing; return width; } string GetNameOfElement(int index) { ExposedAudioParameter exposedParam = m_Controller.exposedParameters[index]; return exposedParam.name; } public void NameChanged(int index, string newName) { const int kMaxNameLength = 64; if (newName.Length > kMaxNameLength) { newName = newName.Substring(0, kMaxNameLength); Debug.LogWarning("Maximum name length of an exposed parameter is " + kMaxNameLength + " characters. Name truncated to '" + newName + "'"); } ExposedAudioParameter[] parameters = m_Controller.exposedParameters; parameters[index].name = newName; m_Controller.exposedParameters = parameters; } void Delete(int index) { if (m_Controller != null) { Undo.RecordObject(m_Controller, "Unexpose Mixer Parameter"); ExposedAudioParameter exposedParam = m_Controller.exposedParameters[index]; m_Controller.RemoveExposedParameter(exposedParam.guid); } } public void EndDragChild(ReorderableList list) { m_ControllerSerialized.ApplyModifiedProperties(); } public void OnEvent() { m_ReorderableListWithRenameAndScrollView.OnEvent(); } } }
UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParameterView.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParameterView.cs", "repo_id": "UnityCsReference", "token_count": 3053 }
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; using UnityEngine; using UnityEngine.UIElements; using Color = UnityEngine.Color; namespace UnityEditor.Audio.UIElements { internal class Tickmarks : VisualElement { private interface Scale { int DivisionCount(); string[] Labels(); int[] SubDivisionCount(); float[] LabelOffsets(); } private struct LargeScale : Scale { public int DivisionCount() { return 15; } public string[] Labels() { return new string[] { "80", "70", "60", "50", "40", "30", "24", "21", "18", "15", "12", "9", "6", "3", "0" }; } public int[] SubDivisionCount() { return new int[] { 4, 4, 4, 4, 4, 5, 2, 2, 2, 2, 2, 2, 2, 2 }; } public float[] LabelOffsets() { return new float[] { -6, -6, -6, -6, -6, -6, -6, -6, -6, -6, -6, -3.5f, -3.5f, -3.5f, -3.5f }; } } private struct CompactScale : Scale { public int DivisionCount() { return 8; } public string[] Labels() { return new string[] { "80", "60", "40", "24", "18", "12", "6", "0" }; } public int[] SubDivisionCount() { return new int[] { 4, 4, 3, 2, 2, 2, 2 }; } public float[] LabelOffsets() { return new float[] { -6, -6, -6, -6, -6, -6, -3.5f, -3.5f }; } } private struct MiniScale : Scale { public int DivisionCount() { return 5; } public string[] Labels() { return new string[] { "80", "45", "21", "12", "0" }; } public int[] SubDivisionCount() { return new int[] { 6, 3, 2, 3 }; } public float[] LabelOffsets() { return new float[] { -6, -6, -6, -6, -3.5f }; } } [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new Tickmarks(); } public Tickmarks() : base() { generateVisualContent += context => GenerateVisualContent(context); RegisterCallback<GeometryChangedEvent>(OnGeometryChanged); RegisterCallback<CustomStyleResolvedEvent>(CustomStylesResolved); } private static void CustomStylesResolved(CustomStyleResolvedEvent evt) { Tickmarks element = (Tickmarks)evt.currentTarget; element.GetColorsFromStylesheet(); } private static readonly CustomStyleProperty<Color> s_TickmarkColorProperty = new("--tickmark-color"); private Color m_TickmarkColor; private void GetColorsFromStylesheet() { if (customStyle.TryGetValue(s_TickmarkColorProperty, out var tickmarkColor)) { m_TickmarkColor = tickmarkColor; } } private void OnGeometryChanged(GeometryChangedEvent evt) { MarkDirtyRepaint(); } private static void GenerateVisualContent(MeshGenerationContext context) { var painter2D = context.painter2D; var contentRect = context.visualElement.contentRect; Scale scale = contentRect.width > 350 ? new LargeScale() : (contentRect.width > 175 ? new CompactScale() : new MiniScale()); var tickmarkColor = (context.visualElement as Tickmarks).m_TickmarkColor; var textColor = tickmarkColor.RGBMultiplied(1.2f); // Compensate for a bug in UI Toolkit which causes MeshGenerationContext.DrawText to render text lighter than the color that you provide. for (int index = 0; index < scale.DivisionCount(); index += 1) { var pos = contentRect.width * index / (scale.DivisionCount() - 1.0f); var rect = new Rect(pos - 0.5f, 5.0f, 1.0f, 8.0f); painter2D.fillColor = tickmarkColor; painter2D.BeginPath(); painter2D.MoveTo(new Vector2(rect.xMin, rect.yMin)); painter2D.LineTo(new Vector2(rect.xMax, rect.yMin)); painter2D.LineTo(new Vector2(rect.xMax, rect.yMax)); painter2D.LineTo(new Vector2(rect.xMin, rect.yMax)); painter2D.ClosePath(); painter2D.Fill(); } for (int index = 0; index < scale.DivisionCount() - 1; index += 1) { var pos = contentRect.width * index / (scale.DivisionCount() - 1.0f); var spacing = contentRect.width / (scale.DivisionCount() - 1.0f); var subDivCount = scale.SubDivisionCount()[index]; for (int subIndex = 0; subIndex < subDivCount; subIndex++) { var rect = new Rect(pos - 0.5f + spacing * (subIndex + 1.0f) / (subDivCount + 1.0f), 5.0f, 1.0f, 4.0f); painter2D.fillColor = tickmarkColor; painter2D.BeginPath(); painter2D.MoveTo(new Vector2(rect.xMin, rect.yMin)); painter2D.LineTo(new Vector2(rect.xMax, rect.yMin)); painter2D.LineTo(new Vector2(rect.xMax, rect.yMax)); painter2D.LineTo(new Vector2(rect.xMin, rect.yMax)); painter2D.ClosePath(); painter2D.Fill(); } } for (int index = 0; index < scale.DivisionCount(); index += 1) { var pos = contentRect.width * index / (scale.DivisionCount() - 1.0f); var rect = new Rect(pos - 10.0f, 10, 20.0f, 20.0f); context.DrawText(scale.Labels()[index], new Vector2(pos + scale.LabelOffsets()[index], 14.0f), 10.0f, textColor); } } } }
UnityCsReference/Editor/Mono/Audio/UIElements/Tickmarks.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/UIElements/Tickmarks.cs", "repo_id": "UnityCsReference", "token_count": 2745 }
285
// 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.Scripting; namespace UnityEditor.Build { [RequiredByNativeCode] public class BuildFailedException : Exception { // We can set the BuildFailedException to be silent if we know we have already printed an // error message for the failure. That is the case when the BuildFailedException originates // from the BeeBuildPostprocessor. That way we can avoid redundant error messages about builds // failing. private bool m_Silent; internal BuildFailedException(string message, bool silent = false) : base(message) { m_Silent = silent; } public BuildFailedException(string message) : base(message) { } public BuildFailedException(Exception innerException) : base(null, innerException) { } [RequiredByNativeCode] private bool IsSilent() { return m_Silent; } [RequiredByNativeCode] private Exception BuildFailedException_GetInnerException() { return InnerException; } } }
UnityCsReference/Editor/Mono/BuildPipeline/BuildFailedException.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/BuildPipeline/BuildFailedException.cs", "repo_id": "UnityCsReference", "token_count": 524 }
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.Bindings; namespace UnityEditor { [NativeHeader("Runtime/Scripting/Scripting.h")] internal class RuntimeClassMetadataUtils { [FreeFunction("Scripting::ScriptingWrapperTypeNameForNativeID")] extern public static string ScriptingWrapperTypeNameForNativeID(int id); } }
UnityCsReference/Editor/Mono/BuildPipeline/RuntimeClassMetadataUtils.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/BuildPipeline/RuntimeClassMetadataUtils.bindings.cs", "repo_id": "UnityCsReference", "token_count": 156 }
287
// 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 UnityEngine.Bindings; namespace UnityEditor.Build.Profile { [VisibleToOtherModules] internal enum ActionState { /// <summary> /// Action is visible and clickable. /// </summary> Enabled, /// <summary> /// Action is visible and non-clickable. /// </summary> Disabled, /// <summary> /// Action is hidden. /// </summary> Hidden } [VisibleToOtherModules] internal class BuildProfileWorkflowState { Action<BuildProfileWorkflowState> m_OnStateChanged; public BuildProfileWorkflowState(Action<BuildProfileWorkflowState> onStateChanged) { this.m_OnStateChanged = onStateChanged; } /// <summary> /// When set, build actions in the Build Profile Window will query the user for a build location. /// </summary> public bool askForBuildLocation { get; set; } = true; /// <summary> /// Name to be displayed in the build button name /// </summary> public string buildButtonDisplayName { get; set; } = L10n.Tr("Build"); /// <summary> /// Name to be displayed in the build and run button name /// </summary> public string buildAndRunButtonDisplayName { get; set; } = L10n.Tr("Build And Run"); /// <summary> /// Activate action allows a profile to be set as active profile. /// </summary> public ActionState activateAction { get; set; } = ActionState.Enabled; /// <summary> /// Allows invoking the Build Pipeline for the selected profile. /// </summary> public ActionState buildAction { get; set; } = ActionState.Enabled; /// <summary> /// Allows invoking the Build Pipeline for the selected profile with BuildAndRun flag set. /// </summary> public ActionState buildAndRunAction { get; set; } = ActionState.Enabled; /// <summary> /// Additional actions shown in the Build Profile Window as generally defined by the Build Profile Extension. /// </summary> /// <remarks> /// Primary use case is for 'Run Last Build' action from console paltforms which implement /// module specific build callbacks. /// </remarks> public IList<(string displayName, bool isOn, Action callback, ActionState state)> additionalActions { get; set; } = new List<(string, bool, Action, ActionState)>(); /// <summary> /// Reprocess the current state. /// </summary> public void Refresh() => m_OnStateChanged?.Invoke(this); /// <summary> /// Apply the next state, OnStateChanged callback should handle reducing the /// target state into the current one. /// </summary> public void Apply(BuildProfileWorkflowState next) => m_OnStateChanged?.Invoke(next); /// <summary> /// Merges two <see cref="ActionState"/> values. /// </summary> public static ActionState CalculateActionState(ActionState lhs, ActionState rhs) { if (lhs == ActionState.Hidden || rhs == ActionState.Hidden) return ActionState.Hidden; if (lhs == ActionState.Disabled || rhs == ActionState.Disabled) return ActionState.Disabled; return ActionState.Enabled; } /// <summary> /// Update the build action and the build and run action to the specified <see cref="ActionState"/> and refresh. /// </summary> public void UpdateBuildActionStates(ActionState buildActionState, ActionState buildAndRunActionState) { if (buildAction == buildActionState && buildAndRunAction == buildAndRunActionState) return; buildAction = buildActionState; buildAndRunAction = buildAndRunActionState; Refresh(); } } }
UnityCsReference/Editor/Mono/BuildProfile/BuildProfileState.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/BuildProfile/BuildProfileState.cs", "repo_id": "UnityCsReference", "token_count": 1588 }
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 System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEditor.Experimental.Rendering { [RequiredByNativeCode] [NativeHeader("Editor/Src/Camera/ScriptableBakedReflectionSystem.h")] [StructLayout(LayoutKind.Sequential)] class ScriptableBakedReflectionSystemWrapper : IDisposable, IScriptableBakedReflectionSystemStageNotifier { IntPtr m_Ptr = IntPtr.Zero; bool Disposed { get { return m_Ptr == IntPtr.Zero; } } internal IScriptableBakedReflectionSystem implementation { get; set; } internal ScriptableBakedReflectionSystemWrapper(IntPtr ptr) { m_Ptr = ptr; } ~ScriptableBakedReflectionSystemWrapper() { Dispose(false); } Hash128[] Internal_ScriptableBakedReflectionSystemWrapper_stateHashes { [RequiredByNativeCode] get { return implementation != null ? implementation.stateHashes : null; } } int Internal_ScriptableBakedReflectionSystemWrapper_stageCount { [RequiredByNativeCode] get { return implementation != null ? implementation.stageCount : 0; } } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } void IScriptableBakedReflectionSystemStageNotifier.EnterStage(int stage, string progressMessage, float progress) { if (Disposed) throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); ScriptingEnterStage(m_Ptr, stage, progressMessage, progress); } void IScriptableBakedReflectionSystemStageNotifier.ExitStage(int stage) { if (Disposed) throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); ScriptingExitStage(m_Ptr, stage); } void IScriptableBakedReflectionSystemStageNotifier.SetIsDone(bool isDone) { if (Disposed) throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); ScriptingSetIsDone(m_Ptr, isDone); } void Dispose(bool disposing) { m_Ptr = IntPtr.Zero; implementation = null; } [RequiredByNativeCode] void Internal_ScriptableBakedReflectionSystemWrapper_Tick(SceneStateHash deps) { if (Disposed) throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); if (implementation != null) implementation.Tick(deps, this); } [RequiredByNativeCode] void Internal_ScriptableBakedReflectionSystemWrapper_SynchronizeReflectionProbes() { if (Disposed) throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); if (implementation != null) implementation.SynchronizeReflectionProbes(); } [RequiredByNativeCode] void Internal_ScriptableBakedReflectionSystemWrapper_Clear() { if (Disposed) throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); if (implementation != null) implementation.Clear(); } [RequiredByNativeCode] void Internal_ScriptableBakedReflectionSystemWrapper_Cancel() { if (Disposed) throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); if (implementation != null) implementation.Cancel(); } [RequiredByNativeCode] bool Internal_ScriptableBakedReflectionSystemWrapper_BakeAllReflectionProbes() { if (Disposed) throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); if (implementation != null) return implementation.BakeAllReflectionProbes(); return false; } [StaticAccessor("ScriptableBakedReflectionSystem", StaticAccessorType.DoubleColon)] static extern void ScriptingEnterStage(IntPtr objPtr, int stage, string progressMessage, float progress); [StaticAccessor("ScriptableBakedReflectionSystem", StaticAccessorType.DoubleColon)] static extern void ScriptingExitStage(IntPtr objPtr, int stage); [StaticAccessor("ScriptableBakedReflectionSystem", StaticAccessorType.DoubleColon)] static extern void ScriptingSetIsDone(IntPtr objPtr, bool isDone); } }
UnityCsReference/Editor/Mono/Camera/ScriptableBakedReflectionSystemWrapper.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Camera/ScriptableBakedReflectionSystemWrapper.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2009 }
289
// 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 UnityEngine; namespace UnityEditor.Collaboration { internal static class AssetAccess { // Attempts to retrieve the Asset GUID within the Unity Object. // Failure: returns false and the given 'assetGUID' is set to empty string. // Success: returns true and updates 'assetGUID'. public static bool TryGetAssetGUIDFromObject(UnityEngine.Object objectWithGUID, out string assetGUID) { if (objectWithGUID == null) { throw new ArgumentNullException("objectWithGuid"); } bool success = false; if (objectWithGUID.GetType() == typeof(SceneAsset)) { success = TryGetAssetGUIDFromDatabase(objectWithGUID, out assetGUID); } else if (objectWithGUID.GetType() == typeof(GameObject)) { success = TryGetPrefabGUID(objectWithGUID, out assetGUID); } else { assetGUID = String.Empty; } return success; } // Attempts to retrieve the Asset corresponding to the given GUID. // Failure: returns false and the given 'asset' is set to null. // Success: returns true and updates 'asset'. public static bool TryGetAssetFromGUID(string assetGUID, out UnityEngine.Object asset) { if (assetGUID == null) { throw new ArgumentNullException("assetGUID"); } bool success = false; string objectPath = AssetDatabase.GUIDToAssetPath(assetGUID); if (objectPath == null) { asset = null; } else { asset = AssetDatabase.LoadMainAssetAtPath(objectPath); success = (asset != null); } return success; } // Expects the given 'gameObject' to have a 'PrefabType' which // is either an 'instance' or straight prefab. // Failure: assigns empty string to 'assetGUID', returns false. // Success: assigns the retrieval of the GUID to 'assetGUID' and returns true. private static bool TryGetPrefabGUID(UnityEngine.Object gameObject, out string assetGUID) { UnityEngine.Object prefabObject = null; if (PrefabUtility.IsPartOfNonAssetPrefabInstance(gameObject)) { prefabObject = PrefabUtility.GetCorrespondingObjectFromSource(gameObject); } else if (PrefabUtility.IsPartOfPrefabAsset(gameObject)) { prefabObject = gameObject; } bool success = false; if (prefabObject == null) { assetGUID = String.Empty; } else { success = TryGetAssetGUIDFromDatabase(prefabObject, out assetGUID); } return success; } // Interacts with 'AssetDatabase' to retrieve 'objectWithGUID' path // and in-turn uses this to access the GUID. // Failure: assigns an empty string to 'assetGUID', returns false. // Success: assigns the GUID result from 'AssetDatabase' to 'assetGUID' and returns true. private static bool TryGetAssetGUIDFromDatabase(UnityEngine.Object objectWithGUID, out string assetGUID) { if (objectWithGUID == null) { throw new ArgumentNullException("objectWithGuid"); } string _assetGUID = null; string objectPath = AssetDatabase.GetAssetPath(objectWithGUID); if (!String.IsNullOrEmpty(objectPath)) { _assetGUID = AssetDatabase.AssetPathToGUID(objectPath); } bool success = false; if (String.IsNullOrEmpty(_assetGUID)) { assetGUID = String.Empty; } else { assetGUID = _assetGUID; success = true; } return success; } } }
UnityCsReference/Editor/Mono/Collab/AssetAccess.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Collab/AssetAccess.cs", "repo_id": "UnityCsReference", "token_count": 2051 }
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 System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using JetBrains.Annotations; using Unity.Collections; using UnityEditorInternal; using UnityEngine; using UnityEngine.Rendering; namespace UnityEditor { internal partial class CustomEditorAttributes { static CustomEditorAttributes instance => k_Instance.Value; static readonly Lazy<CustomEditorAttributes> k_Instance = new(() => new CustomEditorAttributes()); readonly CustomEditorCache m_Cache = new CustomEditorCache(); readonly Func<List<MonoEditorType>, Type>[] m_GetEditorWhenSRPEnabled = { FindEditorsByRenderPipeline, FindEditorsOnlyByAttribute, UseNotSupportedOnInspector }; readonly Func<List<MonoEditorType>, Type>[] m_GetEditorWhenBuiltinEnabled = { FindEditorsOnlyByAttribute, UseNotSupportedOnInspector }; Func<List<MonoEditorType>, Type>[] m_CurrentGetEditorList => GraphicsSettings.isScriptableRenderPipelineEnabled ? m_GetEditorWhenSRPEnabled : m_GetEditorWhenBuiltinEnabled; CustomEditorAttributes() { Initialize(); } Type GetCustomEditorType(Type type, bool multiEdit) { if (type == null) return null; var editor = GetEditor(type, multiEdit, Pass.Regular); return editor ?? GetEditor(type, multiEdit, Pass.Fallback); } Type GetEditor(Type type, bool multiEdit, Pass pass) { for (var inspected = type; inspected != null; inspected = inspected.BaseType) { if (!m_Cache.TryGet(inspected, multiEdit, out var foundEditors)) continue; var filteredEditors = foundEditors .Where(e => IsAppropriateEditor(e, type != inspected, pass == Pass.Fallback)) .ToList(); var inspectorType = FindEditors(filteredEditors); if (inspectorType != null) return inspectorType; } return null; } Type FindEditors(List<MonoEditorType> editors) { if (!editors.Any()) return null; var getEditorActions = m_CurrentGetEditorList; for (int i = 0; i < getEditorActions.Length; i++) { var inspectorType = getEditorActions[i].Invoke(editors); if (inspectorType != null) return inspectorType; } return null; } static Type FindEditorsByRenderPipeline(List<MonoEditorType> editors) { Type editorToUse = null; var rpType = GraphicsSettings.currentRenderPipelineAssetType; for (var i = 0; i < editors.Count; i++) { var editor = editors[i]; if (editor.supportedRenderPipelineTypes == null) continue; var isEditorSupported = SupportedOnRenderPipelineAttribute.GetSupportedMode(editor.supportedRenderPipelineTypes, rpType); if (isEditorSupported == SupportedOnRenderPipelineAttribute.SupportedMode.Supported) return editor.inspectorType; if (isEditorSupported == SupportedOnRenderPipelineAttribute.SupportedMode.SupportedByBaseClass) editorToUse = editor.inspectorType; } return editorToUse; } static Type FindEditorsOnlyByAttribute(List<MonoEditorType> editors) { for (var i = 0; i < editors.Count; i++) { var editor = editors[i]; if (editor.supportedRenderPipelineTypes != null) continue; return editor.inspectorType; } return null; } static Type UseNotSupportedOnInspector(List<MonoEditorType> editors) { if (!editors.Any()) return null; var allEditorHaveSupportedOn = true; for (var i = 0; i < editors.Count; i++) { var editor = editors[i]; if (editor.supportedRenderPipelineTypes == null) allEditorHaveSupportedOn = false; } return allEditorHaveSupportedOn ? typeof(NotSupportedOnRenderPipelineInspector) : null; } static bool IsAppropriateEditor(MonoEditorType editor, bool isChildClass, bool isFallbackPass) { if (isChildClass && !editor.editorForChildClasses) // skip if it's a child class and this editor doesn't want to match on children return false; //if it is fallback pas we expect every editor to be fallback editor return isFallbackPass == editor.isFallback; } internal static void Rebuild() { instance.Initialize(); } void Initialize() { m_Cache.Clear(); var types = TypeCache.GetTypesWithAttribute<CustomEditor>(); foreach (var type in types) { var inspectAttr = type.GetCustomAttribute<CustomEditor>(false); if (inspectAttr.m_InspectedType == null) Debug.Log("Can't load custom inspector " + type.Name + " because the inspected type is null."); else if (!type.IsSubclassOf(typeof(Editor))) { // Suppress a warning on TweakMode, we did this bad in the default project folder // and it's going to be too hard for customers to figure out how to fix it and also quite pointless. if (type.FullName == "TweakMode" && type.IsEnum && inspectAttr.m_InspectedType.FullName == "BloomAndFlares") continue; Debug.LogWarning( type.Name + " uses the CustomEditor attribute but does not inherit from Editor.\nYou must inherit from Editor. See the Editor class script documentation."); } else { var isValid = TryGatherRenderPipelineTypes(type, inspectAttr, out var renderPipelineTypes); if (!isValid) { Debug.LogError($"Inspector {type.FullName} contains invalid attribute. This inspector will be skipped."); continue; } var monoEditorType = new MonoEditorType(type, renderPipelineTypes, inspectAttr.m_EditorForChildClasses, inspectAttr.isFallback); m_Cache.Add(type, inspectAttr, monoEditorType); } } } [MustUseReturnValue] static bool TryGatherRenderPipelineTypes([DisallowNull] Type type, [DisallowNull] CustomEditor inspectAttr, [NotNullWhen(true)] out Type[] results) { var supportedOnAttribute = type.GetCustomAttribute<SupportedOnRenderPipelineAttribute>(false); if (supportedOnAttribute != null) { if (supportedOnAttribute.renderPipelineTypes == null) { results = null; return false; } var supportedPipelines = supportedOnAttribute.renderPipelineTypes .Where(r => r != null) .Distinct() .ToArray(); if (supportedPipelines.Length > 0) { results = supportedPipelines; return true; } } #pragma warning disable CS0618 if (inspectAttr is CustomEditorForRenderPipelineAttribute attr) { results = new[] { attr.renderPipelineType }; return true; } #pragma warning restore CS0618 results = null; return true; } enum Pass { Regular, Fallback } internal readonly struct MonoEditorType { public readonly Type inspectorType; public readonly Type[] supportedRenderPipelineTypes; public readonly bool editorForChildClasses; public readonly bool isFallback; public MonoEditorType(Type inspectorType, Type[] supportedRenderPipelineTypes, bool editorForChildClasses, bool isFallback) { this.inspectorType = inspectorType; this.supportedRenderPipelineTypes = supportedRenderPipelineTypes; this.editorForChildClasses = editorForChildClasses; this.isFallback = isFallback; } } struct MonoEditorTypeStorage { public List<MonoEditorType> customEditors; public List<MonoEditorType> customEditorsMultiEdition; public MonoEditorTypeStorage() { customEditors = new List<MonoEditorType>(); customEditorsMultiEdition = new List<MonoEditorType>(); } } class CustomEditorCache { readonly Dictionary<Type, MonoEditorTypeStorage> m_CustomEditorCache = new(); readonly SortUnityTypesFirstComparer m_SortUnityTypesFirstComparer = new(); internal void Clear() { m_CustomEditorCache.Clear(); } internal bool TryGet(Type type, bool multiedition, out List<MonoEditorType> editors) { if (m_CustomEditorCache.TryGetValue(type, out var storedEditors)) { editors = multiedition ? storedEditors.customEditorsMultiEdition : storedEditors.customEditors; return true; } if (!type.IsGenericType) { editors = null; return false; } type = type.GetGenericTypeDefinition(); if (m_CustomEditorCache.TryGetValue(type, out storedEditors)) { editors = multiedition ? storedEditors.customEditorsMultiEdition : storedEditors.customEditors; return true; } editors = null; return false; } internal void Add(Type type, CustomEditor inspectAttr, MonoEditorType monoEditorType) { var isItExistInCache = m_CustomEditorCache.TryGetValue(inspectAttr.m_InspectedType, out var storage); if (!isItExistInCache) storage = new MonoEditorTypeStorage(); storage.customEditors.AddSorted(monoEditorType, m_SortUnityTypesFirstComparer); if (type.GetCustomAttribute<CanEditMultipleObjects>(false) != null) storage.customEditorsMultiEdition.AddSorted(monoEditorType, m_SortUnityTypesFirstComparer); if (!isItExistInCache) m_CustomEditorCache.Add(inspectAttr.m_InspectedType, storage); } struct SortUnityTypesFirstComparer : IComparer<MonoEditorType> { public int Compare(MonoEditorType typeA, MonoEditorType typeB) { return SortUnityTypesFirst(typeA, typeB); } static int SortUnityTypesFirst(MonoEditorType typeA, MonoEditorType typeB) { var xAssemblyIsUnity = InternalEditorUtility.IsUnityAssembly(typeA.inspectorType); var yAssemblyIsUnity = InternalEditorUtility.IsUnityAssembly(typeB.inspectorType); if (xAssemblyIsUnity == yAssemblyIsUnity) return 0; if (xAssemblyIsUnity) return 1; return -1; } } } } }
UnityCsReference/Editor/Mono/CustomEditorAttributes.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/CustomEditorAttributes.cs", "repo_id": "UnityCsReference", "token_count": 5955 }
291
// 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 UnityEditor.ShortcutManagement; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor { /// <summary> /// Add this interface to all classes that can generate part of the content of a dynamic hint by examining an instance of an object /// </summary> internal interface IComponentDynamicHintContentGenerator { VisualElement CreateContent(GameObject obj); } /// <summary> /// Add this interface to all classes that can generate part of the content of a dynamic hint by examining an asset /// </summary> internal interface IAssetDynamicHintContentGenerator { VisualElement CreateContent(UnityEngine.Object obj); } /// <summary> /// Base class for all classes that can generate part of the content of a dynamic hint by examining an instance of a ScriptableObject /// </summary> /// <typeparam name="T">The component for which to generate the content</typeparam> internal abstract class ScriptableObjectContentGenerator<T> : IAssetDynamicHintContentGenerator where T : ScriptableObject { readonly string m_Title; static T s_ComponentCache; protected ScriptableObjectContentGenerator(string title) { m_Title = title; } /// <summary> /// Defines the logic with which the object is examined to generate the content of the hint /// </summary> /// <param name="root">The root visualElement of the hint</param> /// <param name="objectToAnalyze">The object this Generator will examine</param> protected abstract void GenerateContent(VisualElement root, T objectToAnalyze); public VisualElement CreateContent(UnityEngine.Object obj) { s_ComponentCache = obj as T; if (s_ComponentCache == null) { return null; } VisualElement content = new VisualElement(); content.style.marginTop = 4; Label title = new Label(); title.style.marginBottom = 2; title.style.unityFontStyleAndWeight = FontStyle.Bold; title.text = m_Title; content.Add(title); GenerateContent(content, s_ComponentCache); return content; } protected VisualElement AddInfoField(string label, string value) { VisualElement root = new VisualElement(); root.style.flexDirection = FlexDirection.Row; root.style.flexGrow = 1; root.style.height = 15; root.Add(new Label(label)); Label valueLabel = new Label(value); root.Add(valueLabel); valueLabel.style.unityTextAlign = TextAnchor.UpperRight; return root; } } /// <summary> /// Base class for all classes that can generate part of the content of a dynamic hint by examining an instance of a GameObject /// </summary> /// <typeparam name="T">The component for which to generate the content</typeparam> internal abstract class ComponentContentGenerator<T> : IComponentDynamicHintContentGenerator where T : Component { readonly string m_Title; static readonly List<T> s_ComponentCache = new List<T>(); protected ComponentContentGenerator(string title) { m_Title = title; } /// <summary> /// Defines the logic with which the targeted Components of an object are examined to generate the content of the hint /// </summary> /// <param name="root">The root visualElement of the hint</param> /// <param name="components">The components this Generator will examine</param> protected abstract void GenerateContent(VisualElement root, List<T> components); public VisualElement CreateContent(GameObject obj) { obj.GetComponents(s_ComponentCache); if (s_ComponentCache.Count == 0) { return null; } VisualElement content = new VisualElement(); content.style.marginTop = 4; Label title = new Label(); title.style.marginBottom = 2; title.style.unityFontStyleAndWeight = FontStyle.Bold; title.text = m_Title; content.Add(title); GenerateContent(content, s_ComponentCache); return content; } protected VisualElement AddInfoField(string label, string value) { VisualElement root = new VisualElement(); root.style.flexDirection = FlexDirection.Row; root.style.flexGrow = 1; root.style.height = 15; root.Add(new Label(label)); Label valueLabel = new Label(value); root.Add(valueLabel); valueLabel.style.unityTextAlign = TextAnchor.UpperRight; return root; } } /// <summary> /// Base class for all dynamic hints /// </summary> internal abstract class DynamicHintContent { protected VisualElement root; bool m_Extended; /// <summary> /// Gets or sets the state of the hint. /// </summary> public bool Extended { get { return m_Extended; } set { if (m_Extended == value) { return; } m_Extended = value; OnExtendedStateChanged(m_Extended); } } /// <summary> /// Called whenever the Extended state of the hint changes. /// </summary> /// <param name="extended"></param> protected internal virtual void OnExtendedStateChanged(bool extended) {} /// <summary> /// Override this to update the content of the dynamic hint every editor frame (I.E: when playing videos) /// </summary> internal virtual void Update() {} /// <summary> /// Override this to load the UXML + USS of your dynamic hint and to initialize its UI logic and callbacks /// </summary> /// <returns></returns> protected internal virtual VisualElement CreateContent() { return null; } /// <summary> /// Override this in order to return the right dimensions dependning on the dynamic hints' state and displayed controls /// </summary> /// <returns></returns> protected internal virtual Vector2 GetContentSize() { return Vector2.zero; } internal Rect GetRect() { return root.contentRect; } /// <summary> /// Loads the default StyleSheet according to the desired type of dynamic hint. /// The StyleSheet will be added as the first StyleSheet of the element. /// </summary> /// <param name="element">The element to which the StyleSheet will be added to. This is usually the root of your dynamic hint.</param> /// <param name="useInstanceTooltipStyleSheet">If true, the StyleSheet commonly used in dynamic hints that represent data of an instance of an Object will be applied. /// Otherwise, the style commonly applied to dynamic hints that explain how properties or editor tools work will be applied.</param> protected void AddDefaultStyleSheetAsFirstTo(VisualElement element, bool useInstanceTooltipStyleSheet) { StyleSheet defaultStyleSheet = useInstanceTooltipStyleSheet ? DynamicHintUtility.GetDefaultInstanceDynamicHintStyleSheet() : DynamicHintUtility.GetDefaultDynamicHintStyleSheet(); if (element.styleSheets.count > 0) { element.styleSheetList.Insert(0, defaultStyleSheet); } else { element.styleSheets.Add(defaultStyleSheet); } } internal string ToTooltipString() { return DynamicHintUtility.Serialize(this); } /// <summary> /// Converts the hint to a string /// </summary> /// <param name="hint">the hint to convert</param> public static implicit operator string(DynamicHintContent hint) { return hint.ToTooltipString(); } } /// <summary> /// Tells the Dynamic Hint system which method to use to generate the Dynamic Hint of a specific class. /// Must be placed on a static method. /// </summary> [AttributeUsage(AttributeTargets.Method)] internal /*sealed*/ class DynamicHintGeneratorAttribute : Attribute //todo: make this sealed once it becomes public. For now, it can't be sealed as internal bridges need to inherit from it { internal Type m_Type; public DynamicHintGeneratorAttribute(Type type) { m_Type = type; } } }
UnityCsReference/Editor/Mono/DynamicHints/DynamicHintContent.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/DynamicHints/DynamicHintContent.cs", "repo_id": "UnityCsReference", "token_count": 3357 }
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 System.Collections.Generic; using UnityEditor.Build; using UnityEditor.Inspector.GraphicsSettingsInspectors; using UnityEditor.Rendering.Settings; using UnityEngine.Bindings; using UnityEngine.Rendering; using Object = UnityEngine.Object; namespace UnityEditor.Rendering { [NativeHeader("Editor/Mono/EditorGraphicsSettings.bindings.h")] [StaticAccessor("EditorGraphicsSettingsScripting", StaticAccessorType.DoubleColon)] public sealed partial class EditorGraphicsSettings { [NativeName("SetTierSettings")] extern internal static void SetTierSettingsImpl(BuildTargetGroup target, GraphicsTier tier, TierSettings settings); extern public static TierSettings GetTierSettings(BuildTargetGroup target, GraphicsTier tier); public static TierSettings GetTierSettings(NamedBuildTarget target, GraphicsTier tier) => GetTierSettings(target.ToBuildTargetGroup(), tier); extern internal static TierSettings GetCurrentTierSettings(); extern internal static bool AreTierSettingsAutomatic(BuildTargetGroup target, GraphicsTier tier); extern internal static void MakeTierSettingsAutomatic(BuildTargetGroup target, GraphicsTier tier, bool automatic); extern internal static void OnUpdateTierSettings(BuildTargetGroup target, bool shouldReloadShaders); // we give access to shader settings from both UI and script, and usually script access do not touch Undo system by itself // hence we provide small helper for our UI to register Undo changes when needed extern internal static void RegisterUndo(); extern private static AlbedoSwatchInfo[] GetAlbedoSwatches(); extern private static void SetAlbedoSwatches(AlbedoSwatchInfo[] swatches); public static AlbedoSwatchInfo[] albedoSwatches { get { return GetAlbedoSwatches(); } set { SetAlbedoSwatches(value); } } extern public static BatchRendererGroupStrippingMode batchRendererGroupShaderStrippingMode { get; } [NativeName("RegisterRenderPipelineSettings")] static extern bool Internal_TryRegisterRenderPipeline(string renderpipelineName, Object settings); [NativeName("UnregisterRenderPipelineSettings")] static extern bool Internal_TryUnregisterRenderPipeline(string renderpipelineName); [NativeName("GetSettingsForRenderPipeline")] static extern Object Internal_GetSettingsForRenderPipeline(string renderpipelineName); [NativeName("GetSettingsInstanceIDForRenderPipeline")] internal static extern int Internal_GetSettingsInstanceIDForRenderPipeline(string renderpipelineName); private static void CheckRenderPipelineType(Type renderPipelineType) { if (renderPipelineType == null) throw new ArgumentNullException(nameof(renderPipelineType)); if (!typeof(RenderPipeline).IsAssignableFrom(renderPipelineType)) throw new ArgumentException($"{renderPipelineType} must be a valid {nameof(RenderPipeline)}"); } public static void SetRenderPipelineGlobalSettingsAsset(Type renderPipelineType, RenderPipelineGlobalSettings newSettings) { //In Worker thread, we cannot update assets if (AssetDatabase.IsAssetImportWorkerProcess()) return; CheckRenderPipelineType(renderPipelineType); bool globalSettingsAssetChanged; if (newSettings != null) { RenderPipelineGraphicsSettingsManager.PopulateRenderPipelineGraphicsSettings(newSettings); globalSettingsAssetChanged = Internal_TryRegisterRenderPipeline(renderPipelineType.FullName, newSettings); } else globalSettingsAssetChanged = Internal_TryUnregisterRenderPipeline(renderPipelineType.FullName); if (globalSettingsAssetChanged) { var rpAsset = RenderPipelineManager.currentPipelineAsset; if (rpAsset != null && rpAsset.pipelineType == renderPipelineType) RenderPipelineManager.RecreateCurrentPipeline(rpAsset); } GraphicsSettingsInspectorUtility.ReloadGraphicsSettingsEditorIfNeeded(); } public static void SetRenderPipelineGlobalSettingsAsset<T>(RenderPipelineGlobalSettings newSettings) where T : RenderPipeline { SetRenderPipelineGlobalSettingsAsset(typeof(T), newSettings); } public static RenderPipelineGlobalSettings GetRenderPipelineGlobalSettingsAsset(Type renderPipelineType) { CheckRenderPipelineType(renderPipelineType); return Internal_GetSettingsForRenderPipeline(renderPipelineType.FullName) as RenderPipelineGlobalSettings; } public static RenderPipelineGlobalSettings GetRenderPipelineGlobalSettingsAsset<T>() where T : RenderPipeline { return GetRenderPipelineGlobalSettingsAsset(typeof(T)); } public static bool TryGetRenderPipelineSettingsForPipeline<TSettings, TPipeline>(out TSettings settings) where TSettings : class, IRenderPipelineGraphicsSettings where TPipeline : RenderPipeline { return TryGetRenderPipelineSettingsForPipeline(typeof(TPipeline), out settings); } public static bool TryGetRenderPipelineSettingsForPipeline<TSettings>(Type renderPipelineType, out TSettings settings) where TSettings : class, IRenderPipelineGraphicsSettings { settings = null; var pipelineGlobalSettings = GraphicsSettings.GetSettingsForRenderPipeline(renderPipelineType); if (pipelineGlobalSettings == null) return false; if (pipelineGlobalSettings.TryGet(typeof(TSettings), out var baseSettings)) settings = baseSettings as TSettings; return settings != null; } public static IEnumerable<Type> GetSupportedRenderPipelineGraphicsSettingsTypesForPipeline<T>() where T : RenderPipelineAsset { foreach(var info in RenderPipelineGraphicsSettingsManager.FetchRenderPipelineGraphicsSettingInfos(typeof(T))) yield return info.type; } public static void PopulateRenderPipelineGraphicsSettings(RenderPipelineGlobalSettings settings) { RenderPipelineGraphicsSettingsManager.PopulateRenderPipelineGraphicsSettings(settings); } [NativeName("GraphicsSettingsCount")] static extern int Internal_GraphicsSettingsCount(); [NativeName("GetSettingsForRenderPipelineAt")] static extern Object Internal_GetSettingsForRenderPipelineAt(int index); internal static void ForEachPipelineSettings(Action<RenderPipelineGlobalSettings> action) { int count = Internal_GraphicsSettingsCount(); for (int i = 0; i < count; ++i) action?.Invoke(Internal_GetSettingsForRenderPipelineAt(i) as RenderPipelineGlobalSettings); } public static TSettingsInterfaceType[] GetRenderPipelineSettingsFromInterface<TSettingsInterfaceType>() where TSettingsInterfaceType : class, IRenderPipelineGraphicsSettings { if (!GraphicsSettings.TryGetCurrentRenderPipelineGlobalSettings(out RenderPipelineGlobalSettings asset)) return new TSettingsInterfaceType[] {}; if (asset.GetSettingsImplementingInterface<TSettingsInterfaceType>(out var baseSettings)) { return baseSettings.ToArray(); } return new TSettingsInterfaceType[] {}; } public static bool TryGetFirstRenderPipelineSettingsFromInterface<TSettingsInterfaceType>(out TSettingsInterfaceType settings) where TSettingsInterfaceType : class, IRenderPipelineGraphicsSettings { settings = null; if (!GraphicsSettings.TryGetCurrentRenderPipelineGlobalSettings(out RenderPipelineGlobalSettings asset)) return false; if (asset.TryGetFirstSettingsImplementingInterface<TSettingsInterfaceType>(out var baseSettings)) { settings = baseSettings; return true; } return false; } public static bool TryGetRenderPipelineSettingsFromInterface<TSettingsInterfaceType>(out TSettingsInterfaceType[] settings) where TSettingsInterfaceType : class, IRenderPipelineGraphicsSettings { settings = null; if (!GraphicsSettings.TryGetCurrentRenderPipelineGlobalSettings(out RenderPipelineGlobalSettings asset)) return false; if (asset.GetSettingsImplementingInterface<TSettingsInterfaceType>(out var baseSettings)) settings = baseSettings.ToArray(); return settings != null; } public static bool TryGetRenderPipelineSettingsFromInterfaceForPipeline<TSettingsInterfaceType, TPipeline>(out TSettingsInterfaceType[] settings) where TSettingsInterfaceType : class, IRenderPipelineGraphicsSettings where TPipeline : RenderPipeline { return TryGetRenderPipelineSettingsFromInterfaceForPipeline(typeof(TPipeline), out settings); } public static bool TryGetRenderPipelineSettingsFromInterfaceForPipeline<TSettingsInterfaceType>(Type renderPipelineType, out TSettingsInterfaceType[] settings) where TSettingsInterfaceType : class, IRenderPipelineGraphicsSettings { settings = null; var pipelineGlobalSettings = GraphicsSettings.GetSettingsForRenderPipeline(renderPipelineType); if (pipelineGlobalSettings == null) return false; if (pipelineGlobalSettings.GetSettingsImplementingInterface<TSettingsInterfaceType>(out var baseSettings)) settings = baseSettings.ToArray(); return settings != null; } } }
UnityCsReference/Editor/Mono/EditorGraphicsSettings.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/EditorGraphicsSettings.bindings.cs", "repo_id": "UnityCsReference", "token_count": 3785 }
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.Bindings; namespace UnityEditor { // Embedded Linux && QNX Architecture [NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")] public enum EmbeddedArchitecture { [UnityEngine.InspectorName("Arm64")] Arm64 = 0, [System.Obsolete("Arm32 has been removed in 2023.2")] Arm32 = 1, [UnityEngine.InspectorName("X64")] X64 = 2, [System.Obsolete("X86 has been removed in 2023.2")] X86 = 3, } [NativeHeader("Editor/Src/EditorUserBuildSettings.h")] public partial class EditorUserBuildSettings { // Embedded Linux && QNX remote device information public static extern bool remoteDeviceInfo { get; set; } public static extern string remoteDeviceAddress { get; set; } public static extern string remoteDeviceUsername { get; set; } public static extern string remoteDeviceExports { get; set; } public static extern string pathOnRemoteDevice { get; set; } } }
UnityCsReference/Editor/Mono/EditorUserBuildSettingsEmbeddedCommon.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/EditorUserBuildSettingsEmbeddedCommon.bindings.cs", "repo_id": "UnityCsReference", "token_count": 441 }
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; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEditor { public partial class FileUtil { internal static void ReplaceText(string path, params string[] input) { path = NiceWinPath(path); string[] data = File.ReadAllLines(path); for (int i = 0; i < input.Length; i += 2) { for (int q = 0; q < data.Length; ++q) { data[q] = data[q].Replace(input[i], input[i + 1]); } } File.WriteAllLines(path, data); } internal static bool ReplaceTextRegex(string path, params string[] input) { bool res = false; path = NiceWinPath(path); string[] data = File.ReadAllLines(path); for (int i = 0; i < input.Length; i += 2) { for (int q = 0; q < data.Length; ++q) { string s = data[q]; data[q] = Regex.Replace(s, input[i], input[i + 1]); if (s != (string)data[q]) res = true; } } File.WriteAllLines(path, data); return res; } internal static bool AppendTextAfter(string path, string find, string append) { bool res = false; path = NiceWinPath(path); var data = new List<string>(File.ReadAllLines(path)); for (int q = 0; q < data.Count; ++q) { if (data[q].Contains(find)) { data.Insert(q + 1, append); res = true; break; } } File.WriteAllLines(path, data.ToArray()); return res; } internal static void CopyDirectoryRecursive(string source, string target) { CopyDirectoryRecursive(source, target, overwrite: false, ignoreMeta: false); } internal static void CopyDirectoryRecursive(string source, string target, bool overwrite) { CopyDirectoryRecursive(source, target, overwrite, ignoreMeta: false); } internal static void CopyDirectory(string source, string target, bool overwrite) { CopyDirectoryFiltered(source, target, overwrite, f => true, false); } internal static void CopyDirectoryRecursive(string source, string target, bool overwrite, bool ignoreMeta) { CopyDirectoryRecursiveFiltered(source, target, overwrite, ignoreMeta ? @"\.meta$" : null); } internal static void CopyDirectoryRecursiveForPostprocess(string source, string target, bool overwrite) { CopyDirectoryRecursiveFiltered(source, target, overwrite, @".*/\.+|\.meta$"); } internal static void CopyDirectoryRecursiveFiltered(string source, string target, bool overwrite, string regExExcludeFilter) { CopyDirectoryFiltered(source, target, overwrite, regExExcludeFilter, true); } internal static void CopyDirectoryFiltered(string source, string target, bool overwrite, string regExExcludeFilter, bool recursive) { Regex exclude = null; try { if (regExExcludeFilter != null) exclude = new Regex(regExExcludeFilter); } catch (ArgumentException) { Debug.Log("CopyDirectoryRecursive: Pattern '" + regExExcludeFilter + "' is not a correct Regular Expression. Not excluding any files."); return; } Func<string, bool> includeCallback = file => (exclude == null || !exclude.IsMatch(file)); CopyDirectoryFiltered(source, target, overwrite, includeCallback, recursive); } internal static void CopyDirectoryFiltered(string source, string target, bool overwrite, Func<string, bool> includeCallback, bool recursive) { // Check if the target directory exists, but dont create it yet until we know there are files to copy. bool createDirectory = !Directory.Exists(target); // Copy each file into the new directory. foreach (string fi in Directory.GetFiles(source)) { if (!includeCallback(fi)) continue; if (createDirectory) { Directory.CreateDirectory(target); overwrite = false; // no reason to perform this on subdirs createDirectory = false; } string fname = Path.GetFileName(fi); string targetfname = Path.Combine(target, fname); UnityFileCopy(fi, targetfname, overwrite); } if (!recursive) return; // Copy each subdirectory recursively. foreach (string di in Directory.GetDirectories(source)) { if (!includeCallback(di)) continue; string fname = Path.GetFileName(di); CopyDirectoryFiltered(Path.Combine(source, fname), Path.Combine(target, fname), overwrite, includeCallback, recursive); } } internal static void UnityDirectoryDelete(string path) { UnityDirectoryDelete(path, false); } internal static void UnityDirectoryDelete(string path, bool recursive) { Directory.Delete(NiceWinPath(path), recursive); } // set the System.IO.FileAttributes.Normal recursively on all files in target_dir internal static void UnityDirectoryRemoveReadonlyAttribute(string target_dir) { string[] files = Directory.GetFiles(target_dir); string[] dirs = Directory.GetDirectories(target_dir); foreach (string file in files) { File.SetAttributes(file, System.IO.FileAttributes.Normal); } foreach (string dir in dirs) { UnityDirectoryRemoveReadonlyAttribute(dir); } } internal static void MoveFileIfExists(string src, string dst) { if (File.Exists(src)) { DeleteFileOrDirectory(dst); MoveFileOrDirectory(src, dst); File.SetLastWriteTime(dst, DateTime.Now); } } internal static void CopyFileIfExists(string src, string dst, bool overwrite) { if (File.Exists(src)) { UnityFileCopy(src, dst, overwrite); } } internal static void UnityFileCopy(string from, string to, bool overwrite) { File.Copy(NiceWinPath(from), NiceWinPath(to), overwrite); } internal static bool ReadFileContentBinary(string assetPath, out byte[] fileContent, out string errorMessage) { fileContent = null; errorMessage = null; string absolutePath = FileUtil.PathToAbsolutePath(assetPath); try { fileContent = File.ReadAllBytes(absolutePath); } catch (Exception e) { fileContent = null; errorMessage = e.Message; } return fileContent != null; } internal static string NiceWinPath(string unityPath) { // IO functions do not like mixing of \ and / slashes, esp. for windows network paths (\\path) return Application.platform == RuntimePlatform.WindowsEditor ? unityPath.Replace("/", @"\") : unityPath; } internal static string UnityGetFileNameWithoutExtension(string path) { // this is because on Windows \\ means network path, in unity all \ are converted to / // network paths become // and Path class functions think it's the same as / return Path.GetFileNameWithoutExtension(path.Replace("//", @"\\")).Replace(@"\\", "//"); } internal static string UnityGetFileName(string path) { // this is because on Windows \\ means network path, in unity all \ are converted to / // network paths become // and Path class functions think it's the same as / return Path.GetFileName(path.Replace("//", @"\\")).Replace(@"\\", "//"); } internal static string UnityGetDirectoryName(string path) { // this is because on Windows \\ means network path, in unity all \ are converted to / // network paths become // and Path class functions think it's the same as / return Path.GetDirectoryName(path.Replace("//", @"\\")).Replace(@"\\", "//"); } internal static void UnityFileCopy(string from, string to) { UnityFileCopy(from, to, false); } internal static void CreateOrCleanDirectory(string dir) { if (Directory.Exists(dir)) Directory.Delete(dir, true); Directory.CreateDirectory(dir); } internal static string RemovePathPrefix(string fullPath, string prefix) { var partsOfFull = fullPath.Split(Path.DirectorySeparatorChar); var partsOfPrefix = prefix.Split(Path.DirectorySeparatorChar); int index = 0; if (partsOfFull[0] == string.Empty) index = 1; while (index < partsOfFull.Length && index < partsOfPrefix.Length && partsOfFull[index] == partsOfPrefix[index]) ++index; if (index == partsOfFull.Length) return ""; return string.Join(Path.DirectorySeparatorChar.ToString(), partsOfFull, index, partsOfFull.Length - index); } internal static string CombinePaths(params string[] paths) { if (null == paths) return string.Empty; return string.Join(Path.DirectorySeparatorChar.ToString(), paths); } internal static List<string> GetAllFilesRecursive(string path) { List<string> files = new List<string>(); WalkFilesystemRecursively(path, (p) => { files.Add(p); }, (p) => { return true; }); return files; } internal static void WalkFilesystemRecursively(string path, Action<string> fileCallback, Func<string, bool> directoryCallback) { foreach (string file in Directory.GetFiles(path)) fileCallback(file); foreach (string subdir in Directory.GetDirectories(path)) { if (directoryCallback(subdir)) WalkFilesystemRecursively(subdir, fileCallback, directoryCallback); } } internal static long GetDirectorySize(string path) { var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); long filesSize = 0; foreach (var file in files) { var info = new FileInfo(file); filesSize += info.Length; } return filesSize; } internal static bool IsReadOnly(UnityEngine.Object asset) { if (!AssetDatabase.IsOpenForEdit(asset, StatusQueryOptions.UseCachedIfPossible)) { return false; } string assetPath = AssetDatabase.GetAssetPath(asset); if (!string.IsNullOrEmpty(assetPath)) { return (File.GetAttributes(assetPath) & FileAttributes.ReadOnly) != 0; } return false; } internal static bool HasReadOnly(IEnumerable<UnityEngine.Object> assets) { foreach (UnityEngine.Object asset in assets) if (IsReadOnly(asset)) return true; return false; } [RequiredByNativeCode] internal static bool MakeWritable(string path) { string absolutePath = FileUtil.PathToAbsolutePath(path); if (Directory.Exists(absolutePath)) { foreach (var file in GetAllFilesRecursive(absolutePath)) { var fileInfo = new FileInfo(file); fileInfo.IsReadOnly = false; } return true; } if (File.Exists(absolutePath)) { var fileInfo = new FileInfo(absolutePath); fileInfo.IsReadOnly = false; return true; } return false; } internal static bool WriteTextFileToDisk(string path, string content) { return WriteTextFileToDisk(path, content, out string message); } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static bool WriteTextFileToDisk(string path, string content, out string message) { if (AssetDatabase.IsOpenForEdit(path, out message) || AssetDatabase.MakeEditable(path)) { var fileInfo = new FileInfo(path); if (fileInfo.IsReadOnly) MakeWritable(path); try { File.WriteAllText(path, content); return true; } catch (Exception e) { message = e.Message; } } if (string.IsNullOrEmpty(message)) { message = "Failed to write file " + path + " to disk.\nVerify that the file is not read-only or locked."; } return false; } } }
UnityCsReference/Editor/Mono/FileUtil.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/FileUtil.cs", "repo_id": "UnityCsReference", "token_count": 6774 }
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 UnityEngineInternal; namespace UnityEditor { public partial class Lightmapping { [System.Obsolete("lightmapSnapshot has been deprecated. Use lightingDataAsset instead (UnityUpgradable) -> lightingDataAsset", true)] public static LightmapSnapshot lightmapSnapshot { get { return null; } set {} } [System.Obsolete("BakeSelectedAsync has been deprecated. Use BakeAsync instead (UnityUpgradable) -> BakeAsync()", true)] public static bool BakeSelectedAsync() { return false; } [System.Obsolete("BakeSelected has been deprecated. Use Bake instead (UnityUpgradable) -> Bake()", true)] public static bool BakeSelected() { return false; } [System.Obsolete("BakeLightProbesOnlyAsync has been deprecated. Use BakeAsync instead (UnityUpgradable) -> BakeAsync()", true)] public static bool BakeLightProbesOnlyAsync() { return false; } [System.Obsolete("BakeLightProbesOnly has been deprecated. Use Bake instead (UnityUpgradable) -> Bake()", true)] public static bool BakeLightProbesOnly() { return false; } } }
UnityCsReference/Editor/Mono/GI/Lightmapping.deprecated.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GI/Lightmapping.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 438 }
296
// 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 UnityEngine.Scripting; namespace UnityEditor { internal class BumpMapSettingsFixingWindow : EditorWindow { [RequiredByNativeCode] public static void ShowSettingsWindow(string[] paths) { BumpMapSettingsFixingWindow win = EditorWindow.GetWindow<BumpMapSettingsFixingWindow>(true); win.SetPaths(paths); win.ShowUtility(); } class Styles { public GUIStyle selected = "OL SelectedRow"; public GUIStyle box = "OL Box"; public GUIStyle button = "LargeButton"; public GUIContent overviewText = EditorGUIUtility.TrTextContent("A Material is using the texture as a normal map.\nThe texture must be marked as a normal map in the import settings."); } static Styles s_Styles = null; ListViewState m_LV = new ListViewState(); string[] m_Paths; public BumpMapSettingsFixingWindow() { titleContent = EditorGUIUtility.TrTextContent("NormalMap settings"); } public void SetPaths(string[] paths) { m_Paths = paths; m_LV.totalRows = paths.Length; } void OnGUI() { if (s_Styles == null) { s_Styles = new Styles(); minSize = new Vector2(400, 300); position = new Rect(position.x, position.y, minSize.x, minSize.y); } GUILayout.Space(5); GUILayout.Label(s_Styles.overviewText); GUILayout.Space(10); GUILayout.BeginHorizontal(); GUILayout.Space(10); foreach (ListViewElement el in ListViewGUILayout.ListView(m_LV, s_Styles.box)) { if (el.row == m_LV.row && Event.current.type == EventType.Repaint) s_Styles.selected.Draw(el.position, false, false, false, false); GUILayout.Label(m_Paths[el.row]); } GUILayout.Space(10); GUILayout.EndHorizontal(); GUILayout.Space(10); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Fix now", s_Styles.button)) { InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(1); Close(); } if (GUILayout.Button("Ignore", s_Styles.button)) { InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(0); Close(); } GUILayout.Space(10); GUILayout.EndHorizontal(); GUILayout.Space(10); } void OnDestroy() { InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(0); } } }
UnityCsReference/Editor/Mono/GUI/BumpMapSettingsFixingWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/BumpMapSettingsFixingWindow.cs", "repo_id": "UnityCsReference", "token_count": 1478 }
297
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Experimental; using UnityEditor.StyleSheets; using UnityEngine; using UnityEngine.Internal; // See Style Guide in wiki for more information on editor styles. namespace UnityEditor { // Common GUIStyles used for EditorGUI controls. public sealed class EditorStyles { internal const int kInspectorPaddingLeft = 8 + 10; internal const int kInspectorPaddingRight = 4; internal const int kInspectorPaddingTop = 4; // Style used for the labeled on all EditorGUI overloads that take a prefix label public static GUIStyle label { get { return s_Current.m_Label; } } internal GUIStyle m_Label; // Style for label with small font. public static GUIStyle miniLabel { get { return s_Current.m_MiniLabel; } } private GUIStyle m_MiniLabel; // Style for label with large font. public static GUIStyle largeLabel { get { return s_Current.m_LargeLabel; } } private GUIStyle m_LargeLabel; // Style for bold label. public static GUIStyle boldLabel { get { return s_Current.m_BoldLabel; } } private GUIStyle m_BoldLabel; // Style for mini bold label. public static GUIStyle miniBoldLabel { get { return s_Current.m_MiniBoldLabel; } } private GUIStyle m_MiniBoldLabel; // Style for centered grey mini label. public static GUIStyle centeredGreyMiniLabel { get { return s_Current.m_CenteredGreyMiniLabel; } } private GUIStyle m_CenteredGreyMiniLabel; // Style for word wrapped mini label. public static GUIStyle wordWrappedMiniLabel { get { return s_Current.m_WordWrappedMiniLabel; } } private GUIStyle m_WordWrappedMiniLabel; // Style for word wrapped label. public static GUIStyle wordWrappedLabel { get { return s_Current.m_WordWrappedLabel; } } private GUIStyle m_WordWrappedLabel; // Style for link label. public static GUIStyle linkLabel { get { return s_Current.m_LinkLabel; } } private GUIStyle m_LinkLabel; // Style for white label. public static GUIStyle whiteLabel { get { return s_Current.m_WhiteLabel; } } private GUIStyle m_WhiteLabel; // Style for white mini label. public static GUIStyle whiteMiniLabel { get { return s_Current.m_WhiteMiniLabel; } } private GUIStyle m_WhiteMiniLabel; // Style for white large label. public static GUIStyle whiteLargeLabel { get { return s_Current.m_WhiteLargeLabel; } } private GUIStyle m_WhiteLargeLabel; // Style for white bold label. public static GUIStyle whiteBoldLabel { get { return s_Current.m_WhiteBoldLabel; } } private GUIStyle m_WhiteBoldLabel; // Style used for a radio button public static GUIStyle radioButton { get { return s_Current.m_RadioButton; } } private GUIStyle m_RadioButton; // Style used for a standalone small button. public static GUIStyle miniButton { get { return s_Current.m_MiniButton; } } private GUIStyle m_MiniButton; // Style used for the leftmost button in a horizontal button group. public static GUIStyle miniButtonLeft { get { return s_Current.m_MiniButtonLeft; } } private GUIStyle m_MiniButtonLeft; // Style used for the middle buttons in a horizontal group. public static GUIStyle miniButtonMid { get { return s_Current.m_MiniButtonMid; } } private GUIStyle m_MiniButtonMid; // Style used for the rightmost button in a horizontal group. public static GUIStyle miniButtonRight { get { return s_Current.m_MiniButtonRight; } } private GUIStyle m_MiniButtonRight; public static GUIStyle miniPullDown { get { return s_Current.m_MiniPullDown; } } private GUIStyle m_MiniPullDown; // Style used for EditorGUI::ref::TextField public static GUIStyle textField { get { return s_Current.m_TextField; } } internal GUIStyle m_TextField; // Style used for bold text field internal static GUIStyle boldTextField { get { return s_Current.m_BoldTextField; } } private GUIStyle m_BoldTextField; // Style used for EditorGUI::ref::TextArea public static GUIStyle textArea { get { return s_Current.m_TextArea; } } internal GUIStyle m_TextArea; // Smaller text field public static GUIStyle miniTextField { get { return s_Current.m_MiniTextField; } } private GUIStyle m_MiniTextField; // Style used for field editors for numbers public static GUIStyle numberField { get { return s_Current.m_NumberField; } } private GUIStyle m_NumberField; // Style used for EditorGUI::ref::Popup, EditorGUI::ref::EnumPopup, public static GUIStyle popup { get { return s_Current.m_Popup; } } private GUIStyle m_Popup; // Style used for headings for structures (Vector3, Rect, etc) [System.Obsolete("structHeadingLabel is deprecated, use EditorStyles.label instead.")] public static GUIStyle structHeadingLabel { get { return s_Current.m_Label; } } // Style used for headings for object fields. public static GUIStyle objectField { get { return s_Current.m_ObjectField; } } private GUIStyle m_ObjectField; internal static GUIStyle objectFieldButton { get { return s_Current.m_ObjectFieldButton; } } private GUIStyle m_ObjectFieldButton; // Style used for headings for the Select button in object fields. public static GUIStyle objectFieldThumb { get { return s_Current.m_ObjectFieldThumb; } } private GUIStyle m_ObjectFieldThumb; // Style used for texture object field with minimal height (useful for single line texture objectfields) public static GUIStyle objectFieldMiniThumb { get { return s_Current.m_ObjectFieldMiniThumb; } } private GUIStyle m_ObjectFieldMiniThumb; // Style used for headings for Color fields. public static GUIStyle colorField { get { return s_Current.m_ColorField; } } private GUIStyle m_ColorField; // Style used for headings for Layer masks. public static GUIStyle layerMaskField { get { return s_Current.m_LayerMaskField; } } private GUIStyle m_LayerMaskField; // Style used for headings for EditorGUI::ref::Toggle. public static GUIStyle toggle {get { return s_Current.m_Toggle; } } private GUIStyle m_Toggle; internal static GUIStyle toggleMixed { get { return s_Current.m_ToggleMixed; } } private GUIStyle m_ToggleMixed; // Style used for headings for EditorGUI::ref::Foldout. public static GUIStyle foldout { get { return s_Current.m_Foldout; } } private GUIStyle m_Foldout; internal static GUIStyle titlebarFoldout { get { return s_Current.m_TitlebarFoldout; } } private GUIStyle m_TitlebarFoldout; // Style used for headings for EditorGUI::ref::Foldout. public static GUIStyle foldoutPreDrop { get { return s_Current.m_FoldoutPreDrop; } } private GUIStyle m_FoldoutPreDrop; public static GUIStyle foldoutHeader { get { return s_Current.m_FoldoutHeader;} } GUIStyle m_FoldoutHeader; public static GUIStyle foldoutHeaderIcon { get { return s_Current.m_FoldoutHeaderIcon; } } GUIStyle m_FoldoutHeaderIcon; internal static GUIStyle optionsButtonStyle { get { return s_Current.m_OptionsButtonStyle; } } GUIStyle m_OptionsButtonStyle; // Style used for headings for EditorGUILayout::ref::BeginToggleGroup. public static GUIStyle toggleGroup { get { return s_Current.m_ToggleGroup; } } private GUIStyle m_ToggleGroup; internal static GUIStyle textFieldDropDown { get { return s_Current.m_TextFieldDropDown; } } private GUIStyle m_TextFieldDropDown; internal static GUIStyle textFieldDropDownText { get { return s_Current.m_TextFieldDropDownText; } } private GUIStyle m_TextFieldDropDownText; internal static GUIStyle overrideMargin { get { return s_Current.m_OverrideMargin; } } private GUIStyle m_OverrideMargin; // Standard font. public static Font standardFont => EditorResources.GetFont(FontDef.Style.Normal); // Bold font. public static Font boldFont => EditorResources.GetFont(FontDef.Style.Bold); // Mini font. public static Font miniFont => EditorResources.GetFont(FontDef.Style.Small); // Mini Bold font. public static Font miniBoldFont => EditorResources.GetFont(FontDef.Style.Bold); // Toolbar background from top of windows. public static GUIStyle toolbar { get { return s_Current.m_Toolbar; } } private GUIStyle m_Toolbar; internal static GUIStyle contentToolbar { get { return s_Current.m_ContentToolbar; } } private GUIStyle m_ContentToolbar; // Style for Button and Toggles in toolbars. public static GUIStyle toolbarButton { get { return s_Current.m_ToolbarButton; } } private GUIStyle m_ToolbarButton; internal static GUIStyle toolbarButtonLeft { get { return s_Current.m_ToolbarButtonLeft; } } private GUIStyle m_ToolbarButtonLeft; internal static GUIStyle toolbarButtonRight { get { return s_Current.m_ToolbarButtonRight; } } private GUIStyle m_ToolbarButtonRight; // Toolbar Popup public static GUIStyle toolbarPopup { get { return s_Current.m_ToolbarPopup; } } private GUIStyle m_ToolbarPopup; internal static GUIStyle toolbarPopupLeft { get { return s_Current.m_ToolbarPopupLeft; } } private GUIStyle m_ToolbarPopupLeft; internal static GUIStyle toolbarPopupRight { get { return s_Current.m_ToolbarPopupRight; } } private GUIStyle m_ToolbarPopupRight; internal static GUIStyle toolbarDropDownLeft { get { return s_Current.m_ToolbarDropDownLeft; } } private GUIStyle m_ToolbarDropDownLeft; public static GUIStyle toolbarDropDown { get { return s_Current.m_ToolbarDropDown; } } private GUIStyle m_ToolbarDropDown; // Toolbar Dropdown Right internal static GUIStyle toolbarDropDownRight { get { return s_Current.m_ToolbarDropDownRight; } } private GUIStyle m_ToolbarDropDownRight; // Toolbar Dropdown Toggle internal static GUIStyle toolbarDropDownToggle { get { return s_Current.m_ToolbarDropDownToggle; } } private GUIStyle m_ToolbarDropDownToggle; // Toolbar Dropdown Toggle Button internal static GUIStyle toolbarDropDownToggleButton { get { return s_Current.m_ToolbarDropDownToggleButton; } } private GUIStyle m_ToolbarDropDownToggleButton; // Toolbar Dropdown Toggle Right internal static GUIStyle toolbarDropDownToggleRight { get { return s_Current.m_ToolbarDropDownToggleRight; } } private GUIStyle m_ToolbarDropDownToggleRight; // Toolbar Dropdown internal static GUIStyle toolbarCreateAddNewDropDown { get { return s_Current.m_ToolbarCreateAddNewDropDown; } } private GUIStyle m_ToolbarCreateAddNewDropDown; // Toolbar text field public static GUIStyle toolbarTextField { get { return s_Current.m_ToolbarTextField; } } private GUIStyle m_ToolbarTextField; internal static GUIStyle toolbarLabel { get { return s_Current.m_ToolbarLabel; } } private GUIStyle m_ToolbarLabel; public static GUIStyle inspectorDefaultMargins { get { return s_Current.m_InspectorDefaultMargins; } } private GUIStyle m_InspectorDefaultMargins; public static GUIStyle inspectorFullWidthMargins { get { return s_Current.m_InspectorFullWidthMargins; } } private GUIStyle m_InspectorFullWidthMargins; internal static GUIStyle defaultContentMargins { get { return s_Current.m_DefaultContentMargins; } } private GUIStyle m_DefaultContentMargins; internal static GUIStyle frameBox => s_Current.m_FrameBox; private GUIStyle m_FrameBox; public static GUIStyle helpBox { get { return s_Current.m_HelpBox; } } private GUIStyle m_HelpBox; internal static GUIStyle helpBoxLabel { get { s_Current.m_HelpBoxLabel.Assign(s_Current.m_HelpBox); s_Current.m_HelpBoxLabel.name = "HelpBoxLabel"; s_Current.m_HelpBoxLabel.normal.background = null; s_Current.m_HelpBoxLabel.hover.background = null; s_Current.m_HelpBoxLabel.active.background = null; s_Current.m_HelpBoxLabel.focused.background = null; s_Current.m_HelpBoxLabel.onNormal.background = null; s_Current.m_HelpBoxLabel.onHover.background = null; s_Current.m_HelpBoxLabel.onActive.background = null; s_Current.m_HelpBoxLabel.onFocused.background = null; return s_Current.m_HelpBoxLabel; } } private GUIStyle m_HelpBoxLabel; public static GUIStyle toolbarSearchField { get { return s_Current.m_ToolbarSearchField; } } private GUIStyle m_ToolbarSearchField; internal static GUIStyle toolbarSearchFieldPopup { get { return s_Current.m_ToolbarSearchFieldPopup; } } private GUIStyle m_ToolbarSearchFieldPopup; internal static GUIStyle toolbarSearchFieldWithJumpSynced { get { return s_Current.m_ToolbarSearchFieldWithJumpSynced; } } private GUIStyle m_ToolbarSearchFieldWithJumpSynced; internal static GUIStyle toolbarSearchFieldWithJumpPopupSynced { get { return s_Current.m_ToolbarSearchFieldWithJumpPopupSynced; } } private GUIStyle m_ToolbarSearchFieldWithJumpPopupSynced; internal static GUIStyle toolbarSearchFieldWithJump { get { return s_Current.m_ToolbarSearchFieldWithJump; } } private GUIStyle m_ToolbarSearchFieldWithJump; internal static GUIStyle toolbarSearchFieldWithJumpPopup { get { return s_Current.m_ToolbarSearchFieldWithJumpPopup; } } private GUIStyle m_ToolbarSearchFieldWithJumpPopup; internal static GUIStyle toolbarSearchFieldJumpButton { get { return s_Current.m_ToolbarSearchFieldJumpButton; } } private GUIStyle m_ToolbarSearchFieldJumpButton; internal static GUIStyle toolbarSearchFieldCancelButton { get { return s_Current.m_ToolbarSearchFieldCancelButton; } } private GUIStyle m_ToolbarSearchFieldCancelButton; internal static GUIStyle toolbarSearchFieldCancelButtonEmpty { get { return s_Current.m_ToolbarSearchFieldCancelButtonEmpty; } } private GUIStyle m_ToolbarSearchFieldCancelButtonEmpty; internal static GUIStyle toolbarSearchFieldCancelButtonWithJump { get { return s_Current.m_ToolbarSearchFieldCancelButtonWithJump; } } private GUIStyle m_ToolbarSearchFieldCancelButtonWithJump; internal static GUIStyle toolbarSearchFieldCancelButtonWithJumpEmpty { get { return s_Current.m_ToolbarSearchFieldCancelButtonWithJumpEmpty; } } private GUIStyle m_ToolbarSearchFieldCancelButtonWithJumpEmpty; internal static GUIStyle colorPickerBox { get { return s_Current.m_ColorPickerBox; } } private GUIStyle m_ColorPickerBox; internal static GUIStyle viewBackground { get { return s_Current.m_ViewBg; } } private GUIStyle m_ViewBg; internal static GUIStyle inspectorBig { get { return s_Current.m_InspectorBig; } } private GUIStyle m_InspectorBig; internal static GUIStyle inspectorTitlebar { get { return s_Current.m_InspectorTitlebar; } } private GUIStyle m_InspectorTitlebar; internal static GUIStyle inspectorTitlebarFlat { get { return s_Current.m_InspectorTitlebarFlat; } } private GUIStyle m_InspectorTitlebarFlat; internal static GUIStyle inspectorTitlebarText { get { return s_Current.m_InspectorTitlebarText; } } private GUIStyle m_InspectorTitlebarText; internal static GUIStyle foldoutSelected { get { return s_Current.m_FoldoutSelected; } } private GUIStyle m_FoldoutSelected; // Style used for a standalone icon button public static GUIStyle iconButton { get { return s_Current.m_IconButton; } } private GUIStyle m_IconButton; // Style for tooltips internal static GUIStyle tooltip { get { return s_Current.m_Tooltip; } } private GUIStyle m_Tooltip; // Style for notification text. internal static GUIStyle notificationText { get { return s_Current.m_NotificationText; } } private GUIStyle m_NotificationText; // Style for notification background area. internal static GUIStyle notificationBackground { get { return s_Current.m_NotificationBackground; } } private GUIStyle m_NotificationBackground; internal static GUIStyle assetLabel { get { return s_Current.m_AssetLabel; } } private GUIStyle m_AssetLabel; internal static GUIStyle assetLabelPartial { get { return s_Current.m_AssetLabelPartial; } } private GUIStyle m_AssetLabelPartial; internal static GUIStyle assetLabelIcon { get { return s_Current.m_AssetLabelIcon; } } private GUIStyle m_AssetLabelIcon; internal static GUIStyle searchField { get { return s_Current.m_SearchField; } } private GUIStyle m_SearchField; internal static GUIStyle searchFieldCancelButton { get { return s_Current.m_SearchFieldCancelButton; } } private GUIStyle m_SearchFieldCancelButton; internal static GUIStyle searchFieldCancelButtonEmpty { get { return s_Current.m_SearchFieldCancelButtonEmpty; } } private GUIStyle m_SearchFieldCancelButtonEmpty; public static GUIStyle selectionRect { get { return s_Current.m_SelectionRect; } } private GUIStyle m_SelectionRect; internal static GUIStyle toolbarSlider { get { return s_Current.m_ToolbarSlider; } } private GUIStyle m_ToolbarSlider; internal static GUIStyle minMaxHorizontalSliderThumb { get { return s_Current.m_MinMaxHorizontalSliderThumb; } } private GUIStyle m_MinMaxHorizontalSliderThumb; internal static GUIStyle dropDownList { get { return s_Current.m_DropDownList; } } private GUIStyle m_DropDownList; internal static GUIStyle dropDownToggleButton { get { return s_Current.m_DropDownToggleButton; } } private GUIStyle m_DropDownToggleButton; internal static GUIStyle minMaxStateDropdown { get { return s_Current.m_MinMaxStateDropdown; } } private GUIStyle m_MinMaxStateDropdown; internal static GUIStyle progressBarBack { get { return s_Current.m_ProgressBarBack; } } internal static GUIStyle progressBarBar { get { return s_Current.m_ProgressBarBar; } } internal static GUIStyle progressBarText { get { return s_Current.m_ProgressBarText; } } private GUIStyle m_ProgressBarBar, m_ProgressBarText, m_ProgressBarBack; internal static GUIStyle scrollViewAlt { get { return s_Current.m_ScrollViewAlt; } } private GUIStyle m_ScrollViewAlt; internal static Vector2 knobSize {get {return s_Current.m_KnobSize; }} internal static Vector2 miniKnobSize {get {return s_Current.m_MiniKnobSize; }} private Vector2 m_KnobSize = new Vector2(40, 40); private Vector2 m_MiniKnobSize = new Vector2(29, 29); // the editor styles currently in use internal static EditorStyles s_Current; // the list of editor styles to use private static EditorStyles[] s_CachedStyles = { null, null }; [ExcludeFromDocs] public static GUIStyle FromUSS(string ussStyleRuleName, string ussInPlaceStyleOverride = null) { return GUIStyleExtensions.FromUSS(ussStyleRuleName, ussInPlaceStyleOverride); } [ExcludeFromDocs] public static GUIStyle FromUSS(GUIStyle baseStyle, string ussStyleRuleName, string ussInPlaceStyleOverride = null) { return GUIStyleExtensions.FromUSS(baseStyle, ussStyleRuleName, ussInPlaceStyleOverride); } [ExcludeFromDocs] public static GUIStyle ApplyUSS(GUIStyle style, string ussStyleRuleName, string ussInPlaceStyleOverride = null) { return GUIStyleExtensions.ApplyUSS(style, ussStyleRuleName, ussInPlaceStyleOverride); } internal static void UpdateSkinCache() { UpdateSkinCache(EditorGUIUtility.skinIndex); } internal static void UpdateSkinCache(int skinIndex) { // Don't cache the Game GUISkin styles if (GUIUtility.s_SkinMode == 0) return; if (s_CachedStyles[skinIndex] == null) { EditorResources.RefreshSkin(); s_CachedStyles[skinIndex] = new EditorStyles(); s_CachedStyles[skinIndex].InitSharedStyles(); } s_Current = s_CachedStyles[skinIndex]; EditorGUIUtility.s_FontIsBold = -1; EditorGUIUtility.SetBoldDefaultFont(false); } private void InitSharedStyles() { m_ColorPickerBox = GetStyle("ColorPickerBox"); m_ViewBg = GetStyle("TabWindowBackground"); m_InspectorBig = GetStyle("In BigTitle"); m_MiniLabel = GetStyle("MiniLabel"); m_LargeLabel = GetStyle("LargeLabel"); m_BoldLabel = GetStyle("BoldLabel"); m_MiniBoldLabel = GetStyle("MiniBoldLabel"); m_WordWrappedLabel = GetStyle("WordWrappedLabel"); m_WordWrappedMiniLabel = GetStyle("WordWrappedMiniLabel"); m_WhiteLabel = GetStyle("WhiteLabel"); m_WhiteMiniLabel = GetStyle("WhiteMiniLabel"); m_WhiteLargeLabel = GetStyle("WhiteLargeLabel"); m_WhiteBoldLabel = GetStyle("WhiteBoldLabel"); m_MiniTextField = GetStyle("MiniTextField"); m_RadioButton = GetStyle("Radio"); m_MiniButton = GetStyle("miniButton"); m_MiniButtonLeft = GetStyle("miniButtonLeft"); m_MiniButtonMid = GetStyle("miniButtonMid"); m_MiniButtonRight = GetStyle("miniButtonRight"); m_MiniPullDown = GetStyle("MiniPullDown"); m_Toolbar = GetStyle("toolbar"); m_ContentToolbar = GetStyle("contentToolbar"); m_ToolbarButton = GetStyle("toolbarbutton"); m_ToolbarButtonLeft = GetStyle("toolbarbuttonLeft"); m_ToolbarButtonRight = GetStyle("toolbarbuttonRight"); m_ToolbarPopup = GetStyle("toolbarPopup"); m_ToolbarPopupLeft = GetStyle("toolbarPopupLeft"); m_ToolbarPopupRight = GetStyle("toolbarPopupRight"); m_ToolbarDropDown = GetStyle("toolbarDropDown"); m_ToolbarDropDownLeft = GetStyle("toolbarDropDownLeft"); m_ToolbarDropDownRight = GetStyle("toolbarDropDownRight"); m_ToolbarDropDownToggle = GetStyle("toolbarDropDownToggle"); m_ToolbarDropDownToggleButton = GetStyle("ToolbarDropDownToggleButton"); m_ToolbarDropDownToggleRight = GetStyle("toolbarDropDownToggleRight"); m_ToolbarCreateAddNewDropDown = GetStyle("ToolbarCreateAddNewDropDown"); m_ToolbarTextField = GetStyle("toolbarTextField"); m_ToolbarLabel = GetStyle("ToolbarLabel"); m_ToolbarSearchField = GetStyle("ToolbarSearchTextField"); m_ToolbarSearchFieldPopup = GetStyle("ToolbarSearchTextFieldPopup"); m_ToolbarSearchFieldWithJump = GetStyle("ToolbarSearchTextFieldWithJump"); m_ToolbarSearchFieldWithJumpPopup = GetStyle("ToolbarSearchTextFieldWithJumpPopup"); m_ToolbarSearchFieldJumpButton = GetStyle("ToolbarSearchTextFieldJumpButton"); m_ToolbarSearchFieldCancelButton = GetStyle("ToolbarSearchCancelButton"); m_ToolbarSearchFieldCancelButtonEmpty = GetStyle("ToolbarSearchCancelButtonEmpty"); m_ToolbarSearchFieldCancelButtonWithJump = GetStyle("ToolbarSearchCancelButtonWithJump"); m_ToolbarSearchFieldCancelButtonWithJumpEmpty = GetStyle("ToolbarSearchCancelButtonWithJumpEmpty"); m_ToolbarSearchFieldWithJumpSynced = GetStyle("ToolbarSearchTextFieldWithJumpSynced"); m_ToolbarSearchFieldWithJumpPopupSynced = GetStyle("ToolbarSearchTextFieldWithJumpPopupSynced"); m_SearchField = GetStyle("SearchTextField"); m_SearchFieldCancelButton = GetStyle("SearchCancelButton"); m_SearchFieldCancelButtonEmpty = GetStyle("SearchCancelButtonEmpty"); m_HelpBox = GetStyle("HelpBox"); m_FrameBox = GetStyle("FrameBox"); m_AssetLabel = GetStyle("AssetLabel"); m_AssetLabelPartial = GetStyle("AssetLabel Partial"); m_AssetLabelIcon = GetStyle("AssetLabel Icon"); m_SelectionRect = GetStyle("selectionRect"); m_ToolbarSlider = GetStyle("ToolbarSlider"); m_MinMaxHorizontalSliderThumb = GetStyle("MinMaxHorizontalSliderThumb"); m_DropDownList = GetStyle("DropDownButton"); m_DropDownToggleButton = GetStyle("DropDownToggleButton"); m_MinMaxStateDropdown = GetStyle("IN MinMaxStateDropdown"); m_ProgressBarBack = GetStyle("ProgressBarBack"); m_ProgressBarBar = GetStyle("ProgressBarBar"); m_ProgressBarText = GetStyle("ProgressBarText"); m_FoldoutPreDrop = GetStyle("FoldoutPreDrop"); m_FoldoutHeader = GetStyle("FoldoutHeader"); m_FoldoutHeaderIcon = GetStyle("FoldoutHeaderIcon"); m_OptionsButtonStyle = GetStyle("PaneOptions"); m_InspectorTitlebar = GetStyle("IN Title"); m_InspectorTitlebarFlat = GetStyle("IN Title Flat"); m_InspectorTitlebarText = GetStyle("IN TitleText"); m_ToggleGroup = GetStyle("BoldToggle"); m_Tooltip = GetStyle("Tooltip"); m_NotificationText = GetStyle("NotificationText"); m_NotificationBackground = GetStyle("NotificationBackground"); m_ScrollViewAlt = GetStyle("ScrollViewAlt"); // Former LookLikeControls styles m_Popup = m_LayerMaskField = GetStyle("MiniPopup"); m_TextField = m_NumberField = GetStyle("TextField"); m_BoldTextField = GetStyle("BoldTextFIeld"); m_Label = GetStyle("ControlLabel"); m_ObjectField = GetStyle("ObjectField"); m_ObjectFieldThumb = GetStyle("ObjectFieldThumb"); m_ObjectFieldButton = GetStyle("ObjectFieldButton"); m_ObjectFieldMiniThumb = GetStyle("ObjectFieldMiniThumb"); m_Toggle = GetStyle("Toggle"); m_ToggleMixed = GetStyle("ToggleMixed"); m_ColorField = GetStyle("ColorField"); m_Foldout = GetStyle("Foldout"); m_TitlebarFoldout = GetStyle("Titlebar Foldout"); m_FoldoutSelected = GUIStyle.none; m_IconButton = GetStyle("IconButton"); m_TextFieldDropDown = GetStyle("TextFieldDropDown"); m_TextFieldDropDownText = GetStyle("TextFieldDropDownText"); m_OverrideMargin = GetStyle("OverrideMargin"); m_LinkLabel = GetStyle("LinkLabel"); // Match selection color which works nicely for both light and dark skins m_TextArea = new GUIStyle(m_TextField) {wordWrap = true}; m_InspectorDefaultMargins = new GUIStyle { padding = new RectOffset(kInspectorPaddingLeft, kInspectorPaddingRight, kInspectorPaddingTop, 0) }; // For the full width margins, use padding from right side in both sides, // though adjust for overdraw by adding one in left side to get even margins. m_InspectorFullWidthMargins = new GUIStyle { padding = new RectOffset(kInspectorPaddingRight + 1, kInspectorPaddingRight, 0, 0) }; m_DefaultContentMargins = new GUIStyle { padding = new RectOffset(4, 4, 4, 4) }; // Derive centered grey mini label from base minilabel m_CenteredGreyMiniLabel = new GUIStyle(m_MiniLabel) { alignment = TextAnchor.MiddleCenter, normal = {textColor = Color.grey}, hover = { textColor = Color.grey }, active = { textColor = Color.grey}, focused = { textColor = Color.grey } }; m_HelpBoxLabel = new GUIStyle(m_HelpBox) { name = "HelpBoxLabel" }; } internal GUIStyle GetStyle(string styleName) { GUIStyle s = GUI.skin.FindStyle(styleName) ?? EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).FindStyle(styleName); if (s == null) { Debug.LogError("Missing built-in guistyle " + styleName); s = GUISkin.error; } return s; } } }
UnityCsReference/Editor/Mono/GUI/EditorStyles.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/EditorStyles.cs", "repo_id": "UnityCsReference", "token_count": 11752 }
298
// 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; // NOTE: // This file should only contain internal functions of the EditorGUILayout class namespace UnityEditor { public sealed partial class EditorGUILayout { internal static bool IconButton(int id, GUIContent content, GUIStyle style, params GUILayoutOption[] options) { s_LastRect = GUILayoutUtility.GetRect(content, style, options); return EditorGUI.IconButton(id, s_LastRect, content, style); } internal static void GameViewSizePopup(GameViewSizeGroupType groupType, int selectedIndex, IGameViewSizeMenuUser gameView, GUIStyle style, params GUILayoutOption[] options) { s_LastRect = GetControlRect(false, EditorGUI.kSingleLineHeight, style, options); EditorGUI.GameViewSizePopup(s_LastRect, groupType, selectedIndex, gameView, style); } internal static void SortingLayerField(GUIContent label, SerializedProperty layerID, GUIStyle style, GUIStyle labelStyle) { s_LastRect = EditorGUILayout.GetControlRect(false, EditorGUI.kSingleLineHeight, style); EditorGUI.SortingLayerField(s_LastRect, label, layerID, style, labelStyle); } } }
UnityCsReference/Editor/Mono/GUI/InternalEditorGUILayout.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/InternalEditorGUILayout.cs", "repo_id": "UnityCsReference", "token_count": 511 }
299