Path: redb-route/redb.Route.Xml/XmlCodeWriter.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/XmlCodeWriter.cs
----
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Xml;
/// How the generated C# is shaped.
public enum CodeGenStyle
{
/// For a human taking the code over: comments from descriptions, clean layout.
Readable,
/// For a build step (AOT): #line directives map diagnostics back to the XML.
Machine,
}
///
/// The emitting side of the code generator: indentation, fluent-verb lines, literal rules
/// (§3.2 — raw strings for anything with quotes or templates, never manual escaping) and typed
/// arguments (§3.3 — s, enums and types print as code, not strings).
/// Contributions print their element through this writer and recurse into children via
/// .
///
public sealed class XmlCodeWriter
{
private readonly StringBuilder _text = new();
private readonly ElementRegistry _registry;
private readonly string _sourceName;
private readonly IRouteResourceResolver? _resources;
private int _indent;
internal XmlCodeWriter(ElementRegistry registry, CodeGenStyle style, string sourceName, IRouteResourceResolver? resources)
{
_registry = registry;
Style = style;
_sourceName = sourceName;
_resources = resources;
}
///
/// Reads a file the way the loader would (schema bodies referenced by file=): the
/// generator inlines the content into the generated code.
///
/// No probed location holds the file; the message names each one.
public string ReadResource(string reference)
{
if (Path.IsPathRooted(reference) || _resources is null)
return File.ReadAllText(reference);
var path = _resources.Resolve(reference)
?? throw new FileNotFoundException(
$"resource '{reference}' not found. Searched: {_resources.DescribeSearch(reference)}.", reference);
return File.ReadAllText(path);
}
///
/// Finds a file the way does without reading it, for an element the generated code keeps
/// as a file reference (<validateXsd file="…"/>): a missing file still fails the generation.
///
/// No probed location holds the file; the message names each one.
internal string LocateResource(string reference)
{
if (Path.IsPathRooted(reference) || _resources is null)
return File.Exists(reference) ? reference : throw new FileNotFoundException($"resource '{reference}' not found.", reference);
return _resources.Resolve(reference)
?? throw new FileNotFoundException(
$"resource '{reference}' not found. Searched: {_resources.DescribeSearch(reference)}.", reference);
}
/// The requested output style.
public CodeGenStyle Style { get; }
internal string Text => _text.ToString();
// ── lines and indentation ────────────────────────────────────────────────
/// Writes one line at the current indentation.
public XmlCodeWriter Line(string text)
{
_text.Append(' ', _indent * 4).Append(text).Append('\n');
return this;
}
/// Writes an empty line.
public XmlCodeWriter BlankLine()
{
_text.Append('\n');
return this;
}
/// Increases indentation for a nested block.
public XmlCodeWriter Indent() { _indent++; return this; }
/// Decreases indentation.
public XmlCodeWriter Outdent() { _indent--; return this; }
///
/// In machine style, a #line directive pointing diagnostics at the XML element
/// (Razor's trick, §2); a no-op in readable style. Directives ignore indentation.
///
public XmlCodeWriter MapTo(XElement element)
{
if (Style == CodeGenStyle.Machine && ((IXmlLineInfo)element).HasLineInfo())
_text.Append("#line ").Append(((IXmlLineInfo)element).LineNumber)
.Append(" \"").Append(_sourceName.Replace("\\", "/", StringComparison.Ordinal)).Append("\"\n");
return this;
}
// ── the statement model ──────────────────────────────────────────────────
// Generated code is STATEMENTS against receiver variables, never one long chain: a chain
// dies at the first scope closer (End* returns the IRouteDefinition facade and the concrete
// members vanish), which is exactly why the equivalence tests were written with
// variables. A scope introduces a fresh variable; a typed section (ofType) does too and
// simply never closes — the siblings keep using the parent receiver.
private readonly Stack _receivers = new();
private int _nextVar;
/// The current receiver variable the next statement targets.
public string Receiver => _receivers.Peek();
/// Pushes the root receiver (the route or builder-level definition variable).
public string PushRoot(string declaration, XElement element, string prefix)
{
var name = Fresh(prefix);
MapTo(element);
Line($"var {name} = {declaration};");
_receivers.Push(name);
return name;
}
/// Pops the current receiver.
public void PopReceiver() => _receivers.Pop();
private string Fresh(string prefix) => $"{prefix}{_nextVar++}";
/// One statement on the current receiver: recv.Verb(args);.
public XmlCodeWriter Verb(XElement element, string verb, params string[] args)
{
MapTo(element);
return Line($"{Receiver}.{verb}({string.Join(", ", args)});");
}
/// A configuration statement on the current receiver (no element mapping).
public XmlCodeWriter Config(string call) => Line($"{Receiver}.{call};");
///
/// Prints a scope: a fresh variable opened from the current receiver, the children as
/// statements on it, and the closing call. null = a typed
/// section that never closes (ofType).
///
public XmlCodeWriter Scope(XElement element, string openVerb, string[] args, string? closeVerb,
Action? body = null)
{
var name = Fresh("s");
MapTo(element);
Line($"var {name} = {Receiver}.{openVerb}({string.Join(", ", args)});");
_receivers.Push(name);
if (body is not null)
body(this);
else
PrintSteps(element);
_receivers.Pop();
if (closeVerb is not null)
Line($"{name}.{closeVerb}();");
return this;
}
/// Opens a branch child (when/catch) as a fresh variable on the current receiver.
public string OpenBranch(XElement element, string verb, params string[] args)
{
var name = Fresh("b");
MapTo(element);
Line($"var {name} = {Receiver}.{verb}({string.Join(", ", args)});");
if (element.Attribute("id")?.Value is { Length: > 0 })
throw new NotSupportedException(
$"id= on a branch child <{element.Name.LocalName}> is not supported by the code generator " +
"(the fluent DSL has no public seam to set a branch StepId before its steps).");
if (element.Attribute("description")?.Value is { Length: > 0 } description)
Line($"{name}.Description({Str(description)});");
_receivers.Push(name);
return name;
}
/// Closes a branch opened by .
public void CloseBranch(string name, string? closeVerb = null)
{
_receivers.Pop();
if (closeVerb is not null)
Line($"{name}.{closeVerb}();");
}
/// Prints every child element as a step through its registered contribution.
public XmlCodeWriter PrintSteps(XElement parent)
{
foreach (var child in parent.Elements())
PrintStep(child);
return this;
}
/// Prints one element through its registered contribution.
public XmlCodeWriter PrintStep(XElement element)
{
var contribution = _registry.Find(element.Name.LocalName)
?? throw new NotSupportedException(
$"element <{element.Name.LocalName}> is not in the registry — the parser would refuse it too.");
if (Style == CodeGenStyle.Readable && element.Attribute("description")?.Value is { Length: > 0 } description)
Line($"// {description}");
contribution.Print(element, this);
PrintIdentity(element);
return this;
}
///
/// The trailing identity the parser applies: Id()/Description() on the
/// receiver target its LAST output — the step just printed — exactly like the loader.
///
public XmlCodeWriter PrintIdentity(XElement element)
{
if (element.Attribute("id")?.Value is { Length: > 0 } id)
Config($"Id({Str(id)})");
if (element.Attribute("description")?.Value is { Length: > 0 } description)
Config($"Description({Str(description)})");
return this;
}
// ── literals (§3.2–3.3) ──────────────────────────────────────────────────
/// A C# string literal: plain when harmless, raw """…""" otherwise.
public static string Str(string value)
{
if (!value.Contains('"') && !value.Contains('\\') && !value.Contains('\n') && !value.Contains('\r'))
return $"\"{value}\"";
if (!value.Contains('\n') && !value.Contains('\r') && !value.Contains("\"\"\""))
return $"\"\"\"{value}\"\"\"";
var cleaned = value.Replace("\r", "", StringComparison.Ordinal);
return "\"\"\"\n" + cleaned + "\n\"\"\"";
}
/// An expression argument: the route-language string wrapped in Expr(...).
public static string Expr(string template) => $"Expr({Str(template)})";
/// A markup value= as code: a literal, or Placeholder("…") when it carries {{key}}.
public static string Value(string value)
=> PropertyPlaceholderResolver.HasPlaceholder(value) ? $"Placeholder({Str(value)})" : Str(value);
/// A as code (§3.3): round values by unit, otherwise Parse.
public static string Ts(TimeSpan value)
{
if (value.Ticks % TimeSpan.TicksPerSecond == 0 && value.TotalSeconds is >= 1 and < 1000000)
return $"TimeSpan.FromSeconds({value.TotalSeconds.ToString(CultureInfo.InvariantCulture)})";
if (value.Ticks % TimeSpan.TicksPerMillisecond == 0 && value.TotalMilliseconds is >= 1 and < 1000000)
return $"TimeSpan.FromMilliseconds({value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)})";
return $"TimeSpan.Parse({Str(value.ToString("c", CultureInfo.InvariantCulture))}, System.Globalization.CultureInfo.InvariantCulture)";
}
/// A typeof(...) when the type resolves now; the runtime lookup otherwise.
public static string TypeRef(string typeName)
{
var resolved = Components.Bean.DefaultBeanTypeResolver.Instance.Resolve(typeName);
return resolved?.FullName is { } fullName && !fullName.Contains('`')
? $"typeof(global::{fullName})"
: $"Type.GetType({Str(typeName)}, throwOnError: true)!";
}
/// A bool literal.
public static string Bool(bool value) => value ? "true" : "false";
/// An enum member reference.
public static string EnumRef(T value) where T : struct, Enum => $"{typeof(T).Name}.{value}";
}