Code cleanup

This commit is contained in:
Stone_Red
2026-03-05 22:55:11 +01:00
parent 276ae421e8
commit 789f56ba95
35 changed files with 100 additions and 80 deletions
+1 -1
View File
@@ -399,4 +399,4 @@ internal enum Mode
Edit, Edit,
Command, Command,
Debug Debug
} }
+1 -1
View File
@@ -387,4 +387,4 @@ internal class InputHandler(TextEditor textEditor)
textEditor.IsStepDebugMode = false; textEditor.IsStepDebugMode = false;
textEditor.EditMode = previousMode; textEditor.EditMode = previousMode;
} }
} }
+1 -1
View File
@@ -173,4 +173,4 @@ internal partial class SyntaxHighlighter(ReadOnlyCollection<StatementInformation
// This regex matches the color information embedded in the string, which is in the format \x01{colorIndex}\x01{base64EncodedValue}. // This regex matches the color information embedded in the string, which is in the format \x01{colorIndex}\x01{base64EncodedValue}.
[GeneratedRegex(@"(?<=(\x01))(.*)(?=\x01)")] [GeneratedRegex(@"(?<=(\x01))(.*)(?=\x01)")]
private static partial Regex StringColorRegex(); private static partial Regex StringColorRegex();
} }
+1 -1
View File
@@ -10,4 +10,4 @@ if (args.Length == 1)
else else
{ {
Console.WriteLine("No path specified!"); Console.WriteLine("No path specified!");
} }
+1 -1
View File
@@ -333,4 +333,4 @@ public class AddStatementTests
interpreter.AddStatement("var", SearchMode.StartOfLine, SpaceAround.End, _ => { }); interpreter.AddStatement("var", SearchMode.StartOfLine, SpaceAround.End, _ => { });
}); });
} }
} }
@@ -77,5 +77,4 @@ public class CodeFlowStatementsTests
YesNtAssert.ContainsTerminationMessage(lines, "Function \"nowhere\" not found"); YesNtAssert.ContainsTerminationMessage(lines, "Function \"nowhere\" not found");
} }
} }
+1 -2
View File
@@ -285,5 +285,4 @@ public class CodeFlowTests
YesNtAssert.ContainsTerminationMessage(lines, "No matching while found"); YesNtAssert.ContainsTerminationMessage(lines, "No matching while found");
} }
} }
@@ -106,5 +106,4 @@ public class ConsoleStatementsTests
StringAssert.Contains(output.ToString(), "Terminated by external process"); StringAssert.Contains(output.ToString(), "Terminated by external process");
} }
} }
@@ -223,5 +223,4 @@ public class FunctionStatementsTests
YesNtAssert.IsLastLineEqual(lines, "outer_val"); YesNtAssert.IsLastLineEqual(lines, "outer_val");
} }
} }
@@ -158,4 +158,4 @@ public class ListStatementsTests
YesNtAssert.IsLastLineEqual(lines, "hello world"); YesNtAssert.IsLastLineEqual(lines, "hello world");
} }
} }
@@ -104,4 +104,4 @@ public class PredefinedVariableStatementsTests
Assert.IsTrue(int.TryParse(parts[0], out _)); Assert.IsTrue(int.TryParse(parts[0], out _));
Assert.IsTrue(int.TryParse(parts[1], out _)); Assert.IsTrue(int.TryParse(parts[1], out _));
} }
} }
@@ -198,5 +198,4 @@ public class ProcessingStatementsTests
YesNtAssert.IsLastLineEqual(lines, "2", timeout: 3000); YesNtAssert.IsLastLineEqual(lines, "2", timeout: 3000);
} }
} }
@@ -110,4 +110,4 @@ public class StringLiteralStatementsTests
YesNtAssert.ContainsTerminationMessage(lines, "Invalid string literal"); YesNtAssert.ContainsTerminationMessage(lines, "Invalid string literal");
} }
} }
@@ -45,5 +45,4 @@ public class SystemStatementsTests
YesNtAssert.ContainsTerminationMessage(lines, "Failed to start \"does_not_exist_abc_xyz\""); YesNtAssert.ContainsTerminationMessage(lines, "Failed to start \"does_not_exist_abc_xyz\"");
} }
} }
@@ -128,5 +128,4 @@ public class VariableStatementsTests
YesNtAssert.ContainsTerminationMessage(lines, "Variable \"missing\" not found"); YesNtAssert.ContainsTerminationMessage(lines, "Variable \"missing\" not found");
} }
} }
+1 -1
View File
@@ -123,4 +123,4 @@ internal static class YesNtAssert
return (debugEventArgs, outputBuilder.ToString()); return (debugEventArgs, outputBuilder.ToString());
} }
} }
@@ -107,4 +107,4 @@ public class StatementAttribute : Attribute
SpaceAround = spaceAround; SpaceAround = spaceAround;
IgnoreSyntaxHighlighting = true; IgnoreSyntaxHighlighting = true;
} }
} }
+1 -1
View File
@@ -80,4 +80,4 @@ internal static class ExitMessages
{ {
return $"Failed to start \"{program}\". {message}"; return $"Failed to start \"{program}\". {message}";
} }
} }
+1 -1
View File
@@ -25,4 +25,4 @@ internal class FunctionScope(int callerLine, Stack<string> arguments)
/// <summary>Gets the stack of output values pushed via <c>push_out</c>, consumed by the caller via <c>%out</c>.</summary> /// <summary>Gets the stack of output values pushed via <c>push_out</c>, consumed by the caller via <c>%out</c>.</summary>
public Stack<string> Results { get; } = new(); public Stack<string> Results { get; } = new();
} }
+1 -3
View File
@@ -1,6 +1,4 @@
using System.Collections.Generic; namespace YesNt.Interpreter.Runtime;
namespace YesNt.Interpreter.Runtime;
/// <summary> /// <summary>
/// Represents a single source line together with its location metadata. /// Represents a single source line together with its location metadata.
@@ -197,4 +197,4 @@ internal sealed class RuntimeInformation
{ {
Exit(ExitMessages.TerminatedByParentTask, stopAllTasks); Exit(ExitMessages.TerminatedByParentTask, stopAllTasks);
} }
} }
@@ -1,4 +1,5 @@
using System; using System;
using YesNt.Interpreter.Attributes; using YesNt.Interpreter.Attributes;
namespace YesNt.Interpreter.Runtime; namespace YesNt.Interpreter.Runtime;
@@ -6,4 +7,4 @@ namespace YesNt.Interpreter.Runtime;
/// <summary> /// <summary>
/// Pre-calculated statement handler information for faster matching. /// Pre-calculated statement handler information for faster matching.
/// </summary> /// </summary>
internal record StatementHandler(StatementAttribute Attribute, Action<string> Handler, string FullName); internal record StatementHandler(StatementAttribute Attribute, Action<string> Handler, string FullName);
@@ -430,9 +430,9 @@ public class YesNtInterpreter
{ {
runtimeInfo.BlockBoundaries.Clear(); runtimeInfo.BlockBoundaries.Clear();
lineMatchingHandlers = new List<List<StatementHandler>>(runtimeInfo.Lines.Count); lineMatchingHandlers = new List<List<StatementHandler>>(runtimeInfo.Lines.Count);
// Dictionary to track open blocks by their expected end statement name // Dictionary to track open blocks by their expected end statement name
var openBlocks = new Dictionary<string, Stack<int>>(); Dictionary<string, Stack<int>> openBlocks = [];
for (int i = 0; i < runtimeInfo.Lines.Count; i++) for (int i = 0; i < runtimeInfo.Lines.Count; i++)
{ {
@@ -449,7 +449,7 @@ public class YesNtInterpreter
string blockPair = handler.Attribute.BlockPair; string blockPair = handler.Attribute.BlockPair;
if (!string.IsNullOrEmpty(blockPair) && !handler.Attribute.IsBlockIntermediate) if (!string.IsNullOrEmpty(blockPair) && !handler.Attribute.IsBlockIntermediate)
{ {
if (!openBlocks.TryGetValue(blockPair, out var stack)) if (!openBlocks.TryGetValue(blockPair, out Stack<int> stack))
{ {
stack = new Stack<int>(); stack = new Stack<int>();
openBlocks[blockPair] = stack; openBlocks[blockPair] = stack;
@@ -460,7 +460,7 @@ public class YesNtInterpreter
// Track block ends // Track block ends
if (handler.Attribute.IsBlockEnd) if (handler.Attribute.IsBlockEnd)
{ {
if (openBlocks.TryGetValue(handler.Attribute.Name, out var stack) && stack.Count > 0) if (openBlocks.TryGetValue(handler.Attribute.Name, out Stack<int> stack) && stack.Count > 0)
{ {
int startLine = stack.Pop(); int startLine = stack.Pop();
runtimeInfo.BlockBoundaries[startLine] = i; runtimeInfo.BlockBoundaries[startLine] = i;
@@ -474,7 +474,7 @@ public class YesNtInterpreter
string intermediatePair = handler.Attribute.BlockPair; string intermediatePair = handler.Attribute.BlockPair;
if (!string.IsNullOrEmpty(intermediatePair)) if (!string.IsNullOrEmpty(intermediatePair))
{ {
if (!openBlocks.TryGetValue(intermediatePair, out var stack)) if (!openBlocks.TryGetValue(intermediatePair, out Stack<int> stack))
{ {
stack = new Stack<int>(); stack = new Stack<int>();
openBlocks[intermediatePair] = stack; openBlocks[intermediatePair] = stack;
@@ -507,4 +507,4 @@ public class YesNtInterpreter
_ => false _ => false
}; };
} }
} }
@@ -279,4 +279,4 @@ internal class CodeFlowStatements : StatementRuntimeInformation
{ {
return RuntimeInfo.BlockBoundaries.TryGetValue(currentLine, out int cached) ? cached : -1; return RuntimeInfo.BlockBoundaries.TryGetValue(currentLine, out int cached) ? cached : -1;
} }
} }
@@ -63,4 +63,4 @@ internal class ConsoleStatements : StatementRuntimeInformation
{ {
Console.Clear(); Console.Clear();
} }
} }
@@ -173,4 +173,4 @@ internal class FunctionStatements : StatementRuntimeInformation
{ {
RuntimeInfo.FunctionCallStack.Clear(); RuntimeInfo.FunctionCallStack.Clear();
} }
} }
@@ -271,4 +271,4 @@ internal class ListStatements : StatementRuntimeInformation
return true; return true;
} }
} }
@@ -1,5 +1,4 @@
using System; using System;
using System.Runtime.InteropServices;
using YesNt.Interpreter.Attributes; using YesNt.Interpreter.Attributes;
using YesNt.Interpreter.Enums; using YesNt.Interpreter.Enums;
@@ -47,4 +46,4 @@ internal class PredefinedVariableStatements : StatementRuntimeInformation
{ {
RuntimeInfo.CurrentLine = TemplateProcessor.ProcessDynamicPlaceholders(args, "%rand", () => random.Next(32767, int.MaxValue).ToString()).TrimEnd(); RuntimeInfo.CurrentLine = TemplateProcessor.ProcessDynamicPlaceholders(args, "%rand", () => random.Next(32767, int.MaxValue).ToString()).TrimEnd();
} }
} }
@@ -103,4 +103,4 @@ internal partial class ProcessingStatements : StatementRuntimeInformation
[GeneratedRegex("[0-9*+().,^%/-]+[0-9*+ ().,^%/-]+[0-9*+().,^%/-]+")] [GeneratedRegex("[0-9*+().,^%/-]+[0-9*+ ().,^%/-]+[0-9*+().,^%/-]+")]
private static partial Regex CalculationRegex(); private static partial Regex CalculationRegex();
} }
@@ -79,4 +79,4 @@ internal class StringLiteralStatements : StatementRuntimeInformation
_ => escapeChar _ => escapeChar
}; };
} }
} }
@@ -116,4 +116,4 @@ internal class SystemStatements : StatementRuntimeInformation
RuntimeInfo.OutParametersStack = new(outputStack); RuntimeInfo.OutParametersStack = new(outputStack);
RuntimeInfo.OutParametersStack.Push(process.ExitCode.ToString()); RuntimeInfo.OutParametersStack.Push(process.ExitCode.ToString());
} }
} }
@@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using YesNt.Interpreter.Attributes; using YesNt.Interpreter.Attributes;
@@ -65,4 +64,4 @@ internal partial class VariableStatements : StatementRuntimeInformation
{ {
RuntimeInfo.CurrentLine = TemplateProcessor.ProcessVariables(RuntimeInfo.CurrentLine, RuntimeInfo); RuntimeInfo.CurrentLine = TemplateProcessor.ProcessVariables(RuntimeInfo.CurrentLine, RuntimeInfo);
} }
} }
+1 -1
View File
@@ -214,4 +214,4 @@ internal static partial class Evaluator
[GeneratedRegex("(\\+ +\\-)+")] [GeneratedRegex("(\\+ +\\-)+")]
private static partial Regex PlusMinusRegex(); private static partial Regex PlusMinusRegex();
} }
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using YesNt.Interpreter.Runtime; using YesNt.Interpreter.Runtime;
namespace YesNt.Interpreter.Utilities; namespace YesNt.Interpreter.Utilities;
@@ -16,33 +17,39 @@ internal static class TemplateProcessor
/// </summary> /// </summary>
public static string ProcessVariables(string input, RuntimeInformation runtimeInfo) public static string ProcessVariables(string input, RuntimeInformation runtimeInfo)
{ {
if (string.IsNullOrEmpty(input)) return input; if (string.IsNullOrEmpty(input))
{
return input;
}
int startIdx = input.IndexOf("${", StringComparison.Ordinal); int startIdx = input.IndexOf("${", StringComparison.Ordinal);
if (startIdx == -1) return input; if (startIdx == -1)
{
return input;
}
StringBuilder sb = new StringBuilder(input.Length); StringBuilder sb = new StringBuilder(input.Length);
int lastIdx = 0; int lastIdx = 0;
while (startIdx != -1) while (startIdx != -1)
{ {
sb.Append(input, lastIdx, startIdx - lastIdx); _ = sb.Append(input, lastIdx, startIdx - lastIdx);
int endIdx = input.IndexOf('}', startIdx + 2); int endIdx = input.IndexOf('}', startIdx + 2);
if (endIdx == -1) if (endIdx == -1)
{ {
sb.Append("${"); _ = sb.Append("${");
lastIdx = startIdx + 2; lastIdx = startIdx + 2;
} }
else else
{ {
string varName = input.Substring(startIdx + 2, endIdx - (startIdx + 2)); string varName = input[(startIdx + 2)..endIdx];
if (runtimeInfo.Variables.TryGetValue(varName, out string value)) if (runtimeInfo.Variables.TryGetValue(varName, out string value))
{ {
sb.Append(value); _ = sb.Append(value);
} }
else if (runtimeInfo.GlobalVariables.TryGetValue(varName, out value)) else if (runtimeInfo.GlobalVariables.TryGetValue(varName, out value))
{ {
sb.Append(value); _ = sb.Append(value);
} }
else if (!runtimeInfo.IsSearching) else if (!runtimeInfo.IsSearching)
{ {
@@ -51,9 +58,9 @@ internal static class TemplateProcessor
} }
else else
{ {
sb.Append("${"); _ = sb.Append("${");
sb.Append(varName); _ = sb.Append(varName);
sb.Append('}'); _ = sb.Append('}');
} }
lastIdx = endIdx + 1; lastIdx = endIdx + 1;
@@ -62,7 +69,7 @@ internal static class TemplateProcessor
startIdx = input.IndexOf("${", lastIdx, StringComparison.Ordinal); startIdx = input.IndexOf("${", lastIdx, StringComparison.Ordinal);
} }
sb.Append(input, lastIdx, input.Length - lastIdx); _ = sb.Append(input, lastIdx, input.Length - lastIdx);
return sb.ToString(); return sb.ToString();
} }
@@ -71,10 +78,16 @@ internal static class TemplateProcessor
/// </summary> /// </summary>
public static string ProcessStackParameters(string input, string placeholder, Stack<string> stack, RuntimeInformation runtimeInfo, string emptyStackMessage) public static string ProcessStackParameters(string input, string placeholder, Stack<string> stack, RuntimeInformation runtimeInfo, string emptyStackMessage)
{ {
if (string.IsNullOrEmpty(input)) return input; if (string.IsNullOrEmpty(input))
{
return input;
}
int startIdx = input.IndexOf(placeholder, StringComparison.Ordinal); int startIdx = input.IndexOf(placeholder, StringComparison.Ordinal);
if (startIdx == -1) return input; if (startIdx == -1)
{
return input;
}
StringBuilder sb = new StringBuilder(input.Length); StringBuilder sb = new StringBuilder(input.Length);
int lastIdx = 0; int lastIdx = 0;
@@ -82,18 +95,18 @@ internal static class TemplateProcessor
while (startIdx != -1) while (startIdx != -1)
{ {
sb.Append(input, lastIdx, startIdx - lastIdx); _ = sb.Append(input, lastIdx, startIdx - lastIdx);
if (stack.Count == 0) if (stack.Count == 0)
{ {
runtimeInfo.Exit(emptyStackMessage, true); runtimeInfo.Exit(emptyStackMessage, true);
return input; return input;
} }
sb.Append(stack.Pop()); _ = sb.Append(stack.Pop());
lastIdx = startIdx + placeholderLen; lastIdx = startIdx + placeholderLen;
startIdx = input.IndexOf(placeholder, lastIdx, StringComparison.Ordinal); startIdx = input.IndexOf(placeholder, lastIdx, StringComparison.Ordinal);
} }
sb.Append(input, lastIdx, input.Length - lastIdx); _ = sb.Append(input, lastIdx, input.Length - lastIdx);
return sb.ToString(); return sb.ToString();
} }
@@ -102,9 +115,7 @@ internal static class TemplateProcessor
/// </summary> /// </summary>
public static string ProcessSimplePlaceholders(string input, string placeholder, string value) public static string ProcessSimplePlaceholders(string input, string placeholder, string value)
{ {
if (string.IsNullOrEmpty(input)) return input; return string.IsNullOrEmpty(input) ? input : input.Replace(placeholder, value, StringComparison.Ordinal);
return input.Replace(placeholder, value, StringComparison.Ordinal);
} }
/// <summary> /// <summary>
@@ -112,10 +123,16 @@ internal static class TemplateProcessor
/// </summary> /// </summary>
public static string ProcessDynamicPlaceholders(string input, string placeholder, Func<string> valueProvider) public static string ProcessDynamicPlaceholders(string input, string placeholder, Func<string> valueProvider)
{ {
if (string.IsNullOrEmpty(input)) return input; if (string.IsNullOrEmpty(input))
{
return input;
}
int startIdx = input.IndexOf(placeholder, StringComparison.Ordinal); int startIdx = input.IndexOf(placeholder, StringComparison.Ordinal);
if (startIdx == -1) return input; if (startIdx == -1)
{
return input;
}
StringBuilder sb = new StringBuilder(input.Length); StringBuilder sb = new StringBuilder(input.Length);
int lastIdx = 0; int lastIdx = 0;
@@ -123,13 +140,13 @@ internal static class TemplateProcessor
while (startIdx != -1) while (startIdx != -1)
{ {
sb.Append(input, lastIdx, startIdx - lastIdx); _ = sb.Append(input, lastIdx, startIdx - lastIdx);
sb.Append(valueProvider()); _ = sb.Append(valueProvider());
lastIdx = startIdx + placeholderLen; lastIdx = startIdx + placeholderLen;
startIdx = input.IndexOf(placeholder, lastIdx, StringComparison.Ordinal); startIdx = input.IndexOf(placeholder, lastIdx, StringComparison.Ordinal);
} }
sb.Append(input, lastIdx, input.Length - lastIdx); _ = sb.Append(input, lastIdx, input.Length - lastIdx);
return sb.ToString(); return sb.ToString();
} }
@@ -138,10 +155,16 @@ internal static class TemplateProcessor
/// </summary> /// </summary>
public static string ProcessCalculations(string input, RuntimeInformation runtimeInfo, Regex calculationRegex) public static string ProcessCalculations(string input, RuntimeInformation runtimeInfo, Regex calculationRegex)
{ {
if (string.IsNullOrEmpty(input)) return input; if (string.IsNullOrEmpty(input))
{
return input;
}
MatchCollection matches = calculationRegex.Matches(input); MatchCollection matches = calculationRegex.Matches(input);
if (matches.Count == 0) return input; if (matches.Count == 0)
{
return input;
}
StringBuilder sb = new StringBuilder(input.Length); StringBuilder sb = new StringBuilder(input.Length);
int lastIdx = 0; int lastIdx = 0;
@@ -149,19 +172,19 @@ internal static class TemplateProcessor
for (int i = 0; i < matches.Count; i++) for (int i = 0; i < matches.Count; i++)
{ {
Match match = matches[i]; Match match = matches[i];
sb.Append(input, lastIdx, match.Index - lastIdx); _ = sb.Append(input, lastIdx, match.Index - lastIdx);
string res = Evaluator.Calculate(match.Value); string res = Evaluator.Calculate(match.Value);
if (res is null) if (res is null)
{ {
runtimeInfo.Exit(ExitMessages.InvalidOperation, true); runtimeInfo.Exit(ExitMessages.InvalidOperation, true);
return input; return input;
} }
sb.Append(res); _ = sb.Append(res);
lastIdx = match.Index + match.Length; lastIdx = match.Index + match.Length;
} }
sb.Append(input, lastIdx, input.Length - lastIdx); _ = sb.Append(input, lastIdx, input.Length - lastIdx);
return sb.ToString(); return sb.ToString();
} }
} }
@@ -47,6 +47,13 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.20.0.135146">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\YesNt.Interpreter.Generator\YesNt.Interpreter.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> <ProjectReference Include="..\YesNt.Interpreter.Generator\YesNt.Interpreter.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup> </ItemGroup>