Skip to content

Commit

Permalink
cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
burdoto committed Oct 16, 2022
1 parent e37b876 commit 8f7d957
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 35 deletions.
2 changes: 1 addition & 1 deletion clmath/Compiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ public double Evaluate(MathContext? ctx)

break;
case Type.Eval:
if (Program.LoadFunc(arg!.ToString()!) is not {} res)
if (Program.LoadFunc(arg!.ToString()!) is not { } res)
return double.NaN;
var subCtx = new MathContext(res.ctx);
foreach (var (key, value) in ctx!.var)
Expand Down
105 changes: 75 additions & 30 deletions clmath/Program.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System.Collections.Immutable;
using System.Globalization;
using System.Globalization;
using System.Text.RegularExpressions;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using clmath.Antlr;

namespace clmath;
Expand All @@ -11,7 +9,10 @@ public static class Program
{
private static readonly string FuncExt = ".math";
private static readonly string ConstExt = ".vars";
private static readonly string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "comroid", "clmath");

private static readonly string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"comroid", "clmath");

private static readonly string constantsFile = Path.Combine(dir, "constants" + ConstExt);

private static bool _exiting;
Expand All @@ -24,18 +25,19 @@ public static class Program
{ "e", Math.E },
{ "tau", Math.Tau }
};
internal static Dictionary<string, double> constants { get; private set; } = null!;

static Program()
{
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
if (!File.Exists(constantsFile))
SaveConstants(new());
if (!File.Exists(constantsFile))
SaveConstants(new Dictionary<string, double>());
LoadConstants();
}

internal static Dictionary<string, double> constants { get; private set; } = null!;

private static void SaveConstants(Dictionary<string, double>? values = null)
{
values ??= constants;
Expand All @@ -46,7 +48,7 @@ private static void LoadConstants()
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (constants == null)
constants = new();
constants = new Dictionary<string, double>();
else constants.Clear();
foreach (var (key, value) in globalConstants)
constants[key] = value;
Expand All @@ -57,17 +59,17 @@ private static void LoadConstants()
private static string ConvertValuesToString(Dictionary<string, Component> values, Func<string, bool>? skip = null)
{
skip ??= _ => false;
string txt = string.Empty;
var txt = string.Empty;
foreach (var (key, value) in values)
if (!skip(key))
txt += $"{key} = {value}\n";
return txt;
}

private static string ConvertValuesToString(Dictionary<string, double> values, Func<string, bool>? skip = null)
{
skip ??= _ => false;
string txt = string.Empty;
var txt = string.Empty;
foreach (var (key, value) in values)
if (!skip(key))
txt += $"{key} = {value}\n";
Expand Down Expand Up @@ -103,7 +105,9 @@ public static void Main(string[] args)
else
{
if (args[0] == "graph")
{
StartGraph(CreateArgsFuncs(args));
}
else
{
var arg = string.Join(" ", args);
Expand All @@ -116,8 +120,8 @@ public static void Main(string[] args)

private static string CleanupString(string str)
{
int leadingSpaces = 0;
for (int i = 0; i < str.Length && str[i] == ' '; i++)
var leadingSpaces = 0;
for (var i = 0; i < str.Length && str[i] == ' '; i++)
leadingSpaces++;
return str.Substring(leadingSpaces, str.Length - leadingSpaces);
}
Expand Down Expand Up @@ -152,16 +156,18 @@ private static void StdIoMode()
break;
case "set":
var setConstN = ConvertValueFromString(func.Substring("set ".Length, func.Length - "set ".Length));
if (setConstN is not {} setConst)
if (setConstN is not { } setConst)
{
Console.WriteLine("Error: Invalid declaration of constant variable; try 'x = 5'");
break;
}

if (globalConstants.ContainsKey(setConst.key))
{
Console.WriteLine($"Error: Cannot redefine {setConst.key}");
break;
}

constants[setConst.key] = setConst.value.Evaluate(null);
SaveConstants();
break;
Expand All @@ -173,11 +179,13 @@ private static void StdIoMode()
Console.WriteLine($"Error: Cannot unset {cmds[1]}");
break;
}

if (!constants.ContainsKey(cmds[1]))
{
Console.WriteLine($"Error: Unknown constant {cmds[1]}");
break;
}

constants.Remove(cmds[1]);
SaveConstants();
break;
Expand All @@ -187,53 +195,66 @@ private static void StdIoMode()
Console.WriteLine("Error: Listing target unspecified; options are 'funcs' and 'constants'");
break;
}

switch (cmds[1])
{
case "funcs" or "fx":
var funcs = Directory.EnumerateFiles(dir, "*.math").Select(p => new FileInfo(p)).ToArray();
if (funcs.Length == 0)
{
Console.WriteLine("No saved functions");
}
else
{
Console.WriteLine("Available functions:");
foreach (var file in funcs)
Console.WriteLine($"\t- {file.Name.Substring(0, file.Name.Length - FuncExt.Length)}");
Console.WriteLine(
$"\t- {file.Name.Substring(0, file.Name.Length - FuncExt.Length)}");
}

break;
case "constants" or "const":
if (constants.Count == 0)
if (constants.Count == 0)
{
Console.WriteLine("No available constants");
}
else
{
Console.WriteLine("Available constants:");
foreach (var (key, value) in constants)
Console.WriteLine($"\t{key}\t= {value}");
}

break;
case "stash":
if (stash.Count == 0)
{
Console.WriteLine("No functions in stash");
}
else
{
Console.WriteLine("Stashed Functions:");
int i = 0;
var i = 0;
foreach (var (fx, ctx) in stash)
{
Console.WriteLine($"\tstash[{i++}]\t= {fx}");
ctx.DumpVariables("stash[#]".Length / 8 + 1, shouldError: false);
ctx.DumpVariables("stash[#]".Length / 8 + 1, false);
}
}

break;
default:
Console.WriteLine($"Error: Unknown listing target '{cmds[1]}'; options are 'funcs', 'constants' and 'stash'");
Console.WriteLine(
$"Error: Unknown listing target '{cmds[1]}'; options are 'funcs', 'constants' and 'stash'");
break;
}

break;
case "load":
if (!IsInvalidArgumentCount(cmds, 2))
{
var load = LoadFunc(cmds[1]);
if (load is {} res)
if (load is { } res)
EvalFunc(res.func, ctx: res.ctx);
}

Expand All @@ -256,13 +277,18 @@ private static void StdIoMode()
File.Delete(path0);
Console.WriteLine($"Function with name {cmds[1]} deleted");
}
else Console.WriteLine($"Function with name {cmds[1]} not found");
else
{
Console.WriteLine($"Function with name {cmds[1]} not found");
}

break;
case "restore":
(Component func, MathContext ctx) entry;
if (cmds.Length == 1)
{
entry = stash.Pop();
}
else
{
if (Regex.Match(cmds[1], "\\d+") is { Success: true })
Expand All @@ -273,6 +299,7 @@ private static void StdIoMode()
Console.WriteLine($"Error: Backtrace index {index} too large");
break;
}

entry = stash.ToArray()[index];
var bak = stash.ToList();
bak.Remove(entry);
Expand All @@ -286,6 +313,7 @@ private static void StdIoMode()
break;
}
}

EvalFunc(entry.func, ctx: entry.ctx);
break;
case "graph":
Expand Down Expand Up @@ -315,15 +343,20 @@ internal static (Component func, MathContext ctx)? LoadFunc(string name)
Console.WriteLine($"Function with name {name} not found");
return null;
}

var data = File.ReadAllText(path);
var lnb = data.IndexOf("\n", StringComparison.Ordinal);
MathContext ctx;
if (lnb != -1)
{
var vars = ConvertValuesFromString(data.Substring(lnb + 1, data.Length - lnb - 2));
ctx = new(vars);
ctx = new MathContext(vars);
}
else
{
ctx = new MathContext();
}
else ctx = new();

return (ParseFunc(lnb == -1 ? data : data.Substring(0, lnb)), ctx);
}

Expand Down Expand Up @@ -379,7 +412,7 @@ private static void EvalFunc(Component func, string? f = null, MathContext? ctx
else if (constants.ContainsKey(key))
Console.WriteLine($"Error: Cannot redefine {key}");
else ctx.var[key] = value;

if (FindMissingVariables(func, ctx).Count == 0)
PrintResult(func, func.Evaluate(ctx));
}
Expand All @@ -400,7 +433,8 @@ private static void EvalFunc(Component func, string? f = null, MathContext? ctx
Console.WriteLine("\tdrop\t\tDrops the current function");
Console.WriteLine("\tclear [var]\tClears all variables or just one from the cache");
Console.WriteLine("\tdump\t\tPrints all variables in the cache");
Console.WriteLine("\tsave <name>\tSaves the current function with the given name; append '-y' to store current variables as well");
Console.WriteLine(
"\tsave <name>\tSaves the current function with the given name; append '-y' to store current variables as well");
Console.WriteLine("\tstash\t\tStores the function in stash");
Console.WriteLine("\tgraph\t\tDisplays the function in a 2D graph");
Console.WriteLine(
Expand All @@ -413,7 +447,7 @@ private static void EvalFunc(Component func, string? f = null, MathContext? ctx
case "save":
if (IsInvalidArgumentCount(cmds, 2))
break;
string data = f ?? func.ToString();
var data = f ?? func.ToString();
if (cmds.Length > 2 && cmds[2] == "-y")
data += $"\n{ConvertValuesToString(ctx.var, globalConstants.ContainsKey)}";
var path = Path.Combine(dir, cmds[1] + FuncExt);
Expand All @@ -432,7 +466,11 @@ private static void EvalFunc(Component func, string? f = null, MathContext? ctx
ctx.var.Remove(cmds[1]);
Console.WriteLine($"Variable {cmds[1]} deleted");
}
else ctx.var.Clear();
else
{
ctx.var.Clear();
}

break;
case "stash":
stash.Push((func, ctx));
Expand All @@ -450,7 +488,11 @@ private static void EvalFunc(Component func, string? f = null, MathContext? ctx
Console.WriteLine(
$"Error: Missing variable{(missing.Count != 1 ? "s" : "")} {string.Join(", ", missing)}");
}
else PrintResult(func, func.Evaluate(ctx), ctx);
else
{
PrintResult(func, func.Evaluate(ctx), ctx);
}

break;
default:
Console.WriteLine("Error: Unknown command; type 'help' for a list of commands");
Expand Down Expand Up @@ -486,13 +528,16 @@ private static int DumpVariables(this MathContext ctx, int alignBase = 1, bool s
Console.WriteLine("Error: No variables are set");
return 1;
}
int maxAlign = ctx.var.Keys.Max(key => key.Length) / 8;

var maxAlign = ctx.var.Keys.Max(key => key.Length) / 8;
foreach (var (key, val) in ctx.var)
{
var align = Math.Max(maxAlign > 0 ? maxAlign - alignBase : alignBase, maxAlign - (key.Length / 8 + 1) + alignBase);
var align = Math.Max(maxAlign > 0 ? maxAlign - alignBase : alignBase,
maxAlign - (key.Length / 8 + 1) + alignBase);
var spacer = Enumerable.Range(0, align).Aggregate(string.Empty, (str, _) => str + '\t');
Console.WriteLine($"\t{key}{spacer}= {val}");
}

return maxAlign;
}

Expand Down
8 changes: 4 additions & 4 deletions clmath/clmath.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Antlr4.Runtime.Standard" Version="4.11.1" />
<PackageReference Include="Silk.NET.Input" Version="2.16.0" />
<PackageReference Include="Silk.NET.OpenGL" Version="2.16.0" />
<PackageReference Include="Silk.NET.Windowing" Version="2.16.0" />
<PackageReference Include="Antlr4.Runtime.Standard" Version="4.11.1"/>
<PackageReference Include="Silk.NET.Input" Version="2.16.0"/>
<PackageReference Include="Silk.NET.OpenGL" Version="2.16.0"/>
<PackageReference Include="Silk.NET.Windowing" Version="2.16.0"/>
</ItemGroup>

<ItemGroup>
Expand Down

0 comments on commit 8f7d957

Please sign in to comment.