From 62a89b98318b9bb3543afaa8005c50603c1ea817 Mon Sep 17 00:00:00 2001 From: Jens Tinggaard Date: Mon, 15 Apr 2024 12:22:07 +0200 Subject: [PATCH] Use proper modifiers, names and primary constructors --- .../Exceptions/UnrecognizedValueException.cs | 21 ------------------ .../Compiler/Typechecker/CTableBuilder.cs | 22 +++++++++---------- .../Compiler/Typechecker/SctTableVisitor.cs | 19 ++++++++-------- .../Runtime/QueryHandler.cs | 12 +++------- .../Runtime/QueryPredicate.cs | 17 +++++--------- .../Runtime/RuntimeContextFactory.cs | 4 +--- SocietalConstructionTool/SctRunner.cs | 12 +++++----- .../TypecheckerTests.cs | 4 ++-- 8 files changed, 37 insertions(+), 74 deletions(-) delete mode 100644 SocietalConstructionTool/Compiler/Exceptions/UnrecognizedValueException.cs diff --git a/SocietalConstructionTool/Compiler/Exceptions/UnrecognizedValueException.cs b/SocietalConstructionTool/Compiler/Exceptions/UnrecognizedValueException.cs deleted file mode 100644 index 1c0d320b..00000000 --- a/SocietalConstructionTool/Compiler/Exceptions/UnrecognizedValueException.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Sct.Compiler.Exceptions -{ - public class UnrecognizedValueException : Exception - { - public UnrecognizedValueException() - { - } - - public UnrecognizedValueException(string message) : base(message) - { - } - - public UnrecognizedValueException(string message, Exception innerException) : base(message, innerException) - { - } - - public UnrecognizedValueException(string expected, string actual) : base($"Expected {expected} but got {actual}") - { - } - } -} diff --git a/SocietalConstructionTool/Compiler/Typechecker/CTableBuilder.cs b/SocietalConstructionTool/Compiler/Typechecker/CTableBuilder.cs index d7db90ef..160529e9 100644 --- a/SocietalConstructionTool/Compiler/Typechecker/CTableBuilder.cs +++ b/SocietalConstructionTool/Compiler/Typechecker/CTableBuilder.cs @@ -10,15 +10,15 @@ public CTableBuilder() { _globalClass = new KeyValuePair("Global", new ClassContent("Global")); _currentClass = _globalClass; - _ = AddFunction("count", new FunctionType(TypeTable.Int, [TypeTable.Predicate])); - _ = AddFunction("exists", new FunctionType(TypeTable.Int, [TypeTable.Predicate])); - _ = AddFunction("rand", new FunctionType(TypeTable.Float, [])); - _ = AddFunction("seed", new FunctionType(TypeTable.Void, [TypeTable.Int])); + _ = TryAddFunction("count", new FunctionType(TypeTable.Int, [TypeTable.Predicate])); + _ = TryAddFunction("exists", new FunctionType(TypeTable.Int, [TypeTable.Predicate])); + _ = TryAddFunction("rand", new FunctionType(TypeTable.Float, [])); + _ = TryAddFunction("seed", new FunctionType(TypeTable.Void, [TypeTable.Int])); } public CTable BuildCtable() => new(_classes, _globalClass.Value); - public bool StartClass(string className) + public bool TryStartClass(string className) { if (_classes.ContainsKey(className)) { @@ -28,15 +28,13 @@ public bool StartClass(string className) return true; } - public bool FinishClass() + public void FinishClass() { _classes.Add(_currentClass.Key, _currentClass.Value); _currentClass = _globalClass; - - return _classes.ContainsKey(_currentClass.Key); } - public bool AddField(string name, SctType type) + public bool TryAddField(string name, SctType type) { if (_currentClass.Value.Fields.ContainsKey(name)) { @@ -45,7 +43,7 @@ public bool AddField(string name, SctType type) return _currentClass.Value.AddField(name, type); } - public bool AddFunction(string functionName, FunctionType functionType) + public bool TryAddFunction(string functionName, FunctionType functionType) { if (IDExistsGlobal(functionName)) { @@ -54,7 +52,7 @@ public bool AddFunction(string functionName, FunctionType functionType) return _currentClass.Value.AddFunction(functionName, functionType); } - public bool AddState(string name) + public bool TryAddState(string name) { if (IDExistsGlobal(name)) { @@ -63,7 +61,7 @@ public bool AddState(string name) return _currentClass.Value.AddState(name); } - public bool AddDecorator(string name) + public bool TryAddDecorator(string name) { if (IDExistsGlobal(name)) { diff --git a/SocietalConstructionTool/Compiler/Typechecker/SctTableVisitor.cs b/SocietalConstructionTool/Compiler/Typechecker/SctTableVisitor.cs index a879f526..26891b70 100644 --- a/SocietalConstructionTool/Compiler/Typechecker/SctTableVisitor.cs +++ b/SocietalConstructionTool/Compiler/Typechecker/SctTableVisitor.cs @@ -4,7 +4,8 @@ namespace Sct.Compiler.Typechecker { public class SctTableVisitor : SctBaseVisitor, IErrorReporter { - public CTable? Ctable { get; private set; } + private CTable? InternalCTable { get; set; } + public CTable CTable => InternalCTable ?? _ctableBuilder.BuildCtable(); private readonly List _errors = new(); public IEnumerable Errors => _errors; @@ -14,9 +15,9 @@ public override SctType VisitStart([NotNull] SctParser.StartContext context) { _ = base.VisitStart(context); - Ctable = _ctableBuilder.BuildCtable(); + InternalCTable = _ctableBuilder.BuildCtable(); - var setupType = Ctable.GlobalClass.LookupFunctionType("Setup"); + var setupType = InternalCTable.GlobalClass.LookupFunctionType("Setup"); if (setupType is null) { _errors.Add(new CompilerError("No setup function found")); @@ -32,14 +33,14 @@ public override SctType VisitClass_def([NotNull] SctParser.Class_defContext cont { string className = context.ID().GetText(); - if (!_ctableBuilder.StartClass(className)) + if (!_ctableBuilder.TryStartClass(className)) { _errors.Add(new CompilerError($"ID {className} already exists", context.Start.Line, context.Start.Column)); } foreach (var (id, type) in context.args_def().ID().Zip(context.args_def().type())) { - if (!_ctableBuilder.AddField(id.GetText(), type.Accept(this))) + if (!_ctableBuilder.TryAddField(id.GetText(), type.Accept(this))) { _errors.Add(new CompilerError($"ID {id.GetText()} already exists", id.Symbol.Line, id.Symbol.Column)); } @@ -48,7 +49,7 @@ public override SctType VisitClass_def([NotNull] SctParser.Class_defContext cont _ = base.VisitClass_def(context); - _ = _ctableBuilder.FinishClass(); + _ctableBuilder.FinishClass(); return TypeTable.None; } @@ -60,7 +61,7 @@ public override SctType VisitFunction([NotNull] SctParser.FunctionContext contex var functionType = new FunctionType(type, argsTypes); - if (!_ctableBuilder.AddFunction(context.ID().GetText(), functionType)) + if (!_ctableBuilder.TryAddFunction(context.ID().GetText(), functionType)) { _errors.Add(new CompilerError($"ID {context.ID().GetText()} already exists", context.Start.Line, context.Start.Column)); } @@ -82,7 +83,7 @@ public override SctType VisitType([NotNull] SctParser.TypeContext context) public override SctType VisitState([NotNull] SctParser.StateContext context) { - if (!_ctableBuilder.AddState(context.ID().GetText())) + if (!_ctableBuilder.TryAddState(context.ID().GetText())) { _errors.Add(new CompilerError($"ID {context.ID().GetText()} already exists", context.Start.Line, context.Start.Column)); } @@ -91,7 +92,7 @@ public override SctType VisitState([NotNull] SctParser.StateContext context) public override SctType VisitDecorator([NotNull] SctParser.DecoratorContext context) { - if (!_ctableBuilder.AddDecorator(context.ID().GetText())) + if (!_ctableBuilder.TryAddDecorator(context.ID().GetText())) { _errors.Add(new CompilerError($"ID {context.ID().GetText()} already exists", context.Start.Line, context.Start.Column)); } diff --git a/SocietalConstructionTool/Runtime/QueryHandler.cs b/SocietalConstructionTool/Runtime/QueryHandler.cs index 833c66b6..5122079d 100644 --- a/SocietalConstructionTool/Runtime/QueryHandler.cs +++ b/SocietalConstructionTool/Runtime/QueryHandler.cs @@ -1,17 +1,11 @@ namespace Sct.Runtime { - public class QueryHandler : IQueryHandler + public class QueryHandler(IEnumerable agents) : IQueryHandler { - private readonly IEnumerable _agents; - public QueryHandler(IEnumerable agents) - { - _agents = agents; - } - - private IEnumerable Filter(IQueryPredicate predicate) => _agents.Where(a => predicate.Test(a)); + private IEnumerable Filter(IQueryPredicate predicate) => agents.Where(predicate.Test); public int Count(IQueryPredicate predicate) => Filter(predicate).Count(); - public bool Exists(IQueryPredicate predicate) => Count(predicate) > 0; + public bool Exists(IQueryPredicate predicate) => Filter(predicate).Any(); } } diff --git a/SocietalConstructionTool/Runtime/QueryPredicate.cs b/SocietalConstructionTool/Runtime/QueryPredicate.cs index 27ac812e..70f1d0b0 100644 --- a/SocietalConstructionTool/Runtime/QueryPredicate.cs +++ b/SocietalConstructionTool/Runtime/QueryPredicate.cs @@ -1,18 +1,11 @@ namespace Sct.Runtime { - public class QueryPredicate : IQueryPredicate + public class QueryPredicate(string className, string? state, IDictionary fields) : IQueryPredicate { - public string ClassName { get; } - public string? State { get; } + public string ClassName { get; } = className; + public string? State { get; } = state; - public IDictionary Fields { get; } - - public QueryPredicate(string className, string? state, IDictionary fields) - { - ClassName = className; - State = state; - Fields = fields; - } + public IDictionary Fields { get; } = fields; public bool Test(BaseAgent agent) { @@ -22,7 +15,7 @@ public bool Test(BaseAgent agent) return false; } // Match the state - if (State != null && agent.State != State) + if (State is null || agent.State != State) { return false; } diff --git a/SocietalConstructionTool/Runtime/RuntimeContextFactory.cs b/SocietalConstructionTool/Runtime/RuntimeContextFactory.cs index 39e42641..11d797a5 100644 --- a/SocietalConstructionTool/Runtime/RuntimeContextFactory.cs +++ b/SocietalConstructionTool/Runtime/RuntimeContextFactory.cs @@ -4,9 +4,7 @@ namespace Sct.Runtime { public class RuntimeContextFactory { - public static IRuntimeContext Create() => Create(null); - - public static IRuntimeContext Create(IOutputLogger? logger) => new RuntimeContext(new AgentHandler(), new QueryHandler([]), logger); + public static IRuntimeContext Create(IOutputLogger logger) => new RuntimeContext(new AgentHandler(), new QueryHandler([]), logger); /// /// Create the next RuntimeContext based on the current context. diff --git a/SocietalConstructionTool/SctRunner.cs b/SocietalConstructionTool/SctRunner.cs index 439d78f6..cca15d8d 100644 --- a/SocietalConstructionTool/SctRunner.cs +++ b/SocietalConstructionTool/SctRunner.cs @@ -23,7 +23,7 @@ public static class SctRunner * The path of the SCT source file * The resulting C# source, or null if compilation failed */ - public static (string? outputText, IEnumerable errors) CompileSct(string filename) + private static (string? outputText, IEnumerable errors) CompileSct(string filename) { // TODO: Add error handling string input = File.ReadAllText(filename); @@ -40,11 +40,11 @@ public static (string? outputText, IEnumerable errors) CompileSct // Run visitor that populates the tables. var sctTableVisitor = new SctTableVisitor(); _ = startNode.Accept(sctTableVisitor); - var ctable = sctTableVisitor.Ctable; + var ctable = sctTableVisitor.CTable; errors.AddRange(sctTableVisitor.Errors); // Run visitor that checks the types. - var sctTypeChecker = new SctTypeChecker(ctable!); + var sctTypeChecker = new SctTypeChecker(ctable); _ = startNode.Accept(sctTypeChecker); parser.Reset(); @@ -84,7 +84,7 @@ public static (string? outputText, IEnumerable errors) CompileSct * The stream to output into * The result of emitting */ - public static EmitResult Emit(string sourceText, Stream outputStream) + private static EmitResult Emit(string sourceText, Stream outputStream) { string generatedAssemblyName = "sctGenerated"; var tree = SyntaxFactory.ParseSyntaxTree(sourceText); @@ -116,7 +116,7 @@ private static PortableExecutableReference GetReferenceFromType(Type t) * The assembly to run * The logger to use to output the result of the simulation */ - public static void Run(Assembly assembly, IOutputLogger logger) + private static void Run(Assembly assembly, IOutputLogger logger) { IRuntimeContext ctx = RuntimeContextFactory.Create(logger); Run(assembly, ctx); @@ -129,7 +129,7 @@ public static void Run(Assembly assembly, IOutputLogger logger) * The assembly to run * The initial context of the simulation */ - public static void Run(Assembly assembly, IRuntimeContext initialContext) + private static void Run(Assembly assembly, IRuntimeContext initialContext) { var globalClassName = $"{SctTranslator.GeneratedNamespace}.{SctTranslator.GeneratedGlobalClass}"; _ = assembly.GetType(globalClassName)?.GetMethod(SctTranslator.RunSimulationFunctionName)?.Invoke(null, [initialContext]); diff --git a/SocietalConstructionToolTests/TypecheckerTests.cs b/SocietalConstructionToolTests/TypecheckerTests.cs index f2723244..f65874c9 100644 --- a/SocietalConstructionToolTests/TypecheckerTests.cs +++ b/SocietalConstructionToolTests/TypecheckerTests.cs @@ -39,10 +39,10 @@ public async Task TypecheckFile(string testFile) var sctTableVisitor = new SctTableVisitor(); _ = sctTableVisitor.Visit(startNode); - var ctable = sctTableVisitor.Ctable; + var ctable = sctTableVisitor.CTable; errors.AddRange(sctTableVisitor.Errors); - var sctTypeChecker = new SctTypeChecker(ctable!); + var sctTypeChecker = new SctTypeChecker(ctable); _ = startNode.Accept(sctTypeChecker); errors.AddRange(sctTypeChecker.Errors);