Add more statements and bug fixes

Add `Execute(List<string>...` method to interpreter
Add escape sequence (`!!`)
Fix `Evaluator.Calulate` method not correctly handling `-` and `+` prefixes
This commit is contained in:
Stone_Red
2022-03-31 13:00:12 +02:00
parent 29bbcebf74
commit 3333641541
11 changed files with 101 additions and 41 deletions
+7 -7
View File
@@ -61,7 +61,7 @@ namespace YesNt.CodeEditor
if (SizeChanged()) if (SizeChanged())
{ {
drawAll = true; drawAll = true;
inputHandler.WriteStatus(string.Empty); InputHandler.WriteStatus(string.Empty);
} }
if (LineOffset < 0 || CursorPosition.Y < 0 || CursorPosition.Y < 0) if (LineOffset < 0 || CursorPosition.Y < 0 || CursorPosition.Y < 0)
@@ -111,14 +111,14 @@ namespace YesNt.CodeEditor
if (!File.Exists(path)) if (!File.Exists(path))
{ {
inputHandler.WriteStatus("File does not exist!"); InputHandler.WriteStatus("File does not exist!");
return false; return false;
} }
Lines.Clear(); Lines.Clear();
Lines.AddRange(File.ReadAllLines(path)); Lines.AddRange(File.ReadAllLines(path));
CurrentPath = path; CurrentPath = path;
inputHandler.WriteStatus("File Loaded!"); InputHandler.WriteStatus("File Loaded!");
return true; return true;
} }
@@ -152,12 +152,12 @@ namespace YesNt.CodeEditor
} }
else if (input.Split(' ').Length > 2) else if (input.Split(' ').Length > 2)
{ {
inputHandler.WriteStatus("Invalid arguments!"); InputHandler.WriteStatus("Invalid arguments!");
return false; return false;
} }
else else
{ {
inputHandler.WriteStatus("File path is empty! (Save the file before you can use this command)"); InputHandler.WriteStatus("File path is empty! (Save the file before you can use this command)");
return false; return false;
} }
@@ -174,12 +174,12 @@ namespace YesNt.CodeEditor
try try
{ {
File.WriteAllLines(path, Lines); File.WriteAllLines(path, Lines);
inputHandler.WriteStatus("File Saved!"); InputHandler.WriteStatus("File Saved!");
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
{ {
inputHandler.WriteStatus(ex.Message); InputHandler.WriteStatus(ex.Message);
return false; return false;
} }
} }
+7 -3
View File
@@ -1,4 +1,5 @@
using System; using System;
using System.Text;
namespace YesNt.CodeEditor namespace YesNt.CodeEditor
{ {
@@ -124,11 +125,14 @@ namespace YesNt.CodeEditor
textEditor.Lines.Add(""); textEditor.Lines.Add("");
} }
while (textEditor.Lines[textEditor.CursorPosition.Y].Length <= textEditor.CursorPosition.X) StringBuilder lineBuilder = new StringBuilder(textEditor.Lines[textEditor.CursorPosition.Y]);
while (lineBuilder.Length <= textEditor.CursorPosition.X)
{ {
textEditor.Lines[textEditor.CursorPosition.Y] += " "; lineBuilder.Append(' ');
} }
textEditor.Lines[textEditor.CursorPosition.Y] = lineBuilder.ToString();
if (keyInfo.Key == ConsoleKey.Backspace) if (keyInfo.Key == ConsoleKey.Backspace)
{ {
if (textEditor.CursorPosition.X > 0) if (textEditor.CursorPosition.X > 0)
@@ -307,7 +311,7 @@ namespace YesNt.CodeEditor
return true; return true;
} }
public void WriteStatus(string input) internal static void WriteStatus(string input)
{ {
Console.SetCursorPosition(0, Console.WindowHeight - 1); Console.SetCursorPosition(0, Console.WindowHeight - 1);
Console.Write(input + new string(' ', Console.WindowWidth - input.Length - 1)); Console.Write(input + new string(' ', Console.WindowWidth - input.Length - 1));
+9 -3
View File
@@ -27,6 +27,12 @@ namespace YesNt.CodeEditor
} }
else else
{ {
MatchCollection matches = Regex.Matches(input, @"!!.");
for (int i = 0; i < matches.Count; i++)
{
input = AddColorInformation(input, matches[i].Value, Console.ForegroundColor, SearchMode.Contains);
}
foreach (StatementInformation statement in statementInformation) foreach (StatementInformation statement in statementInformation)
{ {
if (statement.IgnoreSyntaxHighlighting) if (statement.IgnoreSyntaxHighlighting)
@@ -92,7 +98,7 @@ namespace YesNt.CodeEditor
} }
} }
MatchCollection matches = Regex.Matches(input, @">[a-zA-Z0-9]+"); matches = Regex.Matches(input, @">[a-zA-Z0-9]+");
for (int i = 0; i < matches.Count; i++) for (int i = 0; i < matches.Count; i++)
{ {
input = AddColorInformation(input, matches[i].Value, ConsoleColor.Cyan, SearchMode.Contains); input = AddColorInformation(input, matches[i].Value, ConsoleColor.Cyan, SearchMode.Contains);
@@ -134,11 +140,11 @@ namespace YesNt.CodeEditor
} }
Console.ForegroundColor = consoleColor; Console.ForegroundColor = consoleColor;
Console.Write(messagePart); Console.Write(messagePart);
Console.ForegroundColor = ConsoleColor.Gray;
} }
Console.ForegroundColor = ConsoleColor.Gray;
} }
private string AddColorInformation(string originalString, string value, ConsoleColor color, SearchMode searchMode) private static string AddColorInformation(string originalString, string value, ConsoleColor color, SearchMode searchMode)
{ {
int spacesAtEnd = value.WhiteSpaceAtEnd(); int spacesAtEnd = value.WhiteSpaceAtEnd();
string reult = searchMode switch string reult = searchMode switch
+1
View File
@@ -2,6 +2,7 @@
{ {
internal enum Priority internal enum Priority
{ {
PreProcessing,
Highest, Highest,
VeryHigh, VeryHigh,
High, High,
@@ -6,6 +6,7 @@ namespace YesNt.Interpreter.Runtime
{ {
public int CallerLine { get; } public int CallerLine { get; }
public Dictionary<string, string> Variables { get; } = new(); public Dictionary<string, string> Variables { get; } = new();
public Dictionary<string, int> Labels { get; } = new();
public Stack<string> Arguemtns { get; } public Stack<string> Arguemtns { get; }
public Stack<string> Results { get; } = new(); public Stack<string> Results { get; } = new();
+14 -1
View File
@@ -99,6 +99,19 @@ namespace YesNt.Interpreter
Execute(); Execute();
} }
public void Execute(List<string> lines, bool isDebugMode = false)
{
runtimeInfo.Reset();
runtimeInfo.IsDebugMode = isDebugMode;
for (int i = 0; i < lines.Count; i++)
{
runtimeInfo.Lines.Add(new Line(lines[i], Path.GetFileName("#Memory#"), i));
}
Execute();
}
internal void Execute(List<Line> lines, Dictionary<string, string> gloablVariables, int startLine, RuntimeInformation parentRuntimeInformation) internal void Execute(List<Line> lines, Dictionary<string, string> gloablVariables, int startLine, RuntimeInformation parentRuntimeInformation)
{ {
runtimeInfo.Reset(); runtimeInfo.Reset();
@@ -142,7 +155,7 @@ namespace YesNt.Interpreter
foreach (KeyValuePair<StaticStatementAttribute, Action> staticStatement in staticStatements) foreach (KeyValuePair<StaticStatementAttribute, Action> staticStatement in staticStatements)
{ {
StaticStatementAttribute staticStatementAttribute = staticStatement.Key; StaticStatementAttribute staticStatementAttribute = staticStatement.Key;
if (!staticStatementAttribute.ExecuteInSearchLabelMode && runtimeInfo.IsSearching) if (!staticStatementAttribute.ExecuteInSearchMode && runtimeInfo.IsSearching)
{ {
continue; continue;
} }
@@ -1,4 +1,5 @@
using System; using System;
using System.Diagnostics.CodeAnalysis;
using YesNt.Interpreter.Attributes; using YesNt.Interpreter.Attributes;
using YesNt.Interpreter.Enums; using YesNt.Interpreter.Enums;
@@ -50,7 +51,8 @@ namespace YesNt.Interpreter.Statements
} }
[Statement("cls", SearchMode.Exact, SpaceAround.None, ConsoleColor.Magenta)] [Statement("cls", SearchMode.Exact, SpaceAround.None, ConsoleColor.Magenta)]
public void Clear(string args) [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Won't work if static")]
public void Clear(string _)
{ {
Console.Clear(); Console.Clear();
} }
@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using YesNt.Interpreter.Attributes; using YesNt.Interpreter.Attributes;
using YesNt.Interpreter.Enums; using YesNt.Interpreter.Enums;
@@ -62,11 +61,11 @@ namespace YesNt.Interpreter.Statements
} }
} }
[Statement("%iso", SearchMode.Contains, SpaceAround.End, ConsoleColor.Yellow, KeepStatementInArgs = true, Priority = Priority.Highest)] [Statement("%iso", SearchMode.Contains, SpaceAround.None, ConsoleColor.Yellow, KeepStatementInArgs = true, Priority = Priority.Highest)]
public void CheckIfOutParameterAvalible(string args) public void CheckIfOutParameterAvalible(string args)
{ {
args += " "; args += " ";
args = args.Replace("%iso ", $"{RuntimeInfo.OutParametersStack.Count > 0} "); args = args.Replace("%iso", (RuntimeInfo.OutParametersStack.Count > 0).ToString());
RuntimeInfo.CurrentLine = args.TrimEnd(); RuntimeInfo.CurrentLine = args.TrimEnd();
} }
@@ -89,7 +88,7 @@ namespace YesNt.Interpreter.Statements
RuntimeInfo.InParametersStack.Push(argumanet.Trim()); RuntimeInfo.InParametersStack.Push(argumanet.Trim());
} }
RuntimeInfo.FunctionCallStack.Push(new FunctionScope(RuntimeInfo.LineNumber, new Stack<string>(RuntimeInfo.InParametersStack.Reverse()))); RuntimeInfo.FunctionCallStack.Push(new FunctionScope(RuntimeInfo.LineNumber, new Stack<string>(RuntimeInfo.InParametersStack)));
RuntimeInfo.InParametersStack.Clear(); RuntimeInfo.InParametersStack.Clear();
RuntimeInfo.CurrentLine = string.Empty; RuntimeInfo.CurrentLine = string.Empty;
@@ -138,7 +137,7 @@ namespace YesNt.Interpreter.Statements
} }
args += " "; args += " ";
args = args.Replace("%isi ", $"{RuntimeInfo.FunctionCallStack.Peek().Arguemtns.Count > 0} "); args = args.Replace("%isi", (RuntimeInfo.FunctionCallStack.Peek().Arguemtns.Count > 0).ToString());
RuntimeInfo.CurrentLine = args.TrimEnd(); RuntimeInfo.CurrentLine = args.TrimEnd();
} }
@@ -167,6 +166,11 @@ namespace YesNt.Interpreter.Statements
if (RuntimeInfo.IsSearching) if (RuntimeInfo.IsSearching)
{ {
RuntimeInfo.IsInFunction = false; RuntimeInfo.IsInFunction = false;
if (RuntimeInfo.IsLocalSearch)
{
RuntimeInfo.Exit($"Label \"{RuntimeInfo.SearchLabel}\" not found", true);
}
return; return;
} }
else else
@@ -178,7 +182,7 @@ namespace YesNt.Interpreter.Statements
{ {
FunctionScope functionScope = RuntimeInfo.FunctionCallStack.Pop(); FunctionScope functionScope = RuntimeInfo.FunctionCallStack.Pop();
RuntimeInfo.OutParametersStack = functionScope.Results; RuntimeInfo.OutParametersStack = new Stack<string>(functionScope.Results);
RuntimeInfo.LineNumber = functionScope.CallerLine; RuntimeInfo.LineNumber = functionScope.CallerLine;
} }
else else
@@ -10,36 +10,31 @@ namespace YesNt.Interpreter.Statements
{ {
private readonly Random random = new Random(); private readonly Random random = new Random();
[Statement("%tim", SearchMode.Contains, SpaceAround.End, ConsoleColor.Blue, KeepStatementInArgs = true, Priority = Priority.Highest)] [Statement("%tim", SearchMode.Contains, SpaceAround.None, ConsoleColor.Blue, KeepStatementInArgs = true, Priority = Priority.Highest)]
public void GetUnixTimestamp(string args) public void GetUnixTimestamp(string args)
{ {
args += " "; while (args.Contains("%tim"))
while (args.Contains("%tim "))
{ {
args = args.ReplaceFirstOccurrence("%tim ", $"{DateTimeOffset.Now.ToUnixTimeSeconds()}"); args = args.ReplaceFirstOccurrence("%tim", $"{DateTimeOffset.Now.ToUnixTimeSeconds()}");
} }
RuntimeInfo.CurrentLine = args.TrimEnd(); RuntimeInfo.CurrentLine = args.TrimEnd();
} }
[Statement("%pi", SearchMode.Contains, SpaceAround.End, ConsoleColor.Blue, KeepStatementInArgs = true, Priority = Priority.Highest)] [Statement("%pi", SearchMode.Contains, SpaceAround.None, ConsoleColor.Blue, KeepStatementInArgs = true, Priority = Priority.Highest)]
public void GetPi(string args) public void GetPi(string args)
{ {
args += " "; args = args.Replace("%pi", $"{Math.PI}");
args = args.Replace("%pi ", $"{Math.PI} ");
RuntimeInfo.CurrentLine = args.TrimEnd(); RuntimeInfo.CurrentLine = args.TrimEnd();
} }
[Statement("%rnd", SearchMode.Contains, SpaceAround.End, ConsoleColor.Blue, KeepStatementInArgs = true, Priority = Priority.Highest)] [Statement("%rnd", SearchMode.Contains, SpaceAround.None, ConsoleColor.Blue, KeepStatementInArgs = true, Priority = Priority.Highest)]
public void GetRandom(string args) public void GetRandom(string args)
{ {
args += " "; while (args.Contains("%rnd"))
while (args.Contains("%rnd "))
{ {
args = args.ReplaceFirstOccurrence("%rnd ", $"{random.Next(32767, int.MaxValue)} "); args = args.ReplaceFirstOccurrence("%rnd", $"{random.Next(32767, int.MaxValue)}");
} }
RuntimeInfo.CurrentLine = args.TrimEnd(); RuntimeInfo.CurrentLine = args.TrimEnd();
@@ -13,11 +13,9 @@ namespace YesNt.Interpreter.Statements
{ {
internal class ProcessingStatements : StatementRuntimeInformation internal class ProcessingStatements : StatementRuntimeInformation
{ {
private static readonly Regex calculationRegex = new Regex(@"((\)?)+(\(?)+[0-9]+(((\s?)+(\)?)(\s?)+\+(\s?)+(\(?)+(\s?)+|(\s?)+(\)?)(\s?)+\-(\s?)+(\(?)+(\s?)+|(\s?)+(\)?)(\s?)+\*(\s?)+(\(?)+(\s?)+|(\s?)+(\)?)(\s?)+\%(\s?)+(\(?)+(\s?)+|(\s?)+(\)?)(\s?)+\^(\s?)+(\(?)+(\s?)+|(\s?)+(\)?)(\s?)+\/(\s?)+(\(?)+(\s?)+)|[,.])(?=[0-9])+)+[0-9]+(\)?)+"); private static readonly Regex calculationRegex = new Regex(@"[0-9*+().,^%/-]+[0-9*+ ().,^%/-]+[0-9*+().,^%/-]+");
//new Regex(@"((\)?)+(\(?)+[0-9]+(((\s?)+(\)?)(\s?)+\+(\s?)+(\(?)+(\s?)+|(\s?)+(\)?)(\s?)+\-(\s?)+(\(?)+(\s?)+|(\s?)+(\)?)(\s?)+\*(\s?)+(\(?)+(\s?)+|(\s?)+(\)?)(\s?)+\/(\s?)+(\(?)+(\s?)+)|[,.])(?=[0-9])+)+[0-9]+(\)?)+"); [Statement("!calc", SearchMode.EndOfLine, SpaceAround.Start, ConsoleColor.DarkYellow, Priority = Priority.High)]
[Statement("!calc", SearchMode.EndOfLine, SpaceAround.Start, ConsoleColor.DarkYellow, Priority = Priority.High, ExecuteInSearchMode = true)]
public void Calculate(string args) public void Calculate(string args)
{ {
MatchCollection matches = calculationRegex.Matches(args.FromSaveString()); MatchCollection matches = calculationRegex.Matches(args.FromSaveString());
@@ -30,7 +28,7 @@ namespace YesNt.Interpreter.Statements
RuntimeInfo.Exit("Invalid operation", true); RuntimeInfo.Exit("Invalid operation", true);
return; return;
} }
args = args.FromSaveString().Replace(matches[0].Value, res); args = args.FromSaveString().Replace(matches[i].Value, res);
} }
RuntimeInfo.CurrentLine = args; RuntimeInfo.CurrentLine = args;
@@ -42,6 +40,23 @@ namespace YesNt.Interpreter.Statements
RuntimeInfo.CurrentLine = args.FromSaveString(); RuntimeInfo.CurrentLine = args.FromSaveString();
} }
[Statement("!!", SearchMode.Contains, SpaceAround.None, ConsoleColor.DarkYellow, Priority = Priority.PreProcessing, KeepStatementInArgs = true)]
public void DontEvaluate(string args)
{
int index;
while ((index = args.IndexOf("!!")) != -1)
{
args = args.Remove(index, 2);
if (index < args.Length)
{
char charToEscape = args[index];
args = args.Remove(index, 1);
args = args.Insert(index, charToEscape.ToString().ToSaveString());
}
}
RuntimeInfo.CurrentLine = args;
}
[Statement("!task", SearchMode.EndOfLine, SpaceAround.Start, ConsoleColor.DarkYellow, Priority = Priority.VeryHigh)] [Statement("!task", SearchMode.EndOfLine, SpaceAround.Start, ConsoleColor.DarkYellow, Priority = Priority.VeryHigh)]
public void RunTask(string line) public void RunTask(string line)
{ {
+21 -2
View File
@@ -1,4 +1,5 @@
using System; using System;
using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace YesNt.Interpreter.Utilities namespace YesNt.Interpreter.Utilities
@@ -87,7 +88,18 @@ namespace YesNt.Interpreter.Utilities
return null; return null;
} }
public static string Calculate(string input, char op = '+') public static string Calculate(string input)
{
input = Regex.Replace(input, @"(\+ +\+)+", "+");
input = Regex.Replace(input, @"(\- +\-)+", "+");
input = Regex.Replace(input, @"(\- +\+)+", "-");
input = Regex.Replace(input, @"(\+ +\-)+", "-");
string yes = Calculate(input, '+');
return yes;
}
private static string Calculate(string input, char op)
{ {
if (input is null) if (input is null)
{ {
@@ -110,6 +122,13 @@ namespace YesNt.Interpreter.Utilities
string[] parts = input.Split(op); string[] parts = input.Split(op);
//Weird fix
if (parts.Length >= 2 && string.IsNullOrWhiteSpace(parts[0]))
{
parts[1] = $"{op}{parts[1]}";
parts = parts.Skip(1).ToArray();
}
double number = double.NaN; double number = double.NaN;
foreach (string p in parts) foreach (string p in parts)
@@ -173,7 +192,7 @@ namespace YesNt.Interpreter.Utilities
} }
} }
return number.ToString(); return number.ToString(System.Globalization.CultureInfo.InvariantCulture);
} }
} }
} }