Update some code to use C#9 features

This commit is contained in:
ghorsington committed 2021-01-05 22:54:45 +02:00
1 parent 965d9ae1c8
commit 88e3dfb7e7
26 files changed
+88 -136

No files matched your search

+7 -7
View File
@@ -23,13 +23,13 @@ namespace BepInEx.Bootstrap
/// <summary>
/// List of all <see cref="PluginInfo"/> instances loaded via the chainloader.
/// </summary>
public Dictionary<string, PluginInfo> Plugins { get; } = new Dictionary<string, PluginInfo>();
public Dictionary<string, PluginInfo> Plugins { get; } = new();
/// <summary>
/// Collection of error chainloader messages that occured during plugin loading.
/// Contains information about what certain plugins were not loaded.
/// </summary>
public List<string> DependencyErrors { get; } = new List<string>();
public List<string> DependencyErrors { get; } = new();
public virtual void Initialize(string gameExePath = null)
{
@@ -128,13 +128,13 @@ namespace BepInEx.Bootstrap
dependencyDict.Remove(pluginInfo.Metadata.GUID);
var incompatiblePlugins = pluginInfo.Incompatibilities.Select(x => x.IncompatibilityGUID).Where(x => pluginsByGuid.ContainsKey(x)).ToArray();
string message = $@"Could not load [{pluginInfo}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
var message = $@"Could not load [{pluginInfo}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
DependencyErrors.Add(message);
Logger.LogError(message);
}
else if (PluginTargetsWrongBepin(pluginInfo))
{
string message = $@"Plugin [{pluginInfo}] targets a wrong version of BepInEx ({pluginInfo.TargettedBepInExVersion}) and might not work until you update";
var message = $@"Plugin [{pluginInfo}] targets a wrong version of BepInEx ({pluginInfo.TargettedBepInExVersion}) and might not work until you update";
DependencyErrors.Add(message);
Logger.LogWarning(message);
}
@@ -169,7 +169,7 @@ namespace BepInEx.Bootstrap
var missingDependencies = new List<BepInDependency>();
foreach (var dependency in plugin.Dependencies)
{
bool IsHardDependency(BepInDependency dep)
static bool IsHardDependency(BepInDependency dep)
=> (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0;
// If the dependency wasn't already processed, it's missing altogether
@@ -202,7 +202,7 @@ namespace BepInEx.Bootstrap
if (missingDependencies.Count != 0)
{
string message = $@"Could not load [{plugin}] because it has missing dependencies: {
var message = $@"Could not load [{plugin}] because it has missing dependencies: {
string.Join(", ", missingDependencies.Select(s => s.VersionRange == null ? s.DependencyGUID : $"{s.DependencyGUID} ({s.VersionRange})").ToArray())
}";
DependencyErrors.Add(message);
@@ -256,7 +256,7 @@ namespace BepInEx.Bootstrap
#endregion
private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._\-]+$");
private static Regex allowedGuidRegex { get; } = new(@"^[a-zA-Z0-9\._\-]+$");
/// <summary>
/// Analyzes the given type definition and attempts to convert it to a valid <see cref="PluginInfo"/>
+2 -9
View File
@@ -39,7 +39,6 @@ namespace BepInEx.Bootstrap
/// </summary>
public List<T> CacheItems { get; set; }
/// <summary>
/// Timestamp of the assembly. Used to check the age of the cache.
/// </summary>
@@ -61,7 +60,7 @@ namespace BepInEx.Bootstrap
/// </summary>
public static readonly ReaderParameters ReaderParameters;
public static HashSet<string> SearchDirectories = new HashSet<string>();
public static HashSet<string> SearchDirectories = new();
static TypeLoader()
{
@@ -81,13 +80,7 @@ namespace BepInEx.Bootstrap
Utility.TryResolveDllAssembly(name, Paths.ManagedPath, ReaderParameters, out assembly))
return assembly;
foreach (var dir in SearchDirectories)
{
if (Utility.TryResolveDllAssembly(name, dir, ReaderParameters, out assembly))
return assembly;
}
return AssemblyResolve?.Invoke(sender, reference);
return SearchDirectories.Any(dir => Utility.TryResolveDllAssembly(name, dir, ReaderParameters, out assembly)) ? assembly : AssemblyResolve?.Invoke(sender, reference);
}
/// <summary>
@@ -38,6 +38,6 @@ namespace BepInEx.Configuration
/// <summary>
/// An empty description.
/// </summary>
public static ConfigDescription Empty { get; } = new ConfigDescription("");
public static ConfigDescription Empty { get; } = new("");
}
}
+3 -3
View File
@@ -21,9 +21,9 @@ namespace BepInEx.Configuration
/// <summary>
/// All config entries inside
/// </summary>
protected Dictionary<ConfigDefinition, ConfigEntryBase> Entries { get; } = new Dictionary<ConfigDefinition, ConfigEntryBase>();
protected Dictionary<ConfigDefinition, ConfigEntryBase> Entries { get; } = new();
private Dictionary<ConfigDefinition, string> OrphanedEntries { get; } = new Dictionary<ConfigDefinition, string>();
private Dictionary<ConfigDefinition, string> OrphanedEntries { get; } = new();
/// <summary>
/// Create a list with all config entries inside of this config file.
@@ -92,7 +92,7 @@ namespace BepInEx.Configuration
#region Save/Load
private readonly object _ioLock = new object();
private readonly object _ioLock = new();
/// <summary>
/// Reloads the config from disk. Unsaved changes are lost.
+15 -15
View File
@@ -16,7 +16,7 @@ namespace BepInEx.Configuration
// Don't put anything from UnityEngine here or it will break preloader, use LazyTomlConverterLoader instead
private static Dictionary<Type, TypeConverter> TypeConverters { get; } = new Dictionary<Type, TypeConverter>
{
[typeof(string)] = new TypeConverter
[typeof(string)] = new()
{
ConvertToString = (obj, type) => Escape((string)obj),
ConvertToObject = (str, type) =>
@@ -27,12 +27,12 @@ namespace BepInEx.Configuration
return Unescape(str);
},
},
[typeof(bool)] = new TypeConverter
[typeof(bool)] = new()
{
ConvertToString = (obj, type) => obj.ToString().ToLowerInvariant(),
ConvertToObject = (str, type) => bool.Parse(str),
},
[typeof(byte)] = new TypeConverter
[typeof(byte)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => byte.Parse(str),
@@ -40,42 +40,42 @@ namespace BepInEx.Configuration
//integral types
[typeof(sbyte)] = new TypeConverter
[typeof(sbyte)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => sbyte.Parse(str),
},
[typeof(byte)] = new TypeConverter
[typeof(byte)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => byte.Parse(str),
},
[typeof(short)] = new TypeConverter
[typeof(short)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => short.Parse(str),
},
[typeof(ushort)] = new TypeConverter
[typeof(ushort)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => ushort.Parse(str),
},
[typeof(int)] = new TypeConverter
[typeof(int)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => int.Parse(str),
},
[typeof(uint)] = new TypeConverter
[typeof(uint)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => uint.Parse(str),
},
[typeof(long)] = new TypeConverter
[typeof(long)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => long.Parse(str),
},
[typeof(ulong)] = new TypeConverter
[typeof(ulong)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => ulong.Parse(str),
@@ -83,17 +83,17 @@ namespace BepInEx.Configuration
//floating point types
[typeof(float)] = new TypeConverter
[typeof(float)] = new()
{
ConvertToString = (obj, type) => ((float)obj).ToString(NumberFormatInfo.InvariantInfo),
ConvertToObject = (str, type) => float.Parse(str, NumberFormatInfo.InvariantInfo),
},
[typeof(double)] = new TypeConverter
[typeof(double)] = new()
{
ConvertToString = (obj, type) => ((double)obj).ToString(NumberFormatInfo.InvariantInfo),
ConvertToObject = (str, type) => double.Parse(str, NumberFormatInfo.InvariantInfo),
},
[typeof(decimal)] = new TypeConverter
[typeof(decimal)] = new()
{
ConvertToString = (obj, type) => ((decimal)obj).ToString(NumberFormatInfo.InvariantInfo),
ConvertToObject = (str, type) => decimal.Parse(str, NumberFormatInfo.InvariantInfo),
@@ -101,7 +101,7 @@ namespace BepInEx.Configuration
//enums are special
[typeof(Enum)] = new TypeConverter
[typeof(Enum)] = new()
{
ConvertToString = (obj, type) => obj.ToString(),
ConvertToObject = (str, type) => Enum.Parse(type, str, true),
+1 -2
View File
@@ -32,8 +32,7 @@ namespace BepInEx.Unix
internal static class TtyHandler
{
private static readonly string[] ncursesLocations = new[]
{
private static readonly string[] ncursesLocations = {
"/usr/share/terminfo",
"/etc/terminfo",
"/usr/lib/terminfo",
+1 -1
View File
@@ -67,7 +67,7 @@ namespace BepInEx.Logging
InstantFlushing = !delayedFlushing;
}
public static HashSet<string> BlacklistedSources = new HashSet<string>();
public static HashSet<string> BlacklistedSources = new();
/// <inheritdoc />
public void LogEvent(object sender, LogEventArgs eventArgs)
+3 -3
View File
@@ -10,17 +10,17 @@ namespace BepInEx.Logging
/// <summary>
/// Logged data.
/// </summary>
public object Data { get; protected set; }
public object Data { get; }
/// <summary>
/// Log levels for the data.
/// </summary>
public LogLevel Level { get; protected set; }
public LogLevel Level { get; }
/// <summary>
/// Log source that emitted the log event.
/// </summary>
public ILogSource Source { get; protected set; }
public ILogSource Source { get; }
/// <summary>
/// Creates the log event args-
+9 -16
View File
@@ -81,23 +81,16 @@ namespace BepInEx.Logging
public static ConsoleColor GetConsoleColor(this LogLevel level)
{
level = GetHighestLevel(level);
switch (level)
return level switch
{
case LogLevel.Fatal:
return ConsoleColor.Red;
case LogLevel.Error:
return ConsoleColor.DarkRed;
case LogLevel.Warning:
return ConsoleColor.Yellow;
case LogLevel.Message:
return ConsoleColor.White;
case LogLevel.Info:
default:
return ConsoleColor.Gray;
case LogLevel.Debug:
return ConsoleColor.DarkGray;
}
LogLevel.Fatal => ConsoleColor.Red,
LogLevel.Error => ConsoleColor.DarkRed,
LogLevel.Warning => ConsoleColor.Yellow,
LogLevel.Message => ConsoleColor.White,
LogLevel.Info => ConsoleColor.DarkGray,
LogLevel.Debug => ConsoleColor.DarkGray,
_ => ConsoleColor.Gray
};
}
}
}
+2 -2
View File
@@ -74,7 +74,7 @@ namespace BepInEx.Logging
void ICollection<ILogSource>.Clear()
{
foreach (var item in base.ToArray())
foreach (var item in ToArray())
{
((ICollection<ILogSource>)this).Remove(item);
}
@@ -85,7 +85,7 @@ namespace BepInEx.Logging
if (item == null)
return false;
if (!base.Contains(item))
if (!Contains(item))
return false;
item.LogEvent -= InternalLogEvent;
+1 -2
View File
@@ -10,8 +10,7 @@ namespace BepInEx.Core.Logging
{
public void LogEvent(object sender, LogEventArgs eventArgs)
{
string log = $"[{eventArgs.Level,-7}:{((ILogSource)sender).SourceName,10}] {eventArgs.Data}\r\n";
var log = $"[{eventArgs.Level,-7}:{((ILogSource)sender).SourceName,10}] {eventArgs.Data}\r\n";
ConsoleManager.StandardOutStream?.Write(log);
}
+8 -22
View File
@@ -11,7 +11,7 @@ namespace BepInEx.Logging
/// <summary>
/// Whether Trace logs are currently being rerouted.
/// </summary>
public static bool IsListening { get; protected set; } = false;
public static bool IsListening { get; private set; }
private static TraceLogSource traceListener;
@@ -69,28 +69,14 @@ namespace BepInEx.Logging
/// <inheritdoc />
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
LogLevel level;
switch (eventType)
var level = eventType switch
{
case TraceEventType.Critical:
level = LogLevel.Fatal;
break;
case TraceEventType.Error:
level = LogLevel.Error;
break;
case TraceEventType.Warning:
level = LogLevel.Warning;
break;
case TraceEventType.Information:
level = LogLevel.Info;
break;
case TraceEventType.Verbose:
default:
level = LogLevel.Debug;
break;
}
TraceEventType.Critical => LogLevel.Fatal,
TraceEventType.Error => LogLevel.Error,
TraceEventType.Warning => LogLevel.Warning,
TraceEventType.Information => LogLevel.Info,
_ => LogLevel.Debug
};
LogSource.Log(level, $"{message}".Trim());
}
}
+7 -11
View File
@@ -129,14 +129,14 @@ namespace BepInEx
/// <exception cref="Exception">Thrown when a cyclic dependency occurs.</exception>
public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
{
List<TNode> sorted_list = new List<TNode>();
var sorted_list = new List<TNode>();
HashSet<TNode> visited = new HashSet<TNode>();
HashSet<TNode> sorted = new HashSet<TNode>();
var visited = new HashSet<TNode>();
var sorted = new HashSet<TNode>();
foreach (TNode input in nodes)
{
Stack<TNode> currentStack = new Stack<TNode>();
var currentStack = new Stack<TNode>();
if (!Visit(input, currentStack))
{
throw new Exception("Cyclic Dependency:\r\n" + currentStack.Select(x => $" - {x}") //append dashes
@@ -159,13 +159,9 @@ namespace BepInEx
else
{
visited.Add(node);
stack.Push(node);
foreach (var dep in dependencySelector(node))
if (!Visit(dep, stack))
return false;
if (dependencySelector(node).Any(dep => !Visit(dep, stack)))
return false;
sorted.Add(node);
sorted_list.Add(node);
@@ -194,7 +190,7 @@ namespace BepInEx
foreach (string subDirectory in potentialDirectories)
{
string[] potentialPaths = new[]
var potentialPaths = new[]
{
$"{assemblyName.Name}.dll",
$"{assemblyName.Name}.exe"
@@ -19,8 +19,8 @@ namespace BepInEx.IL2CPP.Allocator
{
int startIndex = line.IndexOf('-');
int endIndex = line.IndexOf(' ');
long startAddr = long.Parse(line.Substring(0, startIndex), NumberStyles.HexNumber);
long endAddr = long.Parse(line.Substring(startIndex + 1, endIndex - startIndex - 1), NumberStyles.HexNumber);
long startAddr = long.Parse(line[..startIndex], NumberStyles.HexNumber);
long endAddr = long.Parse(line[(startIndex+1)..endIndex], NumberStyles.HexNumber);
yield return (new IntPtr(startAddr), new IntPtr(endAddr));
}
}
@@ -32,7 +32,7 @@ namespace BepInEx.IL2CPP.Allocator
private static PageAllocator instance;
private readonly List<PageChunk> allocatedChunks = new List<PageChunk>();
private readonly List<PageChunk> allocatedChunks = new();
/// <summary>
/// Platform-specific instance of page allocator.
@@ -125,7 +125,7 @@ namespace BepInEx.IL2CPP.Allocator
var v when v.Is(Platform.Windows) => new WindowsPageAllocator(),
var v when v.Is(Platform.Linux) => new LinuxPageAllocator(),
var v when v.Is(Platform.MacOS) => new MacOsPageAllocator(),
_ => throw new NotImplementedException()
_ => throw new NotImplementedException()
};
}
@@ -90,7 +90,7 @@ namespace BepInEx.IL2CPP.Allocator
private static class Unix
{
public static readonly IntPtr MAP_FAILED = new IntPtr(-1);
public static readonly IntPtr MAP_FAILED = new(-1);
[DynDllImport("mmap")]
public static mmapDelegate mmap;
@@ -102,7 +102,7 @@ namespace BepInEx.IL2CPP.Allocator
[StructLayout(LayoutKind.Sequential)]
// ReSharper disable once InconsistentNaming
public struct MEMORY_BASIC_INFORMATION
public readonly struct MEMORY_BASIC_INFORMATION
{
public readonly IntPtr BaseAddress;
public readonly IntPtr AllocationBase;
+1 -1
View File
@@ -229,7 +229,7 @@ namespace BepInEx.IL2CPP
private sealed class CodeWriterImpl : CodeWriter
{
readonly List<byte> allBytes = new List<byte>();
readonly List<byte> allBytes = new();
public override void WriteByte(byte value) => allBytes.Add(value);
public byte[] ToArray() => allBytes.ToArray();
}
@@ -185,7 +185,7 @@ namespace BepInEx.IL2CPP.Hook
if (!Original.IsStatic)
unmanagedParams[0] = typeof(IntPtr);
unmanagedParams[unmanagedParams.Length - 1] = typeof(Il2CppMethodInfo*);
unmanagedParams[^1] = typeof(Il2CppMethodInfo*);
Array.Copy(managedParams.Select(ConvertManagedTypeToIL2CPPType).ToArray(), 0,
unmanagedParams, paramStartIndex, managedParams.Length);
+8 -20
View File
@@ -13,27 +13,15 @@ namespace BepInEx.IL2CPP.Logging
public void UnityLogCallback(string logLine, string exception, LogType type)
{
LogLevel level = LogLevel.Message;
switch (type)
var level = type switch
{
case LogType.Error:
level = LogLevel.Error;
break;
case LogType.Assert:
level = LogLevel.Debug;
break;
case LogType.Warning:
level = LogLevel.Warning;
break;
case LogType.Log:
level = LogLevel.Message;
break;
case LogType.Exception:
level = LogLevel.Error;
break;
}
LogType.Error => LogLevel.Error,
LogType.Assert => LogLevel.Debug,
LogType.Warning => LogLevel.Warning,
LogType.Log => LogLevel.Message,
LogType.Exception => LogLevel.Error,
_ => LogLevel.Message
};
LogEvent?.Invoke(this, new LogEventArgs(logLine, level, this));
}
+1 -1
View File
@@ -16,7 +16,7 @@ namespace BepInEx
{
if (d == null)
{
throw new ArgumentNullException("d");
throw new ArgumentNullException(nameof(d));
}
return GetFunctionPointerForDelegateInternal2(d, conv);
@@ -12,7 +12,7 @@ namespace BepInEx.Preloader.Core.Logging
/// <summary>
/// A list of all <see cref="LogEventArgs"/> objects that this listener has received.
/// </summary>
public static List<LogEventArgs> LogEvents { get; } = new List<LogEventArgs>();
public static List<LogEventArgs> LogEvents { get; } = new();
/// <inheritdoc />
public void LogEvent(object sender, LogEventArgs eventArgs)
@@ -29,7 +29,7 @@ namespace BepInEx.Preloader.Core
/// <summary>
/// A list of plugins that will be initialized and executed, in the order of the list.
/// </summary>
public List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>();
public List<PatcherPlugin> PatcherPlugins { get; } = new();
/// <summary>
@@ -42,13 +42,13 @@ namespace BepInEx.Preloader.Core
/// <para>The dictionary has the name of the file, without any directories. These are used by the dumping functionality, and as such, these are also required to be unique. They do not have to be exactly the same as the real filename, however they have to be mapped deterministically.</para>
/// <para>Order is not respected, as it will be sorted by dependencies.</para>
/// </summary>
public Dictionary<string, AssemblyDefinition> AssembliesToPatch { get; } = new Dictionary<string, AssemblyDefinition>();
public Dictionary<string, AssemblyDefinition> AssembliesToPatch { get; } = new();
/// <summary>
/// <para>Contains a dictionary of assemblies that have been loaded as part of executing this assembly patcher..</para>
/// <para>The key is the same key as used in <see cref="LoadedAssemblies"/>, while the value is the actual assembly itself.</para>
/// </summary>
public Dictionary<string, Assembly> LoadedAssemblies { get; } = new Dictionary<string, Assembly>();
public Dictionary<string, Assembly> LoadedAssemblies { get; } = new();
/// <summary>
/// The directory location as to where patched assemblies will be saved to and loaded from disk, for debugging purposes. Defaults to BepInEx/DumpedAssemblies
@@ -366,11 +366,9 @@ namespace BepInEx.Preloader.Core
loadedAssembly = Assembly.LoadFile(Path.Combine(DumpedAssembliesPath, filename));
else
{
using (var assemblyStream = new MemoryStream())
{
assembly.Write(assemblyStream);
loadedAssembly =Assembly.Load(assemblyStream.ToArray());
}
using var assemblyStream = new MemoryStream();
assembly.Write(assemblyStream);
loadedAssembly =Assembly.Load(assemblyStream.ToArray());
}
LoadedAssemblies.Add(filename, loadedAssembly);
@@ -15,7 +15,7 @@ namespace BepInEx.Preloader.RuntimeFixes
{
loggedTextWriter = new LoggedTextWriter { Parent = Console.Out };
Console.SetOut(loggedTextWriter);
HarmonyLib.Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix));
Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix));
}
[HarmonyPatch(typeof(Console), nameof(Console.SetOut))]
@@ -40,7 +40,7 @@ namespace BepInEx.Preloader.RuntimeFixes
instance.Patch(
typeof(Trace).GetMethod("DoTrace", BindingFlags.Static | BindingFlags.NonPublic),
prefix: new HarmonyMethod(typeof(TraceFix).GetMethod(nameof(DoTraceReplacement), BindingFlags.Static | BindingFlags.NonPublic)));
new HarmonyMethod(typeof(TraceFix).GetMethod(nameof(DoTraceReplacement), BindingFlags.Static | BindingFlags.NonPublic)));
}
@@ -7,9 +7,9 @@ namespace BepInEx.Preloader.RuntimeFixes
{
internal static class UnityPatches
{
private static HarmonyLib.Harmony HarmonyInstance { get; set; }
private static Harmony HarmonyInstance { get; set; }
public static Dictionary<string, string> AssemblyLocations { get; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
public static Dictionary<string, string> AssemblyLocations { get; } = new(StringComparer.InvariantCultureIgnoreCase);
public static void Apply()
{