Skip to content

Commit

Permalink
Use proper modifiers, names and primary constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
Tinggaard committed Apr 15, 2024
1 parent 1fb8238 commit 62a89b9
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 74 deletions.

This file was deleted.

22 changes: 10 additions & 12 deletions SocietalConstructionTool/Compiler/Typechecker/CTableBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ public CTableBuilder()
{
_globalClass = new KeyValuePair<string, ClassContent>("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))
{
Expand All @@ -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))
{
Expand All @@ -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))
{
Expand All @@ -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))
{
Expand All @@ -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))
{
Expand Down
19 changes: 10 additions & 9 deletions SocietalConstructionTool/Compiler/Typechecker/SctTableVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ namespace Sct.Compiler.Typechecker
{
public class SctTableVisitor : SctBaseVisitor<SctType>, IErrorReporter
{
public CTable? Ctable { get; private set; }
private CTable? InternalCTable { get; set; }
public CTable CTable => InternalCTable ?? _ctableBuilder.BuildCtable();

private readonly List<CompilerError> _errors = new();
public IEnumerable<CompilerError> Errors => _errors;
Expand All @@ -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"));
Expand All @@ -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));
}
Expand All @@ -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;
}
Expand All @@ -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));
}
Expand All @@ -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));
}
Expand All @@ -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));
}
Expand Down
12 changes: 3 additions & 9 deletions SocietalConstructionTool/Runtime/QueryHandler.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
namespace Sct.Runtime
{
public class QueryHandler : IQueryHandler
public class QueryHandler(IEnumerable<BaseAgent> agents) : IQueryHandler
{
private readonly IEnumerable<BaseAgent> _agents;
public QueryHandler(IEnumerable<BaseAgent> agents)
{
_agents = agents;
}

private IEnumerable<BaseAgent> Filter(IQueryPredicate predicate) => _agents.Where(a => predicate.Test(a));
private IEnumerable<BaseAgent> 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();
}
}
17 changes: 5 additions & 12 deletions SocietalConstructionTool/Runtime/QueryPredicate.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
namespace Sct.Runtime
{
public class QueryPredicate : IQueryPredicate
public class QueryPredicate(string className, string? state, IDictionary<string, dynamic> fields) : IQueryPredicate
{
public string ClassName { get; }
public string? State { get; }
public string ClassName { get; } = className;
public string? State { get; } = state;

public IDictionary<string, dynamic> Fields { get; }

public QueryPredicate(string className, string? state, IDictionary<string, dynamic> fields)
{
ClassName = className;
State = state;
Fields = fields;
}
public IDictionary<string, dynamic> Fields { get; } = fields;

public bool Test(BaseAgent agent)
{
Expand All @@ -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;
}
Expand Down
4 changes: 1 addition & 3 deletions SocietalConstructionTool/Runtime/RuntimeContextFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

/// <summary>
/// Create the next RuntimeContext based on the current context.
Expand Down
12 changes: 6 additions & 6 deletions SocietalConstructionTool/SctRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static class SctRunner
* <param name="filename">The path of the SCT source file</param>
* <returns>The resulting C# source, or null if compilation failed</returns>
*/
public static (string? outputText, IEnumerable<CompilerError> errors) CompileSct(string filename)
private static (string? outputText, IEnumerable<CompilerError> errors) CompileSct(string filename)
{
// TODO: Add error handling
string input = File.ReadAllText(filename);
Expand All @@ -40,11 +40,11 @@ public static (string? outputText, IEnumerable<CompilerError> 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();

Expand Down Expand Up @@ -84,7 +84,7 @@ public static (string? outputText, IEnumerable<CompilerError> errors) CompileSct
* <param name="outputStream">The stream to output into</param>
* <returns>The result of emitting</returns>
*/
public static EmitResult Emit(string sourceText, Stream outputStream)
private static EmitResult Emit(string sourceText, Stream outputStream)
{
string generatedAssemblyName = "sctGenerated";
var tree = SyntaxFactory.ParseSyntaxTree(sourceText);
Expand Down Expand Up @@ -116,7 +116,7 @@ private static PortableExecutableReference GetReferenceFromType(Type t)
* <param name="assembly">The assembly to run</param>
* <param name="logger">The logger to use to output the result of the simulation</param>
*/
public static void Run(Assembly assembly, IOutputLogger logger)
private static void Run(Assembly assembly, IOutputLogger logger)
{
IRuntimeContext ctx = RuntimeContextFactory.Create(logger);
Run(assembly, ctx);
Expand All @@ -129,7 +129,7 @@ public static void Run(Assembly assembly, IOutputLogger logger)
* <param name="assembly">The assembly to run</param>
* <param name="initialContext">The initial context of the simulation</param>
*/
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]);
Expand Down
4 changes: 2 additions & 2 deletions SocietalConstructionToolTests/TypecheckerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 62a89b9

Please sign in to comment.