Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V2 prototypes #61

Open
wants to merge 2 commits into
base: v2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 155 additions & 0 deletions src/Hypercube.Core/IO/Parsers/Yaml/YamlParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
using System.Text;

namespace Hypercube.Core.IO.Parsers.Yaml;

public static class YamlParser
{
// Private constants for quotes, escape characters, and comment symbol
private const char DoubleQuote = '"';
private const char SingleQuote = '\'';
private const char EscapeChar = '\\';
private const char CommentChar = '#';

/// <summary>
/// Parses the provided YAML string into a dictionary of prototypes.
/// </summary>
/// <param name="yamlData">The YAML string to be parsed.</param>
/// <returns>A dictionary with prototype IDs as keys and field dictionaries as values.</returns>
public static Dictionary<string, Dictionary<string, string>> ParseYaml(string yamlData)
{
var result = new Dictionary<string, Dictionary<string, string>>();
var lines = yamlData.Split('\n', StringSplitOptions.RemoveEmptyEntries);

string? currentId = null;

var currentFields = new Dictionary<string, string>();
var inString = false;

foreach (var line in lines)
{
var cleanedLine = ProcessLine(line, ref inString);

// Ignore empty or commented-out lines
if (string.IsNullOrWhiteSpace(cleanedLine))
continue;

var parts = cleanedLine.Split(':', 2, StringSplitOptions.TrimEntries);

// Process a new prototype section (ID and fields)
if (!line.StartsWith(" ") && cleanedLine.Contains(":"))
{
if (currentId != null)
result[currentId] = currentFields;

currentId = parts[0];
currentFields = new Dictionary<string, string>();
continue;
}

if (!line.StartsWith(" "))
continue;

if (parts.Length != 2)
continue;

currentFields[parts[0]] = RemoveQuotesAndEscape(parts[1]);
}

// Add the last prototype if present
if (currentId != null)
result[currentId] = currentFields;

return result;
}

/// <summary>
/// Processes a line by stripping out comments and handling quote and escape characters.
/// </summary>
/// <param name="line">The line to process.</param>
/// <param name="inString">Indicates whether we are currently inside a string.</param>
/// <returns>A cleaned-up line with comments removed and quotes handled.</returns>
private static string ProcessLine(string line, ref bool inString)
{
var cleanedLine = string.Empty;
foreach (var ch in line)
{
// Toggle string state on encountering a quote
if (ch is DoubleQuote or SingleQuote)
inString = !inString;

// Ignore comments if not inside a string
// And stop processing the line at the comment symbol
if (ch == CommentChar && !inString)
break;

cleanedLine += ch;
}

return cleanedLine.Trim();
}

/// <summary>
/// Removes surrounding quotes and handles escape sequences inside the string.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The value with quotes removed and escape sequences properly handled.</returns>
private static string RemoveQuotesAndEscape(string value)
{
// Check for open/close quote mismatch
var startsWithQuote = value.StartsWith(DoubleQuote) || value.StartsWith(SingleQuote);
var endsWithQuote = value.EndsWith(DoubleQuote) || value.EndsWith(SingleQuote);

if (startsWithQuote && !endsWithQuote)
throw new FormatException("String starts with a quote but does not end with one.");

if (!startsWithQuote && endsWithQuote)
throw new FormatException("String ends with a quote but does not start with one.");

// Remove surrounding quotes if they exist
if ((value.StartsWith(DoubleQuote) && value.EndsWith(DoubleQuote)) ||
(value.StartsWith(SingleQuote) && value.EndsWith(SingleQuote)))
{
value = value.Substring(1, value.Length - 2); // Remove quotes
}

var result = string.Empty;
var isEscaped = false;

// Process each character in the string
foreach (var currentChar in value)
{
// If we're escaping the next character
if (isEscaped)
{
result += currentChar switch
{
'n' => '\n', // Handle newline escape
't' => '\t', // Handle tab escape
'r' => '\r', // Handle carriage return escape
'\\' => '\\', // Handle escaped backslash
'"' => '\"', // Handle escaped double quote
'\'' => '\'', // Handle escaped single quote
_ => throw new FormatException($"Invalid escape sequence: \\{currentChar}")
};

isEscaped = false;
continue;
}

// Detect escape sequence
if (currentChar == EscapeChar)
{
isEscaped = true;
continue;
}

result += currentChar;
}

// If we're still escaping after the loop, it's an invalid escape sequence
if (isEscaped)
throw new FormatException("String ends with an incomplete escape sequence.");

return result;
}
}
6 changes: 6 additions & 0 deletions src/Hypercube.Core/IO/Prototypes/IPrototype.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Hypercube.Core.IO.Prototypes;

public interface IPrototype
{
string Id { get; set; }
}
12 changes: 12 additions & 0 deletions src/Hypercube.Core/IO/Prototypes/PrototypeAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Hypercube.Core.IO.Prototypes;

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class PrototypeAttribute : Attribute
{
public readonly string Id;

public PrototypeAttribute(string id)
{
Id = id;
}
}
50 changes: 50 additions & 0 deletions src/Hypercube.Core/IO/Prototypes/PrototypeId.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
namespace Hypercube.Core.IO.Prototypes;

public readonly struct PrototypeId<T> where T : IPrototype
{
public readonly string Id;

public PrototypeId(string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentException("Prototype ID cannot be null or empty.", nameof(id));

Id = id;
}

public override string ToString()
{
return Id;
}

public override bool Equals(object? obj)
{
return obj is PrototypeId<T> other && string.Equals(Id, other.Id, StringComparison.Ordinal);
}

public override int GetHashCode()
{
return Id.GetHashCode();
}

public static implicit operator string(PrototypeId<T> prototypeId)
{
return prototypeId.Id;
}

public static explicit operator PrototypeId<T>(string id)
{
return new PrototypeId<T>(id);
}


public static bool operator ==(PrototypeId<T> left, PrototypeId<T> right)
{
return left.Equals(right);
}

public static bool operator !=(PrototypeId<T> left, PrototypeId<T> right)
{
return !(left == right);
}
}
12 changes: 12 additions & 0 deletions src/Hypercube.Core/IO/Prototypes/Storage/IPrototypeStorage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Diagnostics.CodeAnalysis;

namespace Hypercube.Core.IO.Prototypes.Storage;

public interface IPrototypeStorage
{
T GetPrototype<T>(PrototypeId<T> id) where T : class, IPrototype;
bool TryGetPrototype<T>(PrototypeId<T> id, [NotNullWhen(true)] out T? prototype) where T : class, IPrototype;
bool HasPrototype<T>(PrototypeId<T> id) where T : class, IPrototype;
IEnumerable<T> EnumeratePrototypes<T>() where T : class, IPrototype;
void LoadPrototypes(string yamlData);
}
93 changes: 93 additions & 0 deletions src/Hypercube.Core/IO/Prototypes/Storage/PrototypeStorage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System.Collections.Frozen;
using System.Diagnostics.CodeAnalysis;
using Hypercube.Core.IO.Parsers.Yaml;
using Hypercube.Utilities.Helpers;

namespace Hypercube.Core.IO.Prototypes.Storage;

public class PrototypeStorage : IPrototypeStorage
{
private readonly FrozenDictionary<string, Type> _types;
private readonly Dictionary<string, IPrototype> _prototypes = new();

public PrototypeStorage()
{
var types = new Dictionary<string, Type>();
foreach (var (type, attribute) in ReflectionHelper.GetAllTypesWithAttribute<PrototypeAttribute>())
{
types[attribute.Id] = type;
}

_types = types.ToFrozenDictionary();
}

public T GetPrototype<T>(PrototypeId<T> id) where T : class, IPrototype
{
if (_prototypes.TryGetValue(id.Id, out var prototype) && prototype is T typedPrototype)
return typedPrototype;

throw new KeyNotFoundException($"Prototype with ID '{id.Id}' not found or is of the wrong type.");
}

public bool TryGetPrototype<T>(PrototypeId<T> id, [NotNullWhen(true)] out T? prototype) where T : class, IPrototype
{
if (_prototypes.TryGetValue(id.Id, out var proto) && proto is T typedPrototype)
{
prototype = typedPrototype;
return true;
}

prototype = null;
return false;
}

public bool HasPrototype<T>(PrototypeId<T> id) where T : class, IPrototype
{
return _prototypes.TryGetValue(id.Id, out var proto) && proto is T;
}

public IEnumerable<T> EnumeratePrototypes<T>() where T : class, IPrototype
{
return _prototypes.Values.OfType<T>();
}

public void LoadPrototypes(string yamlData)
{
var rawPrototypes = YamlParser.ParseYaml(yamlData);

foreach (var (id, fields) in rawPrototypes)
{
if (!fields.TryGetValue("type", out var value))
throw new InvalidOperationException($"Prototype '{id}' is missing a 'type' field.");

if (!_types.TryGetValue(value, out var prototypeType))
throw new InvalidOperationException($"Unknown or incompatible type '{value}' for prototype '{id}'.");

if (Activator.CreateInstance(prototypeType) is not IPrototype prototype)
throw new InvalidOperationException($"Failed to create prototype '{id}' of type '{value}'.");

PopulateFields(prototype, fields);
var property = prototypeType.GetProperty(nameof(IPrototype.Id));

if (property is null)
throw new InvalidOperationException($"Prototype '{id}' does not have a valid '{nameof(IPrototype.Id)}' property.");

property.SetValue(prototype, id);
_prototypes[id] = prototype;
}
}

private void PopulateFields(IPrototype prototype, Dictionary<string, string> fields)
{
var type = prototype.GetType();
foreach (var (fieldName, rawValue) in fields)
{
var property = type.GetProperty(fieldName);
if (property is null || !property.CanWrite)
continue;

var convertedValue = Convert.ChangeType(rawValue, property.PropertyType);
property.SetValue(prototype, convertedValue);
}
}
}
Loading