Automatic code cleanup (no real changes)

- Use explicit type of var
- Use 'new()'
- Remove unnecessary usings
- Sort usings
- Apply formatting
This commit is contained in:
Sinai
2022-04-12 05:20:35 +10:00
parent 693f5818be
commit 7e0f98ef91
95 changed files with 732 additions and 1073 deletions

View File

@ -2,12 +2,9 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityExplorer.CSConsole.Lexers;
using UnityExplorer.UI;
using UnityExplorer.UI.Widgets.AutoComplete;
using UniverseLib;
using UniverseLib.UI;
using UniverseLib.UI.Models;
using UniverseLib.Utility;
@ -29,10 +26,23 @@ namespace UnityExplorer.CSConsole
private readonly HashSet<char> delimiters = new()
{
'{', '}', ',', ';', '<', '>', '(', ')', '[', ']', '=', '|', '&', '?'
'{',
'}',
',',
';',
'<',
'>',
'(',
')',
'[',
']',
'=',
'|',
'&',
'?'
};
private readonly List<Suggestion> suggestions = new List<Suggestion>();
private readonly List<Suggestion> suggestions = new();
public void CheckAutocompletes()
{
@ -83,7 +93,7 @@ namespace UnityExplorer.CSConsole
// Get manual namespace completions
foreach (var ns in ReflectionUtility.AllNamespaces)
foreach (string ns in ReflectionUtility.AllNamespaces)
{
if (ns.StartsWith(input))
{
@ -97,7 +107,7 @@ namespace UnityExplorer.CSConsole
// Get manual keyword completions
foreach (var kw in KeywordLexer.keywords)
foreach (string kw in KeywordLexer.keywords)
{
if (kw.StartsWith(input))// && kw.Length > input.Length)
{
@ -121,11 +131,11 @@ namespace UnityExplorer.CSConsole
}
private readonly Dictionary<string, string> namespaceHighlights = new Dictionary<string, string>();
private readonly Dictionary<string, string> namespaceHighlights = new();
private readonly Dictionary<string, string> keywordHighlights = new Dictionary<string, string>();
private readonly Dictionary<string, string> keywordHighlights = new();
private readonly StringBuilder highlightBuilder = new StringBuilder();
private readonly StringBuilder highlightBuilder = new();
private const string OPEN_HIGHLIGHT = "<color=cyan>";
private string GetHighlightString(string prefix, string completion)

View File

@ -1,4 +1,6 @@
using System;
using HarmonyLib;
using Mono.CSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
@ -8,18 +10,14 @@ using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UniverseLib.Input;
using UnityExplorer.CSConsole;
using UnityExplorer.UI;
using UnityExplorer.UI.Panels;
using UnityExplorer.UI.Widgets.AutoComplete;
using UniverseLib.UI;
using UniverseLib;
using UniverseLib.Input;
using UniverseLib.Runtime;
using UniverseLib.UI.Models;
using UniverseLib.Utility;
using HarmonyLib;
using UniverseLib.Runtime;
using Mono.CSharp;
namespace UnityExplorer.CSConsole
{
@ -99,11 +97,11 @@ namespace UnityExplorer.CSConsole
if (!Directory.Exists(ScriptsFolder))
Directory.CreateDirectory(ScriptsFolder);
var startupPath = Path.Combine(ScriptsFolder, "startup.cs");
string startupPath = Path.Combine(ScriptsFolder, "startup.cs");
if (File.Exists(startupPath))
{
ExplorerCore.Log($"Executing startup script from '{startupPath}'...");
var text = File.ReadAllText(startupPath);
string text = File.ReadAllText(startupPath);
Input.Text = text;
Evaluate();
}
@ -153,7 +151,7 @@ namespace UnityExplorer.CSConsole
if (Evaluator != null)
Evaluator.Dispose();
GenerateTextWriter();
Evaluator = new ScriptEvaluator(evaluatorStringWriter)
{
@ -161,7 +159,7 @@ namespace UnityExplorer.CSConsole
};
usingDirectives = new HashSet<string>();
foreach (var use in DefaultUsing)
foreach (string use in DefaultUsing)
AddUsing(use);
if (logSuccess)
@ -200,7 +198,7 @@ namespace UnityExplorer.CSConsole
{
// Compile the code. If it returned a CompiledMethod, it is REPL.
CompiledMethod repl = Evaluator.Compile(input);
if (repl != null)
{
// Valid REPL, we have a delegate to the evaluation.
@ -208,7 +206,7 @@ namespace UnityExplorer.CSConsole
{
object ret = null;
repl.Invoke(ref ret);
var result = ret?.ToString();
string result = ret?.ToString();
if (!string.IsNullOrEmpty(result))
ExplorerCore.Log($"Invoked REPL, result: {ret}");
else
@ -222,13 +220,13 @@ namespace UnityExplorer.CSConsole
else
{
// The compiled code was not REPL, so it was a using directive or it defined classes.
string output = Evaluator._textWriter.ToString();
var outputSplit = output.Split('\n');
string[] outputSplit = output.Split('\n');
if (outputSplit.Length >= 2)
output = outputSplit[outputSplit.Length - 2];
evaluatorOutput.Clear();
if (ScriptEvaluator._reportPrinter.ErrorsCount > 0)
throw new FormatException($"Unable to compile the code. Evaluator's last output was:\r\n{output}");
else if (!supressLog)
@ -286,7 +284,7 @@ namespace UnityExplorer.CSConsole
DoAutoIndent();
}
var inStringOrComment = HighlightVisibleInput();
bool inStringOrComment = HighlightVisibleInput();
if (!settingCaretCoroutine)
{
@ -359,12 +357,12 @@ namespace UnityExplorer.CSConsole
// If caret moved, ensure caret is visible in the viewport
if (caretMoved)
{
var charInfo = Input.TextGenerator.characters[LastCaretPosition];
var charTop = charInfo.cursorPos.y;
var charBot = charTop - CSCONSOLE_LINEHEIGHT;
UICharInfo charInfo = Input.TextGenerator.characters[LastCaretPosition];
float charTop = charInfo.cursorPos.y;
float charBot = charTop - CSCONSOLE_LINEHEIGHT;
var viewportMin = Input.Transform.rect.height - Input.Transform.anchoredPosition.y - (Input.Transform.rect.height * 0.5f);
var viewportMax = viewportMin - Panel.InputScroller.ViewportRect.rect.height;
float viewportMin = Input.Transform.rect.height - Input.Transform.anchoredPosition.y - (Input.Transform.rect.height * 0.5f);
float viewportMax = viewportMin - Panel.InputScroller.ViewportRect.rect.height;
float diff = 0f;
if (charTop > viewportMin)
@ -374,7 +372,7 @@ namespace UnityExplorer.CSConsole
if (Math.Abs(diff) > 1)
{
var rect = Input.Transform;
RectTransform rect = Input.Transform;
rect.anchoredPosition = new Vector2(rect.anchoredPosition.x, rect.anchoredPosition.y - diff);
}
}
@ -391,7 +389,7 @@ namespace UnityExplorer.CSConsole
{
try
{
foreach (var member in typeof(EventSystem).GetMembers(AccessTools.all))
foreach (MemberInfo member in typeof(EventSystem).GetMembers(AccessTools.all))
{
if (member.Name == "m_CurrentSelected")
{
@ -414,14 +412,14 @@ namespace UnityExplorer.CSConsole
static bool usingEventSystemDictionaryMembers;
static readonly AmbiguousMemberHandler<EventSystem, GameObject> m_CurrentSelected_Handler_Normal
static readonly AmbiguousMemberHandler<EventSystem, GameObject> m_CurrentSelected_Handler_Normal
= new(true, true, "m_CurrentSelected", "m_currentSelected");
static readonly AmbiguousMemberHandler<EventSystem, Dictionary<int, GameObject>> m_CurrentSelected_Handler_Dictionary
static readonly AmbiguousMemberHandler<EventSystem, Dictionary<int, GameObject>> m_CurrentSelected_Handler_Dictionary
= new(true, true, "m_CurrentSelected", "m_currentSelected");
static readonly AmbiguousMemberHandler<EventSystem, bool> m_SelectionGuard_Handler_Normal
static readonly AmbiguousMemberHandler<EventSystem, bool> m_SelectionGuard_Handler_Normal
= new(true, true, "m_SelectionGuard", "m_selectionGuard");
static readonly AmbiguousMemberHandler<EventSystem, Dictionary<int, bool>> m_SelectionGuard_Handler_Dictionary
static readonly AmbiguousMemberHandler<EventSystem, Dictionary<int, bool>> m_SelectionGuard_Handler_Dictionary
= new(true, true, "m_SelectionGuard", "m_selectionGuard");
static void SetCurrentSelectedGameObject(EventSystem instance, GameObject value)
@ -444,11 +442,11 @@ namespace UnityExplorer.CSConsole
private static IEnumerator SetCaretCoroutine(int caretPosition)
{
var color = Input.Component.selectionColor;
Color color = Input.Component.selectionColor;
color.a = 0f;
Input.Component.selectionColor = color;
try { SetCurrentSelectedGameObject(CursorUnlocker.CurrentEventSystem, null); }
try { SetCurrentSelectedGameObject(CursorUnlocker.CurrentEventSystem, null); }
catch (Exception ex) { ExplorerCore.Log($"Failed removing selected object: {ex}"); }
yield return null; // ~~~~~~~ YIELD FRAME ~~~~~~~~~
@ -456,7 +454,7 @@ namespace UnityExplorer.CSConsole
try { SetSelectionGuard(CursorUnlocker.CurrentEventSystem, false); }
catch (Exception ex) { ExplorerCore.Log($"Failed setting selection guard: {ex}"); }
try { SetCurrentSelectedGameObject(CursorUnlocker.CurrentEventSystem, Input.GameObject); }
try { SetCurrentSelectedGameObject(CursorUnlocker.CurrentEventSystem, Input.GameObject); }
catch (Exception ex) { ExplorerCore.Log($"Failed setting selected gameobject: {ex}"); }
yield return null; // ~~~~~~~ YIELD FRAME ~~~~~~~~~
@ -495,12 +493,12 @@ namespace UnityExplorer.CSConsole
// the top and bottom position of the viewport in relation to the text height
// they need the half-height adjustment to normalize against the 'line.topY' value.
var viewportMin = Input.Transform.rect.height - Input.Transform.anchoredPosition.y - (Input.Transform.rect.height * 0.5f);
var viewportMax = viewportMin - Panel.InputScroller.ViewportRect.rect.height;
float viewportMin = Input.Transform.rect.height - Input.Transform.anchoredPosition.y - (Input.Transform.rect.height * 0.5f);
float viewportMax = viewportMin - Panel.InputScroller.ViewportRect.rect.height;
for (int i = 0; i < Input.TextGenerator.lineCount; i++)
{
var line = Input.TextGenerator.lines[i];
UILineInfo line = Input.TextGenerator.lines[i];
// if not set the top line yet, and top of line is below the viewport top
if (topLine == -1 && line.topY <= viewportMin)
topLine = i;
@ -534,7 +532,7 @@ namespace UnityExplorer.CSConsole
realStartLine++;
char lastPrev = '\n';
var sb = new StringBuilder();
StringBuilder sb = new();
// append leading new lines for spacing (no point rendering line numbers we cant see)
for (int i = 0; i < topLine; i++)
@ -676,7 +674,7 @@ Doorstop example:
public static void SetupHelpInteraction()
{
var drop = Panel.HelpDropdown;
Dropdown drop = Panel.HelpDropdown;
helpDict.Add("Help", "");
helpDict.Add("Usings", HELP_USINGS);
@ -684,7 +682,7 @@ Doorstop example:
helpDict.Add("Classes", HELP_CLASSES);
helpDict.Add("Coroutines", HELP_COROUTINES);
foreach (var opt in helpDict)
foreach (KeyValuePair<string, string> opt in helpDict)
drop.options.Add(new Dropdown.OptionData(opt.Key));
}
@ -693,7 +691,7 @@ Doorstop example:
if (index == 0)
return;
var helpText = helpDict.ElementAt(index);
KeyValuePair<string, string> helpText = helpDict.ElementAt(index);
Input.Text = helpText.Value;

View File

@ -1,12 +1,7 @@
using Mono.CSharp;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.CSConsole.Lexers;
using UniverseLib;
using UniverseLib.Utility;
namespace UnityExplorer.CSConsole
@ -25,14 +20,14 @@ namespace UnityExplorer.CSConsole
#region Core and initialization
public const char WHITESPACE = ' ';
public readonly HashSet<char> IndentOpenChars = new HashSet<char> { '{', '(' };
public readonly HashSet<char> IndentCloseChars = new HashSet<char> { '}', ')' };
public readonly HashSet<char> IndentOpenChars = new() { '{', '(' };
public readonly HashSet<char> IndentCloseChars = new() { '}', ')' };
private readonly Lexer[] lexers;
private readonly HashSet<char> delimiters = new HashSet<char>();
private readonly HashSet<char> delimiters = new();
private readonly StringLexer stringLexer = new StringLexer();
private readonly CommentLexer commentLexer = new CommentLexer();
private readonly StringLexer stringLexer = new();
private readonly CommentLexer commentLexer = new();
public LexerBuilder()
{
@ -45,7 +40,7 @@ namespace UnityExplorer.CSConsole
new KeywordLexer(),
};
foreach (var matcher in lexers)
foreach (Lexer matcher in lexers)
{
foreach (char c in matcher.Delimiters)
{
@ -97,13 +92,13 @@ namespace UnityExplorer.CSConsole
currentStartIdx = startIdx;
currentEndIdx = endIdx;
var sb = new StringBuilder();
StringBuilder sb = new();
for (int i = 0; i < leadingLines; i++)
sb.Append('\n');
int lastUnhighlighted = startIdx;
foreach (var match in GetMatches())
foreach (MatchInfo match in GetMatches())
{
// append non-highlighted text between last match and this
for (int i = lastUnhighlighted; i < match.startIndex; i++)
@ -130,7 +125,7 @@ namespace UnityExplorer.CSConsole
}
// check caretIdx to determine inStringOrComment state
if (caretIdx >= match.startIndex && (caretIdx <= (matchEndIdx+1) || (caretIdx >= input.Length && matchEndIdx >= input.Length - 1)))
if (caretIdx >= match.startIndex && (caretIdx <= (matchEndIdx + 1) || (caretIdx >= input.Length && matchEndIdx >= input.Length - 1)))
caretInStringOrComment = match.isStringOrComment;
}
@ -158,7 +153,7 @@ namespace UnityExplorer.CSConsole
bool anyMatch = false;
int startIndex = CommittedIndex + 1;
foreach (var lexer in lexers)
foreach (Lexer lexer in lexers)
{
if (lexer.TryMatchCurrent(this))
{

View File

@ -1,6 +1,4 @@
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine;
namespace UnityExplorer.CSConsole.Lexers
{
@ -13,7 +11,7 @@ namespace UnityExplorer.CSConsole.Lexers
}
// forest green
protected override Color HighlightColor => new Color(0.34f, 0.65f, 0.29f, 1.0f);
protected override Color HighlightColor => new(0.34f, 0.65f, 0.29f, 1.0f);
public override bool TryMatchCurrent(LexerBuilder lexer)
{

View File

@ -7,9 +7,9 @@ namespace UnityExplorer.CSConsole.Lexers
public class KeywordLexer : Lexer
{
// system blue
protected override Color HighlightColor => new Color(0.33f, 0.61f, 0.83f, 1.0f);
protected override Color HighlightColor => new(0.33f, 0.61f, 0.83f, 1.0f);
public static readonly HashSet<string> keywords = new HashSet<string>
public static readonly HashSet<string> keywords = new()
{
// reserved keywords
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue",
@ -28,15 +28,15 @@ namespace UnityExplorer.CSConsole.Lexers
public override bool TryMatchCurrent(LexerBuilder lexer)
{
var prev = lexer.Previous;
var first = lexer.Current;
char prev = lexer.Previous;
char first = lexer.Current;
// check for keywords
if (lexer.IsDelimiter(prev, true) && char.IsLetter(first))
{
// can be a keyword...
var sb = new StringBuilder();
StringBuilder sb = new();
sb.Append(lexer.Current);
while (!lexer.EndOfInput && char.IsLetter(lexer.PeekNext()))
sb.Append(lexer.Current);

View File

@ -1,7 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UniverseLib;
using UniverseLib.Utility;
namespace UnityExplorer.CSConsole.Lexers

View File

@ -5,7 +5,7 @@ namespace UnityExplorer.CSConsole.Lexers
public class NumberLexer : Lexer
{
// Maroon
protected override Color HighlightColor => new Color(0.58f, 0.33f, 0.33f, 1.0f);
protected override Color HighlightColor => new(0.58f, 0.33f, 0.33f, 1.0f);
private bool IsNumeric(char c) => char.IsNumber(c) || c == '.';

View File

@ -8,7 +8,7 @@ namespace UnityExplorer.CSConsole.Lexers
public override IEnumerable<char> Delimiters => new[] { '"', '\'', };
// orange
protected override Color HighlightColor => new Color(0.79f, 0.52f, 0.32f, 1.0f);
protected override Color HighlightColor => new(0.79f, 0.52f, 0.32f, 1.0f);
public override bool TryMatchCurrent(LexerBuilder lexer)
{

View File

@ -1,6 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace UnityExplorer.CSConsole.Lexers
@ -8,14 +7,14 @@ namespace UnityExplorer.CSConsole.Lexers
public class SymbolLexer : Lexer
{
// silver
protected override Color HighlightColor => new Color(0.6f, 0.6f, 0.6f);
protected override Color HighlightColor => new(0.6f, 0.6f, 0.6f);
// all symbols are delimiters
public override IEnumerable<char> Delimiters => symbols.Where(it => it != '.'); // '.' is not a delimiter, only a separator.
public static bool IsSymbol(char c) => symbols.Contains(c);
public static readonly HashSet<char> symbols = new HashSet<char>
public static readonly HashSet<char> symbols = new()
{
'[', '{', '(', // open
']', '}', ')', // close

View File

@ -3,7 +3,6 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
// Thanks to ManlyMarco for this
@ -13,7 +12,10 @@ namespace UnityExplorer.CSConsole
{
private static readonly HashSet<string> StdLib = new(StringComparer.InvariantCultureIgnoreCase)
{
"mscorlib", "System.Core", "System", "System.Xml"
"mscorlib",
"System.Core",
"System",
"System.Xml"
};
internal TextWriter _textWriter;
@ -45,7 +47,7 @@ namespace UnityExplorer.CSConsole
private void Reference(Assembly asm)
{
var name = asm.GetName().Name;
string name = asm.GetName().Name;
if (name == "completions")
return;
ReferenceAssembly(asm);
@ -55,7 +57,7 @@ namespace UnityExplorer.CSConsole
{
_reportPrinter = new StreamReportPrinter(tw);
var settings = new CompilerSettings
CompilerSettings settings = new()
{
Version = LanguageVersion.Experimental,
GenerateDebugInfo = false,

View File

@ -2,11 +2,9 @@
using Mono.CSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityExplorer.Runtime;
using UnityExplorer.UI.Panels;
using UniverseLib;
@ -29,16 +27,16 @@ namespace UnityExplorer.CSConsole
public static void Inspect(Type type)
=> InspectorManager.Inspect(type);
public static Coroutine Start(IEnumerator ienumerator)
public static Coroutine Start(IEnumerator ienumerator)
=> RuntimeHelper.StartCoroutine(ienumerator);
public static void Stop(Coroutine coro)
=> RuntimeHelper.StopCoroutine(coro);
public static void Copy(object obj)
public static void Copy(object obj)
=> ClipboardPanel.Copy(obj);
public static object Paste()
public static object Paste()
=> ClipboardPanel.Current;
public static void GetUsing()
@ -46,7 +44,7 @@ namespace UnityExplorer.CSConsole
public static void GetVars()
{
var vars = Evaluator.GetVars()?.Trim();
string vars = Evaluator.GetVars()?.Trim();
if (string.IsNullOrEmpty(vars))
ExplorerCore.LogWarning("No variables seem to be defined!");
else
@ -59,12 +57,12 @@ namespace UnityExplorer.CSConsole
.GetValue(Evaluator) is CompilationSourceFile sourceFile
&& sourceFile.Containers.Any())
{
var sb = new StringBuilder();
StringBuilder sb = new();
sb.Append($"There are {sourceFile.Containers.Count} defined classes:");
foreach (TypeDefinition type in sourceFile.Containers.Where(it => it is TypeDefinition))
{
sb.Append($"\n\n{type.MemberName.Name}:");
foreach (var member in type.Members)
foreach (MemberCore member in type.Members)
sb.Append($"\n\t- {member.AttributeTargets}: \"{member.MemberName.Name}\" ({member.ModFlags})");
}
Log(sb.ToString());