using System.Text; using Canon.Core.Abstractions; using Canon.Core.GrammarParser; namespace Canon.Generator.GrammarGenerator; public class GeneratedTransformer : ITransformer { private readonly IDictionary _shiftPointers; public string Name { get; } public IDictionary ReduceTable { get; } public IDictionary ShiftTable { get; } public GeneratedTransformer(Dictionary shiftTable, Dictionary reduceTable, string name) { ReduceTable = reduceTable; ShiftTable = new Dictionary(); _shiftPointers = shiftTable; Name = name; } public GeneratedTransformer() { ReduceTable = new Dictionary(); ShiftTable = new Dictionary(); _shiftPointers = new Dictionary(); Name = Guid.NewGuid().ToString(); } public void ConstructShiftTable(Dictionary transformers) { foreach (KeyValuePair pair in _shiftPointers) { ShiftTable.Add(pair.Key, transformers[pair.Value]); } } public override bool Equals(object? obj) { if (obj is not GeneratedTransformer other) { return false; } return Name == other.Name; } public override int GetHashCode() => Name.GetHashCode(); public string GenerateCode() { StringBuilder builder = new(); builder.Append("new GeneratedTransformer(new Dictionary").Append("{"); foreach (KeyValuePair pair in ShiftTable) { builder.Append($" {{ {pair.Key.GenerateCode()}, \"{pair.Value.Name}\"}},"); } builder.Append("}, "); builder.Append("new Dictionary{"); foreach (KeyValuePair pair in ReduceTable) { builder.Append($" {{ {pair.Key.GenerateCode()}, {pair.Value.GenerateCode()}}},"); } builder.Append($" }}, \"{Name}\")"); return builder.ToString(); } }