Upsilon/Ycicle/Program.cs

126 lines
4.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using Upsilon;
using Upsilon.Evaluator;
using Upsilon.StandardLibraries;
namespace Ycicle
{
internal static class Program
{
private static void Main()
{
Console.WriteLine("Upsilon REPL");
Script script = null;
var options = new ScriptOptions()
{
ThrowExceptionOnError = false
};
while (true)
{
Console.Write("» ");
var input = Console.ReadLine();
if (input == "exit") return;
script = script == null
? Executor.ParseInput(input, options)
: Executor.ContinueWith(script, input);
if (script.Diagnostics.Errors.Count > 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Errors were found during parsing");
foreach (var diagnosticsMessage in script.Diagnostics.Errors)
{
LogMessage(DiagnosticLevel.Error, diagnosticsMessage);
}
Console.ResetColor();
continue;
}
//Console.WriteLine(script.PrettyPrintSyntaxTree());
var evaluate = script.Evaluate();
if (script.Diagnostics.Errors.Count > 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Errors were found during evaluating");
foreach (var diagnosticsMessage in script.Diagnostics.Errors)
{
LogMessage(DiagnosticLevel.Error, diagnosticsMessage);
}
Console.ResetColor();
}
else
{
foreach (var diagnosticsMessage in script.Diagnostics.Warnings)
{
LogMessage(DiagnosticLevel.Warning, diagnosticsMessage);
}
Console.ResetColor();
if (evaluate == null)
continue;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(ParseEvaluated(evaluate));
Console.ResetColor();
}
}
}
private static void LogMessage(DiagnosticLevel level, DiagnosticsMessage message)
{
if (level == DiagnosticLevel.Error)
Console.ForegroundColor = ConsoleColor.Red;
else if (level == DiagnosticLevel.Warning)
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine(message.Message);
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(message.GetDiagnosticPosition() + " ");
Console.Write(message.LineBeforeError());
if (level == DiagnosticLevel.Error)
Console.ForegroundColor = ConsoleColor.Red;
else if (level == DiagnosticLevel.Warning)
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.Write(message.AtError());
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(message.LineAfterError());
Console.WriteLine();
}
private static string ParseEvaluated(object o, int jumps = 0)
{
var sb = new StringBuilder();
if (o is Dictionary<string, object> dic)
{
for (var i = 0; i < jumps; i++) sb.Append(" ");
sb.Append("{\n");
foreach (var (key, value) in dic)
{
for (var i = 0; i < jumps; i++) sb.Append(" ");
sb.Append(" {");
sb.Append("\"");
sb.Append(key);
sb.Append("\": ");
sb.Append(ParseEvaluated(value, jumps + 1));
sb.Append(" }");
sb.Append(",\n");
}
for (var i = 0; i < jumps; i++) sb.Append(" ");
sb.Append("}\n");
}
else
{
sb.Append(o);
}
return sb.ToString();
}
}
}