TextDoc is the literal-text variant of the Doc data structure. It stores text without line-break characters, allowing that text to be appended directly while a pretty printer decides where optional breaks become spaces or new lines. section 9.3.1
TextDoc participates in formatting through a small set of simple behaviors:
- Its stored text contributes its length when Fits checks whether a document can remain on one line. section 9.3.3
- Pretty appends its text to a StringBuilder and updates the number of characters used on the current line. section 9.3.4
- It combines with OptBreakDoc, GroupDoc, IndentDoc, and ConcatDoc to describe formatting preferences without containing formatting decisions itself. section 9.3.1
Literal pieces in a formatted expression
A formatting document can represent Foo, ., Bar, parentheses, operators, and identifiers as separate TextDoc values. Combined with optional breaks and groups, these pieces produce outputs such as Foo.Bar(xx + yy * zz) at width 30 and a multiline form at narrower widths. section 9.3.1
Listing 9.1 The doc data structure
using System.Text;
abstract record class Doc
{
public static readonly int IndentSpaces = 4; #1
public static readonly Doc Empty = new TextDoc("");
public static readonly Doc Space = new OptBreakDoc(" ");
public static readonly Doc OptBreak = new OptBreakDoc("");
public static TextDoc Text(string text) => new TextDoc(text); #2
public static GroupDoc Group(Doc doc) => new GroupDoc(doc);
public static IndentDoc Indent(Doc doc) => new IndentDoc(doc);
public static ConcatDoc Concat(Doc left, Doc right) =>
new ConcatDoc(left, right);
public static ConcatDoc operator +(Doc left, Doc right) =>
Concat(left, right); #3
private bool Fits(int width) { ... }
public string Pretty(int width) { ... }
}
sealed record class TextDoc(string text) : Doc;
sealed record class OptBreakDoc(string text) : Doc;
sealed record class GroupDoc(Doc doc) : Doc;
sealed record class IndentDoc(Doc doc) : Doc;
sealed record class ConcatDoc(Doc left, Doc right) : Doc;
Inspect the immutable Doc hierarchy and the Text factory that creates TextDoc values. section 9.3.1
