Skip to content
Merged
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
11 changes: 11 additions & 0 deletions RPGModder.Core/Merge/CommandBranch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Newtonsoft.Json.Linq;

namespace RPGModder.Core.Merge;

/// <summary>
/// One body of a block (guide 3.6). <c>Marker</c> is <c>null</c> for an unmarked body, as the first body of a
/// Conditional Branch or a Loop. <c>Body</c> ends with its code 0 node.
/// </summary>
internal sealed record CommandBranch(
JObject? Marker,
IReadOnlyList<CommandNode> Body);
14 changes: 14 additions & 0 deletions RPGModder.Core/Merge/CommandNode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Newtonsoft.Json.Linq;

namespace RPGModder.Core.Merge;

/// <summary>
/// One command of a list with what belongs to it (guide 3.6): the continuation lines of its block, its branches, and
/// the end marker that closes them. The code 0 command that ends a body or the list is a node of its own with
/// nothing below it. <c>End</c> is kept, and not rebuilt, so a list comes back unchanged (GR-T1).
/// </summary>
internal sealed record CommandNode(
JObject Head,
IReadOnlyList<JObject> Continuations,
IReadOnlyList<CommandBranch> Branches,
JObject? End);
279 changes: 279 additions & 0 deletions RPGModder.Core/Merge/CommandTree.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,279 @@
using Newtonsoft.Json.Linq;

namespace RPGModder.Core.Merge;

/// <summary>
/// Parses a command list into its tree and back (guide 3.6). Structure is indent alone, as in the engine's
/// <c>Game_Interpreter</c>: a branch marker tests only the branch of its own indent, and <c>skipBranch</c> skips the
/// deeper commands. The parser is strict, so a list it accepts is walked by the engine the way the tree says, and
/// anything else is one Atomic value (GR-T2).
/// </summary>
internal static class CommandTree
{
/// <summary>The code that ends a body and the list.</summary>
internal const int EndCode = 0;

/// <summary>
/// A list nested deeper than this is one Atomic value. The editor stops far below it, and the bound keeps the
/// parser's recursion on a stack of any size.
/// </summary>
internal const int MaxDepth = 100;

private const string CodeProperty = "code";
private const string IndentProperty = "indent";

/// <summary>The blocks of guide 3.6 whose head is followed by lines of its own at the same indent.</summary>
private static readonly Dictionary<long, long> ContinuationOf = new()
{
[101] = 401,
[105] = 405,
[108] = 408,
[205] = 505,
[302] = 605,
[355] = 655,
[357] = 657
};

/// <summary>The blocks of guide 3.6 that hold bodies.</summary>
private static readonly Dictionary<long, BlockShape> Blocks = new()
{
[102] = new BlockShape(FirstBodyUnmarked: false, Markers: [402, 403], End: 404, OnlyWithMarkers: false),
[111] = new BlockShape(FirstBodyUnmarked: true, Markers: [411], End: 412, OnlyWithMarkers: false),
[112] = new BlockShape(FirstBodyUnmarked: true, Markers: [], End: 413, OnlyWithMarkers: false),
[301] = new BlockShape(FirstBodyUnmarked: false, Markers: [601, 602, 603], End: 604, OnlyWithMarkers: true)
};

/// <summary>Codes that only follow their head: a list that starts a node with one is not parsed.</summary>
private static readonly HashSet<long> Followers = ContinuationOf.Values
.Concat(Blocks.Values.SelectMany(shape => shape.Markers.Append(shape.End)))
.ToHashSet();

/// <summary>
/// The nodes of the list, the final code 0 node last, or <c>null</c> when the list is not well formed: a command
/// that is not an object with a whole <c>code</c> and <c>indent</c>, an indent that is not the depth of its
/// place, a continuation, marker or end marker without its head, a body or a list without its code 0, or
/// anything after the final one.
/// </summary>
internal static IReadOnlyList<CommandNode>? Parse(JArray list)
{
ArgumentNullException.ThrowIfNull(list);

var reader = new Reader(list);
return reader.TryBody(0, out List<CommandNode> nodes) && reader.AtEnd ? nodes : null;
}

/// <summary>The commands of <paramref name="nodes"/> in order, each a copy with its indent set to its depth (GR-T1).</summary>
internal static JArray Flatten(IReadOnlyList<CommandNode> nodes)
{
ArgumentNullException.ThrowIfNull(nodes);

var list = new JArray();
Emit(nodes, 0, list);
return list;
}

/// <summary>The commands of one node at <paramref name="depth"/>, for comparing nodes and for fingerprints.</summary>
internal static JArray Flatten(CommandNode node, int depth)
{
var list = new JArray();
Emit([node], depth, list);
return list;
}

/// <summary>
/// GR-T8: indent steps of at most one, markers only after their head, every body terminated and the final
/// terminator. These are what <see cref="Parse"/> checks, so a list is valid when it parses.
/// </summary>
internal static bool Validate(JArray list)
{
return Parse(list) is not null;
}

internal static bool IsEnd(CommandNode node)
{
return node.Head.Value<long>(CodeProperty) == EndCode;
}

private static void Emit(IReadOnlyList<CommandNode> nodes, int depth, JArray list)
{
foreach (CommandNode node in nodes)
{
Add(node.Head, depth, list);
foreach (JObject line in node.Continuations)
{
Add(line, depth, list);
}

foreach (CommandBranch branch in node.Branches)
{
if (branch.Marker is not null)
{
Add(branch.Marker, depth, list);
}

Emit(branch.Body, depth + 1, list);
}

if (node.End is not null)
{
Add(node.End, depth, list);
}
}
}

private static void Add(JObject command, int depth, JArray list)
{
var copy = (JObject)command.DeepClone();
copy[IndentProperty] = depth;
list.Add(copy);
}

private sealed record BlockShape(bool FirstBodyUnmarked, long[] Markers, long End, bool OnlyWithMarkers);

private sealed class Reader
{
private readonly JArray _list;
private int _position;

public Reader(JArray list)
{
_list = list;
}

public bool AtEnd => _position == _list.Count;

/// <summary>The nodes at <paramref name="depth"/> up to and with the code 0 that ends them.</summary>
public bool TryBody(int depth, out List<CommandNode> nodes)
{
nodes = new List<CommandNode>();
if (depth > MaxDepth)
{
return false;
}

while (CodeAt(_position, depth) is long code)
{
var head = (JObject)_list[_position];
_position++;
if (code == EndCode)
{
nodes.Add(new CommandNode(head, [], [], null));
return true;
}

if (!TryNode(head, code, depth, out CommandNode? node))
{
return false;
}

nodes.Add(node);
}

return false;
}

private bool TryNode(JObject head, long code, int depth, out CommandNode node)
{
node = new CommandNode(head, [], [], null);
if (Followers.Contains(code))
{
return false;
}

var continuations = new List<JObject>();
if (ContinuationOf.TryGetValue(code, out long continuation))
{
while (CodeAt(_position, depth) == continuation)
{
continuations.Add((JObject)_list[_position]);
_position++;
}
}

var branches = new List<CommandBranch>();
JObject? end = null;
if (Blocks.TryGetValue(code, out BlockShape? shape))
{
if (!TryBlock(shape, depth, branches, out end))
{
return false;
}
}
else if (CodeAt(_position, depth + 1) is not null)
{
// GR-T2: a code the parser does not know, with deeper commands after it, holds one unmarked body.
if (!TryBody(depth + 1, out List<CommandNode> body))
{
return false;
}

branches.Add(new CommandBranch(null, body));
}

node = new CommandNode(head, continuations, branches, end);
return true;
}

private bool TryBlock(BlockShape shape, int depth, List<CommandBranch> branches, out JObject? end)
{
end = null;
if (shape.OnlyWithMarkers && !IsMarker(shape, CodeAt(_position, depth)))
{
// Battle Processing without Can Escape or Can Lose has no branches and no end.
return true;
}

if (shape.FirstBodyUnmarked)
{
if (!TryBody(depth + 1, out List<CommandNode> first))
{
return false;
}

branches.Add(new CommandBranch(null, first));
}

while (IsMarker(shape, CodeAt(_position, depth)))
{
var marker = (JObject)_list[_position];
_position++;
if (!TryBody(depth + 1, out List<CommandNode> body))
{
return false;
}

branches.Add(new CommandBranch(marker, body));
}

if (CodeAt(_position, depth) != shape.End)
{
return false;
}

end = (JObject)_list[_position];
_position++;
return true;
}

private static bool IsMarker(BlockShape shape, long? code)
{
return code is long value && shape.Markers.Any(marker => marker == value);
}

/// <summary>The code of the command at <paramref name="index"/> when it is a well-formed command at <paramref name="depth"/>.</summary>
private long? CodeAt(int index, int depth)
{
if (index >= _list.Count ||
_list[index] is not JObject command ||
command.Property(CodeProperty, StringComparison.Ordinal)?.Value is not JValue { Value: long code } ||
command.Property(IndentProperty, StringComparison.Ordinal)?.Value is not JValue { Value: long indent } ||
indent != depth)
{
return null;
}

// A whole number too large for a long is read as a BigInteger, so it is not a code.
return code;
}
}
}
Loading