/// The explorer's Stats pane, built top-down from expressions: children are
/// lazy variadic arguments, evaluated by their parent after it opens.
module (module) appThe explorer's Stats pane, built top-down from expressions: children are
lazy variadic arguments, evaluated by their parent after it opens.
app;
import (package) stdstd.(module) std.sumtypeSumType is a generic discriminated union implementation that uses
design-by-introspection to generate safe and efficient code. Its features
include:
Pattern matching.
Support for self-referential types.
Full attribute correctness (pure, @safe, @nogc, and nothrow are
inferred whenever possible).
A type-safe and memory-safe API compatible with DIP 1000 (scope).
No dependency on runtime type information (TypeInfo).
Compatibility with BetterC.
List of examples
Memory corruption (why assignment can be @system)
Source
std/sumtype.d
Examples
Basic usage
import std.math.operations : isClose;
struct Fahrenheit { double value; }
struct Celsius { double value; }
struct Kelvin { double value; }
alias Temperature = SumType!(Fahrenheit, Celsius, Kelvin);
// Construct from any of the member types.
Temperature t1 = Fahrenheit(98.6);
Temperature t2 = Celsius(100);
Temperature t3 = Kelvin(273);
// Use pattern matching to access the value.
Fahrenheit toFahrenheit(Temperature t)
{
return Fahrenheit(
t.match!(
(Fahrenheit f) => f.value,
(Celsius c) => c.value * 9.0/5 + 32,
(Kelvin k) => k.value * 9.0/5 - 459.4
)
);
}
assert(toFahrenheit(t1).value.isClose(98.6));
assert(toFahrenheit(t2).value.isClose(212));
assert(toFahrenheit(t3).value.isClose(32));
// Use ref to modify the value in place.
void freeze(ref Temperature t)
{
t.match!(
(ref Fahrenheit f) => f.value = 32,
(ref Celsius c) => c.value = 0,
(ref Kelvin k) => k.value = 273
);
}
freeze(t1);
assert(toFahrenheit(t1).value.isClose(32));
// Use a catch-all handler to give a default result.
bool isFahrenheit(Temperature t)
{
return t.match!(
(Fahrenheit f) => true,
_ => false
);
}
assert(isFahrenheit(t1));
assert(!isFahrenheit(t2));
assert(!isFahrenheit(t3));
Matching with an overload set
Instead of writing match handlers inline as lambdas, you can write them as
overloads of a function. An alias can be used to create an additional
overload for the SumType itself.
For example, with this overload set:
string handle(int n) { return "got an int"; }
string handle(string s) { return "got a string"; }
string handle(double d) { return "got a double"; }
alias handle = match!handle;
Usage would look like this:
alias ExampleSumType = SumType!(int, string, double);
ExampleSumType a = 123;
ExampleSumType b = "hello";
ExampleSumType c = 3.14;
assert(a.handle == "got an int");
assert(b.handle == "got a string");
assert(c.handle == "got a double");
Recursive SumTypes
This example makes use of the special placeholder type This to define a
recursive data type: an
abstract syntax tree for
representing simple arithmetic expressions.
import std.functional : partial;
import std.traits : EnumMembers;
import std.typecons : Tuple;
enum Op : string
{
Plus = "+",
Minus = "-",
Times = "*",
Div = "/"
}
// An expression is either
// - a number,
// - a variable, or
// - a binary operation combining two sub-expressions.
alias Expr = SumType!(
double,
string,
Tuple!(Op, "op", This*, "lhs", This*, "rhs")
);
// Shorthand for Tuple!(Op, "op", Expr*, "lhs", Expr*, "rhs"),
// the Tuple type above with Expr substituted for This.
alias BinOp = Expr.Types[2];
// Factory function for number expressions
Expr* num(double value)
{
return new Expr(value);
}
// Factory function for variable expressions
Expr* var(string name)
{
return new Expr(name);
}
// Factory function for binary operation expressions
Expr* binOp(Op op, Expr* lhs, Expr* rhs)
{
return new Expr(BinOp(op, lhs, rhs));
}
// Convenience wrappers for creating BinOp expressions
alias sum = partial!(binOp, Op.Plus);
alias diff = partial!(binOp, Op.Minus);
alias prod = partial!(binOp, Op.Times);
alias quot = partial!(binOp, Op.Div);
// Evaluate expr, looking up variables in env
double eval(Expr expr, double[string] env)
{
return expr.match!(
(double num) => num,
(string var) => env[var],
(BinOp bop)
{
double lhs = eval(*bop.lhs, env);
double rhs = eval(*bop.rhs, env);
final switch (bop.op)
{
static foreach (op; EnumMembers!Op)
{
case op:
return mixin("lhs" ~ op ~ "rhs");
}
}
}
);
}
// Return a "pretty-printed" representation of expr
string pprint(Expr expr)
{
import std.format : format;
return expr.match!(
(double num) => "%g".format(num),
(string var) => var,
(BinOp bop) => "(%s %s %s)".format(
pprint(*bop.lhs),
cast(string) bop.op,
pprint(*bop.rhs)
)
);
}
Expr* myExpr = sum(var("a"), prod(num(2), var("b")));
double[string] myEnv = ["a":3, "b":4, "c":7];
assert(eval(*myExpr, myEnv) == 11);
assert(pprint(*myExpr) == "(a + (2 * b))");
sumtype : (alias struct) app.SumType = std.sumtype.SumType(Types...) if (is(NoDuplicates!Types == Types) && (Types.length > 0))A tagged union that can hold a
single value from any of a specified set of types.
The value in a SumType can be operated on using pattern matching.
To avoid ambiguity, duplicate types are not allowed (but see the
"basic usage" example for a workaround).
The special type This can be used as a placeholder to create
self-referential types, just like with Algebraic. See the
"Recursive SumTypes" example for usage.
A SumType is initialized by default to hold the .init value of its
first member type, just like a regular union. The version identifier
SumTypeNoDefaultCtor can be used to disable this behavior.
SumType, (alias template) app.match = std.sumtype.match(handlers...)Calls a type-appropriate function with the value held in a SumType.
For each possible type the SumType can hold, the given handlers are
checked, in order, to see whether they accept a single argument of that type.
The first one that does is chosen as the match for that type. (Note that the
first match may not always be the most exact match.
See "Avoiding unintentional matches" for
one common pitfall.)
Every type must have a matching handler, and every handler must match at
least one type. This is enforced at compile time.
Handlers may be functions, delegates, or objects with opCall overloads. If
a function with more than one overload is given as a handler, all of the
overloads are considered as potential matches.
Templated handlers are also accepted, and will match any type for which they
can be implicitly instantiated.
(Remember that a function literal
without an explicit argument type is considered a template.)
If multiple SumTypes are passed to match, their values are passed to the
handlers as separate arguments, and matching is done for each possible
combination of value types. See "Multiple dispatch" for
an example.
match;
import (module) ui_sketchA compile-and-run sketch of sparkles:ui authoring, built top-down from
expressions*: children are D lazy variadic arguments,
Node column(ref Ui ui, NamedOnly = NamedOnly.init, int gap = 0, …,
NamedOnly children = NamedOnly.init, scope ChildFn[] children...)
so ui.column(gap: 1, children: a, b, c) reads like the inside-out form, but
the compiler wraps each of a, b, c in a delegate literal. column opens
its element (appended, pushed on the open stack, its env pushed), calls each
child delegate in order, then closes: the fit size is computed from the
children right there (Clay's CloseElement) and the env pops.
A child's identity is its parent's id mixed with its argument position: a
ternary with Node.none keeps every later sibling's position, so an if
never shifts identity. mapKeyed splices a keyed run of rows into the one
argument position it occupies; each row's id mixes in its key.
The scope lazy variadic must not allocate a closure in the caller. Stock
DMD 2.115 / LDC 1.43 do allocate one ("allocates closure … with the GC"), so
@nogc views need the frontend fix for it (dlang/dmd#22885; see README.md).
Nothing here lays out or paints. Every name is a proposal.
ui_sketch;
// ── the app's model and messages ───────────────────────────────────────────
struct (struct) app.MemberRowMemberRow { (alias) object.string = stringstring (field) string app.MemberRow.namename; (alias) object.string = stringstring (field) string app.MemberRow.valuevalue; }
struct (struct) app.StatsStats { bool (field) bool app.Stats.hashOnEdithashOnEdit; int (field) int app.Stats.debounceMsdebounceMs; }
struct (struct) app.IdsViewIdsView { bool (field) bool app.IdsView.computingcomputing; (alias) object.string = stringstring (field) string app.IdsView.queryquery; const((struct) app.MemberRowMemberRow)[] (field) const(app.MemberRow)[] app.IdsView.rowsrows; }
struct (struct) app.ModelModel { (struct) app.StatsStats (field) app.Stats app.Model.statsstats; (struct) app.IdsViewIdsView (field) app.IdsView app.Model.idsids; bool (field) bool app.Model.tutorialtutorial; }
/// The Stats pane's own messages: it knows nothing of the explorer's.
struct (struct) app.ToggleHashThe Stats pane's own messages: it knows nothing of the explorer's.
ToggleHash {}
struct (struct) app.SetDebounceSetDebounce { int (field) int app.SetDebounce.msms; }
struct (struct) app.CopyNameCopyName { (alias) object.string = stringstring (field) string app.CopyName.namename; }
alias (alias) app.StatsMsg = std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName)StatsMsg = (struct) std.sumtype.SumType!(app.ToggleHash, app.SetDebounce, app.CopyName)A tagged union that can hold a
single value from any of a specified set of types.
The value in a SumType can be operated on using pattern matching.
To avoid ambiguity, duplicate types are not allowed (but see the
"basic usage" example for a workaround).
The special type This can be used as a placeholder to create
self-referential types, just like with Algebraic. See the
"Recursive SumTypes" example for usage.
A SumType is initialized by default to hold the .init value of its
first member type, just like a regular union. The version identifier
SumTypeNoDefaultCtor can be used to disable this behavior.
SumType!((struct) app.ToggleHashThe Stats pane's own messages: it knows nothing of the explorer's.
ToggleHash, (struct) app.SetDebounceSetDebounce, (struct) app.CopyNameCopyName);
/// The explorer's messages; the Stats pane's arrive wrapped.
struct (struct) app.QuitThe explorer's messages; the Stats pane's arrive wrapped.
Quit {}
alias (alias) app.ExplorerMsg = std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit)ExplorerMsg = (struct) std.sumtype.SumType!(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName), app.Quit)A tagged union that can hold a
single value from any of a specified set of types.
The value in a SumType can be operated on using pattern matching.
To avoid ambiguity, duplicate types are not allowed (but see the
"basic usage" example for a workaround).
The special type This can be used as a placeholder to create
self-referential types, just like with Algebraic. See the
"Recursive SumTypes" example for usage.
A SumType is initialized by default to hold the .init value of its
first member type, just like a regular union. The version identifier
SumTypeNoDefaultCtor can be used to disable this behavior.
SumType!((alias) app.StatsMsg = std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName)StatsMsg, (struct) app.QuitThe explorer's messages; the Stats pane's arrive wrapped.
Quit);
alias (alias) app.liftStats = std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) app.__lambda_L26_C7(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) sm) pure nothrow @nogc @safeliftStats = (StatsMsg sm) => ExplorerMsg(sm);
// ── a composite: one expression, children evaluated top-down ───────────────
(struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node ui_sketch.Node app.statsPane(ref ui_sketch.Ui ui, in app.Stats s, in app.IdsView ids) pure nothrow @nogc @safestatsPane(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui, in (struct) app.StatsStats (parameter) const(app.Stats) ss, in (struct) app.IdsViewIdsView (parameter) const(app.IdsView) idsids) @safe pure nothrow @nogc
=> (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(gap: (parameter) ui_sketch.Ui uiui.ui_sketch.Env ui_sketch.Ui.env() const pure nothrow @nogc @safeStructural context, as resolved by the elements open around the caller.
env.(field) ui_sketch.Density ui_sketch.Env.densitydensity == (enum) ui_sketch.DensityDensity.(enum value) ui_sketch.Density.compact = 1compact ? 0 : 1, children:
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.row(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA horizontal stack.
row(gap: 2, children:
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(slot: (enum) ui_sketch.SlotSlot.(enum value) ui_sketch.Slot.heading = 1heading, text: "Stats"),
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.toggle(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), bool on = false, scope const(char)[] label = null, ui_sketch.MsgRef onPress = MsgRef(4294967295u)) pure nothrow @nogc @safeA switch; onPress is whatever message the caller wants on a press.
toggle(on: (parameter) const(app.Stats) ss.(field) bool app.Stats.hashOnEdithashOnEdit, label: "hash on edit",
onPress: (parameter) ui_sketch.Ui uiui.ui_sketch.MsgRef ui_sketch.on!(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName))(ref ui_sketch.Ui ui, std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) value) pure nothrow @nogc @safeA constant message, copied into the frame's table. Checked (debug, at run
time) against the open mapMsg scope: the child is evaluated inside it.
on((struct) std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName)StatsMsg(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) std.sumtype.SumType!(app.ToggleHash, app.SetDebounce, app.CopyName).this(app.ToggleHash value) pure nothrow @nogc ref @safeConstructs a SumType holding a specific value.
ToggleHash()))),
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.numberField(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int value = 0, scope const(char)[] unit = null, ui_sketch.MsgRef onChange = MsgRef(4294967295u)) pure nothrow @nogc @safeA number field; onChange carries the new value as an int payload.
numberField(value: (parameter) const(app.Stats) ss.(field) int app.Stats.debounceMsdebounceMs, unit: "ms",
onChange: (parameter) ui_sketch.Ui uiui.ui_sketch.MsgRef ui_sketch.on!(function (int v) pure nothrow @nogc @safe => SumType(Storage(ToggleHash(), , ), cast(ubyte)0u).this(SetDebounce(v)))(ref ui_sketch.Ui ui) pure nothrow @nogc @safeA message built from a component's payload. fn may not capture.
on!((int v) => StatsMsg(SetDebounce(v)))),
),
(parameter) const(app.IdsView) idsids.(field) bool app.IdsView.computingcomputing
? (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(slot: (enum) ui_sketch.SlotSlot.(enum value) ui_sketch.Slot.dim = 2dim, text: (parameter) ui_sketch.Ui uiui.const(char)[] ui_sketch.Ui.text!(core.interpolation.InterpolatedLiteral!"computing\xe2\x80\xa6 (query ", core.interpolation.InterpolatedExpression!"ids.query", string, core.interpolation.InterpolatedLiteral!")")(core.interpolation.InterpolationHeader header, core.interpolation.InterpolatedLiteral!"computing\xe2\x80\xa6 (query " __param_1, core.interpolation.InterpolatedExpression!"ids.query" __param_2, string __param_3, core.interpolation.InterpolatedLiteral!")" __param_4, core.interpolation.InterpolationFooter footer) pure nothrow @nogc return @safeFormats an IES into the frame's scratch (UI-Q2.1).
text(i"computing… (query $(ids.query))"))
: (struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node.(constant) ui_sketch.Node ui_sketch.Node.none = Node(4294967294u)An empty child: its argument position still counts, so the siblings
after it keep their identity whether or not it is shown.
none,
(parameter) const(app.IdsView) idsids.(field) const(app.MemberRow)[] app.IdsView.rowsrows
.ui_sketch.UiRange!(const(MemberRow)[]) ui_sketch.toUi!(const(app.MemberRow)[])(const(app.MemberRow)[] r, return ref ui_sketch.Ui ui) pure nothrow @nogc @safeA range bound to the builder. It offers mapKeyed and mapByIndex, and no
plain map: it is not an input range, so Phobos' map does not apply.
toUi((parameter) ui_sketch.Ui uiui)
.ui_sketch.Node app.statsPane.mapKeyed!((r) => r.name, (r) => ui.keyValue(name: r.name, value: r.value, onPress: ui.on(StatsMsg(CopyName(r.name)))), const(app.MemberRow)[])(ui_sketch.UiRange!(const(MemberRow)[]) r) pure nothrow @nogc @safeSplices one keyed row per element into the argument position it occupies:
no fragment node, so the rows are the parent's own children for layout (as
Clay's would be). It is itself a lazy child, so it runs while the parent is
open. A free function, not a Ui method: a method template taking a local
lambda by alias needs a dual context.
mapKeyed!(
r => r.name,
r => ui.keyValue(name: r.name, value: r.value,
onPress: ui.on(StatsMsg(CopyName(r.name)))),
),
// Structure chosen from context: the column above has opened, so this
// reads the env it is evaluated under (compact under the override).
(parameter) ui_sketch.Ui uiui.ui_sketch.Env ui_sketch.Ui.env() const pure nothrow @nogc @safeStructural context, as resolved by the elements open around the caller.
env.(field) ui_sketch.Density ui_sketch.Env.densitydensity == (enum) ui_sketch.DensityDensity.(enum value) ui_sketch.Density.comfortable = cast(ubyte)0ucomfortable
? (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(slot: (enum) ui_sketch.SlotSlot.(enum value) ui_sketch.Slot.dim = 2dim, text: "click a name to copy it")
: (struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node.(constant) ui_sketch.Node ui_sketch.Node.none = Node(4294967294u)An empty child: its argument position still counts, so the siblings
after it keep their identity whether or not it is shown.
none,
);
// ── the root composite ─────────────────────────────────────────────────────
(struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node ui_sketch.Node app.explorerView(ref ui_sketch.Ui ui, in app.Model m) pure nothrow @nogc @safeexplorerView(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui, in (struct) app.ModelModel (parameter) const(app.Model) mm) @safe pure nothrow @nogc
=> (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(children:
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(slot: (enum) ui_sketch.SlotSlot.(enum value) ui_sketch.Slot.heading = 1heading, text: (parameter) ui_sketch.Ui uiui.const(char)[] ui_sketch.Ui.text!(core.interpolation.InterpolatedLiteral!"members: ", core.interpolation.InterpolatedExpression!"m.ids.rows.length", ulong)(core.interpolation.InterpolationHeader header, core.interpolation.InterpolatedLiteral!"members: " __param_1, core.interpolation.InterpolatedExpression!"m.ids.rows.length" __param_2, ulong __param_3, core.interpolation.InterpolationFooter footer) pure nothrow @nogc return @safeFormats an IES into the frame's scratch (UI-Q2.1).
text(i"members: $(m.ids.rows.length)")),
// Was "deferred": now a plain call. The column opens (pushing compact
// and `disabled`) before its child slot runs, so the pane sees both.
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(env: (parameter) ui_sketch.Ui uiui.ui_sketch.Env ui_sketch.Ui.env() const pure nothrow @nogc @safeStructural context, as resolved by the elements open around the caller.
env.ui_sketch.EnvOverride ui_sketch.Env.withDensity(ui_sketch.Density d) const pure nothrow @nogc @safeAn override replacing density for a subtree.
withDensity((enum) ui_sketch.DensityDensity.(enum value) ui_sketch.Density.compact = 1compact), disabled: (parameter) const(app.Model) mm.(field) bool app.Model.tutorialtutorial, children:
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.mapMsg!(function (std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) sm) pure nothrow @nogc @safe => SumType(Storage(SumType(Storage(ToggleHash(), , ), cast(ubyte)0u), ), cast(ubyte)0u).this(sm))(ref ui_sketch.Ui ui, ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeLifts every message its child sends with fn. The child is lazy, so it is
evaluated inside the scope: each ``ui.on below sees From as the expected
type and checks against it right there.
mapMsg!std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) app.__lambda_L26_C7(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) sm) pure nothrow @nogc @safeliftStats(ui_sketch.Node app.statsPane(ref ui_sketch.Ui ui, in app.Stats s, in app.IdsView ids) pure nothrow @nogc @safestatsPane((parameter) ui_sketch.Ui uiui, (parameter) const(app.Model) mm.(field) app.Stats app.Model.statsstats, (parameter) const(app.Model) mm.(field) app.IdsView app.Model.idsids)),
),
// Was "eager": the same plain call, under the caller's env (comfortable).
// There is no longer any difference between the two placements.
ui_sketch.Node app.badOrGood(ref ui_sketch.Ui ui, in app.Model m) pure nothrow @nogc @safebadOrGood((parameter) ui_sketch.Ui uiui, (parameter) const(app.Model) mm),
// Was "memo": a memo element keyed by the arguments and the env.
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.mapMsg!(function (std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) sm) pure nothrow @nogc @safe => SumType(Storage(SumType(Storage(ToggleHash(), , ), cast(ubyte)0u), ), cast(ubyte)0u).this(sm))(ref ui_sketch.Ui ui, ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeLifts every message its child sends with fn. The child is lazy, so it is
evaluated inside the scope: each ``ui.on below sees From as the expected
type and checks against it right there.
mapMsg!std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) app.__lambda_L26_C7(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) sm) pure nothrow @nogc @safeliftStats((parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.memo!(statsPane, app.Stats, app.IdsView)(ref ui_sketch.Ui ui, ref const(app.Stats) __param_1, ref const(app.IdsView) __param_2) pure nothrow @nogc @safeA memo site (UI-Q3's seam): a memo element keyed by fn's arguments and the
env, then fn(ui, args) built as its one child. A real host compares the key
with last frame's element of the same id and, when equal, splices last
frame's subtree instead of calling fn.
memo!ui_sketch.Node app.statsPane(ref ui_sketch.Ui ui, in app.Stats s, in app.IdsView ids) pure nothrow @nogc @safestatsPane((parameter) const(app.Model) mm.(field) app.Stats app.Model.statsstats, (parameter) const(app.Model) mm.(field) app.IdsView app.Model.idsids)),
);
version (BadMissingMapMsgBadMissingMapMsg)
{
// The pane's `StatsMsg`s are sent where `ExplorerMsg` is expected. `ui.on`
// runs inside the explorer's column, so the check fires right there — at
// run time (debug): `ui` carries no message type to fail at compile time.
Node badOrGood(ref Ui ui, in Model m) @safe pure nothrow @nogc
=> statsPane(ui, m.stats, m.ids);
}
else
{
(struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node ui_sketch.Node app.badOrGood(ref ui_sketch.Ui ui, in app.Model m) pure nothrow @nogc @safebadOrGood(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui, in (struct) app.ModelModel (parameter) const(app.Model) mm) @safe pure nothrow @nogc
=> (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.mapMsg!(function (std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) sm) pure nothrow @nogc @safe => SumType(Storage(SumType(Storage(ToggleHash(), , ), cast(ubyte)0u), ), cast(ubyte)0u).this(sm))(ref ui_sketch.Ui ui, ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeLifts every message its child sends with fn. The child is lazy, so it is
evaluated inside the scope: each ``ui.on below sees From as the expected
type and checks against it right there.
mapMsg!std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) app.__lambda_L26_C7(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) sm) pure nothrow @nogc @safeliftStats(ui_sketch.Node app.statsPane(ref ui_sketch.Ui ui, in app.Stats s, in app.IdsView ids) pure nothrow @nogc @safestatsPane((parameter) ui_sketch.Ui uiui, (parameter) const(app.Model) mm.(field) app.Stats app.Model.statsstats, (parameter) const(app.Model) mm.(field) app.IdsView app.Model.idsids));
}
// ── subtrees as values ─────────────────────────────────────────────────────
/// A composite receiving a subtree from its caller: `content` is a lazy
/// builder, evaluated in the card's second slot, under the card's env.
(struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node ui_sketch.Node app.card(ref ui_sketch.Ui ui, string title, scope ui_sketch.Node delegate() pure nothrow @nogc @safe content) pure nothrow @nogc @safeA composite receiving a subtree from its caller: content is a lazy
builder, evaluated in the card's second slot, under the card's env.
card(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui, (alias) object.string = stringstring (parameter) string titletitle, scope (alias) ui_sketch.ChildFn = ui_sketch.Node delegate() pure nothrow @nogc @safeWhat a child slot holds: a lazy, non-capturing-by-GC subtree builder.
scope at every use site is what keeps it off the GC (with the patch).
ChildFn (parameter) ui_sketch.Node delegate() pure nothrow @nogc @safe contentcontent) @safe pure nothrow @nogc
=> (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(gap: 0, children:
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(slot: (enum) ui_sketch.SlotSlot.(enum value) ui_sketch.Slot.heading = 1heading, text: (parameter) string titletitle),
(parameter) ui_sketch.Node delegate() pure nothrow @nogc @safe contentcontent(),
);
/// A list whose rows a caller-supplied function builds; the list keys them.
(struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node ui_sketch.Node app.memberList(ref ui_sketch.Ui ui, in app.IdsView ids, scope ui_sketch.Node delegate(in app.MemberRow) pure nothrow @nogc @safe row) pure nothrow @nogc @safeA list whose rows a caller-supplied function builds; the list keys them.
memberList(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui, in (struct) app.IdsViewIdsView (parameter) const(app.IdsView) idsids,
scope (struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node delegate(in (struct) app.MemberRowMemberRow) @safe pure nothrow @nogc (parameter) ui_sketch.Node delegate(in app.MemberRow) pure nothrow @nogc @safe rowrow) @safe pure nothrow @nogc
=> (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(children: (parameter) const(app.IdsView) idsids.(field) const(app.MemberRow)[] app.IdsView.rowsrows.ui_sketch.UiRange!(const(MemberRow)[]) ui_sketch.toUi!(const(app.MemberRow)[])(const(app.MemberRow)[] r, return ref ui_sketch.Ui ui) pure nothrow @nogc @safeA range bound to the builder. It offers mapKeyed and mapByIndex, and no
plain map: it is not an input range, so Phobos' map does not apply.
toUi((parameter) ui_sketch.Ui uiui).ui_sketch.Node app.memberList.mapKeyed!((r) => r.name, (r) => row(r), const(app.MemberRow)[])(ui_sketch.UiRange!(const(MemberRow)[]) r) pure nothrow @nogc @safeSplices one keyed row per element into the argument position it occupies:
no fragment node, so the rows are the parent's own children for layout (as
Clay's would be). It is itself a lazy child, so it runs while the parent is
open. A free function, not a Ui method: a method template taking a local
lambda by alias needs a dual context.
mapKeyed!(r => r.name, r => row(r)));
(struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node ui_sketch.Node app.subtrees(ref ui_sketch.Ui ui, in app.IdsView ids, bool wide) pure nothrow @nogc @safesubtrees(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui, in (struct) app.IdsViewIdsView (parameter) const(app.IdsView) idsids, bool (parameter) bool widewide) @safe pure nothrow @nogc
{
// A subtree stored in a variable: a `scope` delegate, so no closure. It is
// *not* built here — only where it is placed, under that place's env.
scope (alias) ui_sketch.ChildFn = ui_sketch.Node delegate() pure nothrow @nogc @safeWhat a child slot holds: a lazy, non-capturing-by-GC subtree builder.
scope at every use site is what keeps it off the GC (with the patch).
ChildFn (local variable) ui_sketch.Node delegate() pure nothrow @nogc @safe namesnames = () => (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(children:
(parameter) const(app.IdsView) idsids.(field) const(app.MemberRow)[] app.IdsView.rowsrows.ui_sketch.UiRange!(const(MemberRow)[]) ui_sketch.toUi!(const(app.MemberRow)[])(const(app.MemberRow)[] r, return ref ui_sketch.Ui ui) pure nothrow @nogc @safeA range bound to the builder. It offers mapKeyed and mapByIndex, and no
plain map: it is not an input range, so Phobos' map does not apply.
toUi((parameter) ui_sketch.Ui uiui).ui_sketch.Node app.subtrees.__lambda_L109_C27.mapKeyed!((r) => r.name, (r) => ui.label(text: r.name), const(app.MemberRow)[])(ui_sketch.UiRange!(const(MemberRow)[]) r) pure nothrow @nogc @safeSplices one keyed row per element into the argument position it occupies:
no fragment node, so the rows are the parent's own children for layout (as
Clay's would be). It is itself a lazy child, so it runs while the parent is
open. A free function, not a Ui method: a method template taking a local
lambda by alias needs a dual context.
mapKeyed!(r => r.name, r => ui.label(text: r.name)));
return (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(gap: 1, children:
ui_sketch.Node app.card(ref ui_sketch.Ui ui, string title, scope ui_sketch.Node delegate() pure nothrow @nogc @safe content) pure nothrow @nogc @safeA composite receiving a subtree from its caller: content is a lazy
builder, evaluated in the card's second slot, under the card's env.
card((parameter) ui_sketch.Ui uiui, title: "(a) inline content", content: () => (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: (parameter) const(app.IdsView) idsids.(field) string app.IdsView.queryquery)),
ui_sketch.Node app.card(ref ui_sketch.Ui ui, string title, scope ui_sketch.Node delegate() pure nothrow @nogc @safe content) pure nothrow @nogc @safeA composite receiving a subtree from its caller: content is a lazy
builder, evaluated in the card's second slot, under the card's env.
card((parameter) ui_sketch.Ui uiui, title: "(b) stored content", content: (local variable) ui_sketch.Node delegate() pure nothrow @nogc @safe namesnames),
// Placed in one of two places: left when wide, right otherwise.
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.row(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA horizontal stack.
row(gap: 3, children:
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(children: (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: "left"), (parameter) bool widewide ? (local variable) ui_sketch.Node delegate() pure nothrow @nogc @safe namesnames() : (struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node.(constant) ui_sketch.Node ui_sketch.Node.none = Node(4294967294u)An empty child: its argument position still counts, so the siblings
after it keep their identity whether or not it is shown.
none),
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(env: (parameter) ui_sketch.Ui uiui.ui_sketch.Env ui_sketch.Ui.env() const pure nothrow @nogc @safeStructural context, as resolved by the elements open around the caller.
env.ui_sketch.EnvOverride ui_sketch.Env.withDensity(ui_sketch.Density d) const pure nothrow @nogc @safeAn override replacing density for a subtree.
withDensity((enum) ui_sketch.DensityDensity.(enum value) ui_sketch.Density.compact = 1compact), children:
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: "right"), (parameter) bool widewide ? (struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node.(constant) ui_sketch.Node ui_sketch.Node.none = Node(4294967294u)An empty child: its argument position still counts, so the siblings
after it keep their identity whether or not it is shown.
none : (local variable) ui_sketch.Node delegate() pure nothrow @nogc @safe namesnames()),
),
ui_sketch.Node app.memberList(ref ui_sketch.Ui ui, in app.IdsView ids, scope ui_sketch.Node delegate(in app.MemberRow) pure nothrow @nogc @safe row) pure nothrow @nogc @safeA list whose rows a caller-supplied function builds; the list keys them.
memberList((parameter) ui_sketch.Ui uiui, (parameter) const(app.IdsView) idsids, (in (struct) app.MemberRowMemberRow (parameter) const(app.MemberRow) rr) => (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: (parameter) const(app.MemberRow) rr.(field) string app.MemberRow.valuevalue)),
);
}
/// The hazard: a `Node` expression outside a children slot is built at once,
/// under whatever is open (here: the frame's root slot), not where it is used.
(struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node ui_sketch.Node app.misplaced(ref ui_sketch.Ui ui) pure nothrow @nogc @safeThe hazard: a Node expression outside a children slot is built at once,
under whatever is open (here: the frame's root slot), not where it is used.
misplaced(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui) @safe pure nothrow @nogc
{
auto (local variable) ui_sketch.Node earlyearly = (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: "early"); // built now, before the column
return (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(env: (parameter) ui_sketch.Ui uiui.ui_sketch.Env ui_sketch.Ui.env() const pure nothrow @nogc @safeStructural context, as resolved by the elements open around the caller.
env.ui_sketch.EnvOverride ui_sketch.Env.withDensity(ui_sketch.Density d) const pure nothrow @nogc @safeAn override replacing density for a subtree.
withDensity((enum) ui_sketch.DensityDensity.(enum value) ui_sketch.Density.compact = 1compact), children:
(parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: "a"),
(local variable) ui_sketch.Node earlyearly, // only the handle is passed: the slot returns an old node
);
}
// ── what the API rejects ───────────────────────────────────────────────────
int (thread local global) int app.impureCounterimpureCounter;
(struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node ui_sketch.Node app.impurePane(ref ui_sketch.Ui ui)impurePane(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui) => (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: (thread local global) int app.impureCounterimpureCounter++ ? "a" : "b");
struct (struct) app.StashStash { (alias) ui_sketch.ChildFn = ui_sketch.Node delegate() pure nothrow @nogc @safeWhat a child slot holds: a lazy, non-capturing-by-GC subtree builder.
scope at every use site is what keeps it off the GC (with the patch).
ChildFn (field) ui_sketch.Node delegate() pure nothrow @nogc @safe app.Stash.keptkept; }
void void app.rejected(ref ui_sketch.Ui ui, in app.IdsView ids) pure nothrow @nogc @saferejected(ref (struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (parameter) ui_sketch.Ui uiui, in (struct) app.IdsViewIdsView (parameter) const(app.IdsView) idsids) @safe pure nothrow @nogc
{
import (package) stdstd.(module) std.algorithmThis package implements generic algorithms oriented towards the processing of
sequences. Sequences processed by these functions define range-based
interfaces. See also Reference on ranges and
tutorial on ranges.
Algorithms are categorized into the following submodules:
Submodule Functions
| Searching |
all
any
balancedParens
boyerMooreFinder
canFind
commonPrefix
count
countUntil
endsWith
find
findAdjacent
findAmong
findSkip
findSplit
findSplitAfter
findSplitBefore
minCount
maxCount
minElement
maxElement
minIndex
maxIndex
minPos
maxPos
skipOver
startsWith
until
|
| Comparison |
among
castSwitch
clamp
cmp
either
equal
isPermutation
isSameLength
levenshteinDistance
levenshteinDistanceAndPath
max
min
mismatch
predSwitch
|
| Iteration |
cache
cacheBidirectional
chunkBy
cumulativeFold
each
filter
filterBidirectional
fold
group
joiner
map
mean
permutations
reduce
splitWhen
splitter
substitute
sum
uniq
|
| Sorting |
completeSort
isPartitioned
isSorted
isStrictlyMonotonic
ordered
strictlyOrdered
makeIndex
merge
multiSort
nextEvenPermutation
nextPermutation
nthPermutation
partialSort
partition
partition3
schwartzSort
sort
topN
topNCopy
topNIndex
|
| Set operations (setops) |
cartesianProduct
largestPartialIntersection
largestPartialIntersectionWeighted
multiwayMerge
multiwayUnion
setDifference
setIntersection
setSymmetricDifference
|
| Mutation |
bringToFront
copy
fill
initializeAll
move
moveAll
moveSome
moveEmplace
moveEmplaceAll
moveEmplaceSome
remove
reverse
strip
stripLeft
stripRight
swap
swapRanges
uninitializedFill
|
Many functions in this package are parameterized with a predicate.
The predicate may be any suitable callable type
(a function, a delegate, a functor, or a lambda), or a
compile-time string. The string may consist of any legal D
expression that uses the symbol a (for unary functions) or the
symbols a and b (for binary functions). These names will NOT
interfere with other homonym symbols in user code because they are
evaluated in a different context. The default for all binary
comparison predicates is "a == b" for unordered operations and
"a < b" for ordered operations.
Example
int[] a = ...;
static bool greater(int a, int b)
{
return a > b;
}
sort!greater(a); // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a); // predicate as string
// (no ambiguity with array name)
sort(a); // no predicate, "a < b" is implicit
Source
std/algorithm/package.d
algorithm : (alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)Implements the homonym function (also known as transform) present
in many languages of functional flavor. The call map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Params:
fun = one or more transformation functions
See_Also:
$(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))
map;
// Attributes are named-only: the first parameter is a private sentinel.
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label((enum) ui_sketch.SlotSlot.(enum value) ui_sketch.Slot.dim = 2dim, "x")));
// `children:` is required: with no attribute the child hits the first
// sentinel, after the last attribute it hits the second.
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column((parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: "x"))));
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.row(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA horizontal stack.
row(gap: 2, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: "x"))));
static assert(__traits(compiles, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.row(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA horizontal stack.
row(gap: 2, children: (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: "x"))));
// An IES expands to several arguments, so it cannot be one named argument.
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.label(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), ui_sketch.Slot slot = Slot.code, scope const(char)[] text = null) pure nothrow @nogc @safeOne run of text.
label(text: i"q $(ids.query)")));
// A bare range is not a child: lists go through `mapKeyed`/`mapByIndex`.
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(children: (parameter) const(app.IdsView) idsids.(field) const(app.MemberRow)[] app.IdsView.rowsrows)));
static assert(!__traits(compiles, (parameter) const(app.IdsView) idsids.(field) const(app.MemberRow)[] app.IdsView.rowsrows.ui_sketch.UiRange!(const(MemberRow)[]) ui_sketch.toUi!(const(app.MemberRow)[])(const(app.MemberRow)[] r, return ref ui_sketch.Ui ui) pure nothrow @nogc @safeA range bound to the builder. It offers mapKeyed and mapByIndex, and no
plain map: it is not an input range, so Phobos' map does not apply.
toUi((parameter) ui_sketch.Ui uiui).map!(r => ui.label(text: r.name))));
// A child is a `Node` expression, nothing else.
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(children: 42)));
// A payload lambda may not capture: nothing outlives the frame.
int (local variable) int locallocal = 3;
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.on!((int v) => StatsMsg(SetDebounce(v + local)))));
// A child slot is `@safe pure nothrow @nogc`: an impure composite is no child,
// and a memoised composite must be pure.
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(children: ui_sketch.Node app.impurePane(ref ui_sketch.Ui ui)impurePane((parameter) ui_sketch.Ui uiui))));
static assert(!__traits(compiles, (parameter) ui_sketch.Ui uiui.(template function) ui_sketch.memo(alias fn, Args...)(ref Ui ui, auto ref const Args args)memo!ui_sketch.Node app.impurePane(ref ui_sketch.Ui ui)impurePane()));
// A child builder is `scope`: it cannot be kept past the frame.
(struct) app.StashStash (local variable) app.Stash stashstash;
static assert(!__traits(compiles, (scope (alias) ui_sketch.ChildFn = ui_sketch.Node delegate() pure nothrow @nogc @safeWhat a child slot holds: a lazy, non-capturing-by-GC subtree builder.
scope at every use site is what keeps it off the GC (with the patch).
ChildFn (parameter) ui_sketch.Node delegate() pure nothrow @nogc @safe cc) @safe { (local variable) app.Stash stashstash.(field) ui_sketch.Node delegate() pure nothrow @nogc @safe app.Stash.keptkept = (parameter) ui_sketch.Node delegate() pure nothrow @nogc @safe cc; }));
// Not rejected — the hazard `misplaced` shows: a `Node` built outside a
// slot still type-checks as a child. Only the debug check reports it.
static assert(__traits(compiles, ((struct) ui_sketch.NodeA handle to a node this frame built. Children return it so a parent can
tell a child built in its slot from one built earlier (see evalChild).
Node (parameter) ui_sketch.Node earlyearly) => (parameter) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.column(ref ui_sketch.Ui ui, ui_sketch.NamedOnly _ = NamedOnly(), int gap = 0, bool disabled = false, ui_sketch.EnvOverride env = EnvOverride(false, Env(Layout.wide, Density.comfortable, false)), ui_sketch.NamedOnly _children = NamedOnly(), ui_sketch.Node delegate() pure nothrow @nogc @safe[] children...) pure nothrow @nogc @safeA vertical stack. env and disabled reach its whole subtree, which is
evaluated after it opens.
column(children: (parameter) ui_sketch.Node earlyearly)));
}
// ── run one frame, then deliver three events ───────────────────────────────
void void D main() @systemmain() @system
{
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Equivalent to $(D writef(fmt, args, '\n')).
writefln, (alias template) writeln = std.stdio.writeln(T...)(T args)Equivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Params:
args = the items to write to stdout
Throws:
In case of an I/O error, throws an $(LREF StdioException).
Example:
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
---
writeln;
import (package) stdstd.(module) std.rangeThis module defines the notion of a range. Ranges generalize the concept of
arrays, lists, or anything that involves sequential access. This abstraction
enables the same set of algorithms (see std.algorithm) to be used
with a vast variety of different concrete types. For example,
a linear search algorithm such as find
works not just for arrays, but for linked-lists, input files,
incoming network data, etc.
Guides
There are many articles available that can bolster understanding ranges:
Ali Çehreli's tutorial on ranges
for the basics of working with and creating range-based code.
Jonathan M. Davis Introduction to Ranges
talk at DConf 2015 a vivid introduction from its core constructs to practical advice.
The DLang Tour's chapter on ranges
for an interactive introduction.
H. S. Teoh's tutorial on
component programming with ranges for a real-world showcase of the influence
of range-based programming on complex algorithms.
Andrei Alexandrescu's article
On Iteration for conceptual aspect of ranges and the motivation
Submodules
This module has two submodules:
The std.range.primitives submodule
provides basic range functionality. It defines several templates for testing
whether a given object is a range, what kind of range it is, and provides
some common range operations.
The std.range.interfaces submodule
provides object-based interfaces for working with ranges via runtime
polymorphism.
The remainder of this module provides a rich set of range creation and
composition templates that let you construct new ranges out of existing ranges:
| chain |
Concatenates several ranges into a single range.
|
| choose |
Chooses one of two ranges at runtime based on a boolean condition.
|
| chooseAmong |
Chooses one of several ranges at runtime based on an index.
|
| chunks |
Creates a range that returns fixed-size chunks of the original
range.
|
| cycle |
Creates an infinite range that repeats the given forward range
indefinitely. Good for implementing circular buffers.
|
| drop |
Creates the range that results from discarding the first n
elements from the given range.
|
| dropBack |
Creates the range that results from discarding the last n
elements from the given range.
|
| dropExactly |
Creates the range that results from discarding exactly n
of the first elements from the given range.
|
| dropBackExactly |
Creates the range that results from discarding exactly n
of the last elements from the given range.
|
| dropOne |
Creates the range that results from discarding
the first element from the given range.
|
| dropBackOne |
Creates the range that results from discarding
the last element from the given range.
|
| enumerate |
Iterates a range with an attached index variable.
|
| evenChunks |
Creates a range that returns a number of chunks of
approximately equal length from the original range.
|
| frontTransversal |
Creates a range that iterates over the first elements of the
given ranges.
|
| generate |
Creates a range by successive calls to a given function. This
allows to create ranges as a single delegate.
|
| indexed |
Creates a range that offers a view of a given range as though
its elements were reordered according to a given range of indices.
|
| iota |
Creates a range consisting of numbers between a starting point
and ending point, spaced apart by a given interval.
|
| lockstep |
Iterates n ranges in lockstep, for use in a foreach
loop. Similar to zip, except that lockstep is designed
especially for foreach loops.
|
| nullSink |
An output range that discards the data it receives.
|
| only |
Creates a range that iterates over the given arguments.
|
| padLeft |
Pads a range to a specified length by adding a given element to
the front of the range. Is lazy if the range has a known length.
|
| padRight |
Lazily pads a range to a specified length by adding a given element to
the back of the range.
|
| radial |
Given a random-access range and a starting point, creates a
range that alternately returns the next left and next right element to
the starting point.
|
| recurrence |
Creates a forward range whose values are defined by a
mathematical recurrence relation.
|
| refRange |
Pass a range by reference. Both the original range and the RefRange
will always have the exact same elements.
Any operation done on one will affect the other.
|
| repeat |
Creates a range that consists of a single element repeated n
times, or an infinite range repeating that element indefinitely.
|
| retro |
Iterates a bidirectional range backwards.
|
| roundRobin |
Given n ranges, creates a new range that return the n
first elements of each range, in turn, then the second element of each
range, and so on, in a round-robin fashion.
|
| sequence |
Similar to recurrence, except that a random-access range is
created.
|
| slide |
Creates a range that returns a fixed-size sliding window
over the original range. Unlike chunks,
it advances a configurable number of items at a time,
not one chunk at a time.
|
| stride |
Iterates a range with stride n.
|
| tail |
Return a range advanced to within n elements of the end of
the given range.
|
| take |
Creates a sub-range consisting of only up to the first n
elements of the given range.
|
| takeExactly |
Like take, but assumes the given range actually has n
elements, and therefore also defines the length property.
|
| takeNone |
Creates a random-access range consisting of zero elements of the
given range.
|
| takeOne |
Creates a random-access range consisting of exactly the first
element of the given range.
|
| tee |
Creates a range that wraps a given range, forwarding along
its elements while also calling a provided function with each element.
|
| transposed |
Transposes a range of ranges.
|
| transversal |
Creates a range that iterates over the n'th elements of the
given random-access ranges.
|
| zip |
Given n ranges, creates a range that successively returns a
tuple of all the first elements, a tuple of all the second elements,
etc.
|
Sortedness
Ranges whose elements are sorted afford better efficiency with certain
operations. For this, the assumeSorted function can be used to
construct a SortedRange from a pre-sorted range. The sort function also conveniently
returns a SortedRange. SortedRange objects provide some additional
range operations that take advantage of the fact that the range is sorted.
Source
std/range/package.d
range : (alias template) repeat = std.range.repeat(T)(T value)Create a range which repeats one value.
Params:
value = the _value to repeat
n = the number of times to repeat value
Returns:
If n is not defined, an infinite random access range
with slicing.
If `n` is defined, a random access range with slicing.
repeat;
import (package) stdstd.(module) std.arrayFunctions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
Function Name Description
| array |
Returns a copy of the input in a newly allocated dynamic array.
|
| appender |
Returns a new Appender or RefAppender initialized with a given array.
|
| assocArray |
Returns a newly allocated associative array from a range/ranges of keys and values.
|
| byPair |
Construct a range iterating over an associative array by key/value tuples.
|
| insertInPlace |
Inserts into an existing array at a given position.
|
| join |
Concatenates a range of ranges into one array.
|
| minimallyInitializedArray |
Returns a new array of type T.
|
| replace |
Returns a new array with all occurrences of a certain subrange replaced.
|
| replaceFirst |
Returns a new array with the first occurrence of a certain subrange replaced.
|
| replaceInPlace |
Replaces all occurrences of a certain subrange and puts the result into a given array.
|
| replaceInto |
Replaces all occurrences of a certain subrange and puts the result into an output range.
|
| replaceLast |
Returns a new array with the last occurrence of a certain subrange replaced.
|
| replaceSlice |
Returns a new array with a given slice replaced.
|
| replicate |
Creates a new array out of several copies of an input array or range.
|
| sameHead |
Checks if the initial segments of two arrays refer to the same
place in memory.
|
| sameTail |
Checks if the final segments of two arrays refer to the same place
in memory.
|
| split |
Eagerly split a range or string into an array.
|
| staticArray |
Creates a new static array from given data.
|
| uninitializedArray |
Returns a new array of type T without initializing its elements.
|
Source
std/array.d
array : (alias template) join = std.array.join(RoR, R)(RoR ror, R sep) if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && isInputRange!R && (is(immutable(ElementType!(ElementType!RoR)) == immutable(ElementType!R)) || isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!(ElementType!R)))Eagerly concatenates all of the ranges in ror together (with the GC)
into one array using sep as the separator if present.
Params:
ror = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of input ranges
sep = An input range, or a single element, to join the ranges on
Returns:
An array of elements
See_Also:
For a lazy version, see $(REF joiner, std,algorithm,iteration)
join;
static immutable (struct) app.MemberRowMemberRow[2] (immutable global) immutable(app.MemberRow[2]) app.main.rowsrows = [(struct) app.MemberRowMemberRow("NarHash", "sha256-q2v…"), (struct) app.MemberRowMemberRow("castore", "b3:9f1…")];
const (local variable) const(app.Model) mm = (struct) app.ModelModel((struct) app.StatsStats(true, 300), (struct) app.IdsViewIdsView(true, "ab", (immutable global) immutable(app.MemberRow[2]) app.main.rowsrows[]), tutorial: true);
void void app.main.line(uint depth, string s) @safeline(uint (parameter) uint depthdepth, (alias) object.string = stringstring (parameter) string ss) @safe { void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" ".std.range.Take!(Repeat!string) std.range.repeat!string(string value, ulong n) pure nothrow @nogc @safeExamples
import std.algorithm.comparison : equal;
assert(5.repeat(4).equal([5, 5, 5, 5]));
repeat((parameter) uint depthdepth).string std.array.join!(std.range.Take!(Repeat!string))(std.range.Take!(Repeat!string) ror) pure nothrow @safeEagerly concatenates all of the ranges in ror together (with the GC)
into one array using sep as the separator if present.
Examples
assert(join(["hello", "silly", "world"], " ") == "hello silly world");
assert(join(["hello", "silly", "world"]) == "hellosillyworld");
assert(join([[1, 2, 3], [4, 5]], [72, 73]) == [1, 2, 3, 72, 73, 4, 5]);
assert(join([[1, 2, 3], [4, 5]]) == [1, 2, 3, 4, 5]);
const string[] arr = ["apple", "banana"];
assert(arr.join(",") == "apple,banana");
assert(arr.join() == "applebanana");
join, (parameter) string ss); }
void void app.main.diag(string s) @safediag((alias) object.string = stringstring (parameter) string ss) @safe { void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" ! ", (parameter) string ss); }
(struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (local variable) ui_sketch.Ui uiui; // on the stack: its arenas are a few tens of KiB
(local variable) ui_sketch.Ui uiui.void ui_sketch.Ui.expectMsg!(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit))() pure nothrow @nogc @safeThe app's message type (runApp!(view, update, Msg) in the real host).
expectMsg!ExplorerMsg;
cast(void) (local variable) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.Ui.frame(ui_sketch.Env env, ui_sketch.Node delegate() pure nothrow @nogc @safe[] root...) pure nothrow @nogc @safeBuilds the root view under env: the view is a lazy child, so env
and the app's message type are in place before it runs.
frame((struct) ui_sketch.EnvContext pushed by an element on open and popped on close. A child is
evaluated after its parent opens, so it reads the context directly.
Env((enum) ui_sketch.LayoutLayout.(enum value) ui_sketch.Layout.wide = cast(ubyte)0uwide, (enum) ui_sketch.DensityDensity.(enum value) ui_sketch.Density.comfortable = cast(ubyte)0ucomfortable), ui_sketch.Node app.explorerView(ref ui_sketch.Ui ui, in app.Model m) pure nothrow @nogc @safeexplorerView((local variable) ui_sketch.Ui uiui, (local variable) const(app.Model) mm));
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("── tree ──");
(local variable) ui_sketch.Ui uiui.void ui_sketch.Ui.dump!(void delegate(uint, string) @safe)(scope void delegate(uint, string) @safe write) @safeWrites every root (normally one) and its subtree, indented: kind,
text, fit size, id prefix, key, the env children see, [msg].
dump(&void app.main.line(uint depth, string s) @safeline);
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("── diagnostics ──");
(local variable) ui_sketch.Ui uiui.void ui_sketch.Ui.diagnostics!(void delegate(string) @safe)(scope void delegate(string) @safe write) @systemReports every diagnostic of the frame (debug builds only record them).
diagnostics(&void app.main.diag(string s) @safediag);
void std.stdio.writefln!(char, bool)(in char[] fmt, bool __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("messages type-check: %s (checked at each `ui.on`, at run time)", (local variable) ui_sketch.Ui uiui.bool ui_sketch.Ui.messagesTypeCheck() const pure nothrow @nogc @safeWhether the frame recorded no message-type diagnostic.
messagesTypeCheck);
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("── events ──");
void void app.main.deliver(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) e) @safedeliver((alias) app.ExplorerMsg = std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit)ExplorerMsg (parameter) std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) ee) @safe
{
(parameter) std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) ee.void std.sumtype.match!(function (std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName) sm) @safe
{
match(sm);
return ;
}
, function (app.Quit _) @safe
{
writeln("update: quit");
return ;
}
).match!(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit))(ref std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) __param_0) @safeCalls a type-appropriate function with the value held in a SumType.
For each possible type the SumType can hold, the given handlers are
checked, in order, to see whether they accept a single argument of that type.
The first one that does is chosen as the match for that type. (Note that the
first match may not always be the most exact match.
See "Avoiding unintentional matches" for
one common pitfall.)
Every type must have a matching handler, and every handler must match at
least one type. This is enforced at compile time.
Handlers may be functions, delegates, or objects with opCall overloads. If
a function with more than one overload is given as a handler, all of the
overloads are considered as potential matches.
Templated handlers are also accepted, and will match any type for which they
can be implicitly instantiated.
(Remember that a function literal
without an explicit argument type is considered a template.)
If multiple SumTypes are passed to match, their values are passed to the
handlers as separate arguments, and matching is done for each possible
combination of value types. See "Multiple dispatch" for
an example.
Examples
Avoiding unintentional matches
Sometimes, implicit conversions may cause a handler to match more types than
intended. The example below shows two solutions to this problem.
alias Number = SumType!(double, int);
Number x;
// Problem: because int implicitly converts to double, the double
// handler is used for both types, and the int handler never matches.
assert(!__traits(compiles,
x.match!(
(double d) => "got double",
(int n) => "got int"
)
));
// Solution 1: put the handler for the "more specialized" type (in this
// case, int) before the handler for the type it converts to.
assert(__traits(compiles,
x.match!(
(int n) => "got int",
(double d) => "got double"
)
));
// Solution 2: use a template that only accepts the exact type it's
// supposed to match, instead of any type that implicitly converts to it.
alias exactly(T, alias fun) = function (arg)
{
static assert(is(typeof(arg) == T));
return fun(arg);
};
// Now, even if we put the double handler first, it will only be used for
// doubles, not ints.
assert(__traits(compiles,
x.match!(
exactly!(double, d => "got double"),
exactly!(int, n => "got int")
)
));
Multiple dispatch
Pattern matching can be performed on multiple SumTypes at once by passing
handlers with multiple arguments. This usually leads to more concise code
than using nested calls to match, as show below.
struct Point2D { double x, y; }
struct Point3D { double x, y, z; }
alias Point = SumType!(Point2D, Point3D);
version (none)
{
// This function works, but the code is ugly and repetitive.
// It uses three separate calls to match!
@safe pure nothrow @nogc
bool sameDimensions(Point p1, Point p2)
{
return p1.match!(
(Point2D _) => p2.match!(
(Point2D _) => true,
_ => false
),
(Point3D _) => p2.match!(
(Point3D _) => true,
_ => false
)
);
}
}
// This version is much nicer.
@safe pure nothrow @nogc
bool sameDimensions(Point p1, Point p2)
{
alias doMatch = match!(
(Point2D _1, Point2D _2) => true,
(Point3D _1, Point3D _2) => true,
(_1, _2) => false
);
return doMatch(p1, p2);
}
Point a = Point2D(1, 2);
Point b = Point2D(3, 4);
Point c = Point3D(5, 6, 7);
Point d = Point3D(8, 9, 0);
assert( sameDimensions(a, b));
assert( sameDimensions(c, d));
assert(!sameDimensions(a, c));
assert(!sameDimensions(d, b));
match!(
(StatsMsg sm) => sm.match!(
(ToggleHash _) => writeln("update: stats ▸ toggle hash-on-edit"),
(SetDebounce d) => writefln("update: stats ▸ debounce = %s ms", d.ms),
(CopyName c) => writefln("update: stats ▸ copy %s", c.name),
),
(Quit _) => writeln("update: quit"),
);
}
version (BadMissingMapMsgBadMissingMapMsg)
writeln("(not dispatching: the frame failed its message check)");
else
{
// The first toggle is the compact (formerly deferred) pane's.
(local variable) ui_sketch.Ui uiui.void ui_sketch.Ui.dispatch!(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit))(ui_sketch.Node target, scope void delegate(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit)) @safe deliver, int payload = 0) @safeDelivers the message target sends, as the app's Msg: decoded, then
mapped by every mapMsg between target and the root.
dispatch!ExplorerMsg((local variable) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.Ui.find(string kind, scope const(char)[] text, uint from = 0u) pure nothrow @nogc @safeThe first node of kind whose text is text (the demo's hit test).
find("toggle", "hash on edit"), &void app.main.deliver(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) e) @safedeliver);
(local variable) ui_sketch.Ui uiui.void ui_sketch.Ui.dispatch!(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit))(ui_sketch.Node target, scope void delegate(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit)) @safe deliver, int payload = 0) @safeDelivers the message target sends, as the app's Msg: decoded, then
mapped by every mapMsg between target and the root.
dispatch!ExplorerMsg((local variable) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.Ui.find(string kind, scope const(char)[] text, uint from = 0u) pure nothrow @nogc @safeThe first node of kind whose text is text (the demo's hit test).
find("numberField", "ms"), &void app.main.deliver(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) e) @safedeliver, payload: 500);
(local variable) ui_sketch.Ui uiui.void ui_sketch.Ui.dispatch!(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit))(ui_sketch.Node target, scope void delegate(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit)) @safe deliver, int payload = 0) @safeDelivers the message target sends, as the app's Msg: decoded, then
mapped by every mapMsg between target and the root.
dispatch!ExplorerMsg((local variable) ui_sketch.Ui uiui.ui_sketch.Node ui_sketch.Ui.find(string kind, scope const(char)[] text, uint from = 0u) pure nothrow @nogc @safeThe first node of kind whose text is text (the demo's hit test).
find("keyValue", "castore"), &void app.main.deliver(std.sumtype.SumType!(SumType!(ToggleHash, SetDebounce, CopyName), Quit) e) @safedeliver);
}
foreach ((parameter) bool widewide; [true, false])
{
(struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (local variable) ui_sketch.Ui subsub;
(local variable) ui_sketch.Ui subsub.void ui_sketch.Ui.expectMsg!(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName))() pure nothrow @nogc @safeThe app's message type (runApp!(view, update, Msg) in the real host).
expectMsg!StatsMsg;
cast(void) (local variable) ui_sketch.Ui subsub.ui_sketch.Node ui_sketch.Ui.frame(ui_sketch.Env env, ui_sketch.Node delegate() pure nothrow @nogc @safe[] root...) pure nothrow @nogc @safeBuilds the root view under env: the view is a lazy child, so env
and the app's message type are in place before it runs.
frame((struct) ui_sketch.EnvContext pushed by an element on open and popped on close. A child is
evaluated after its parent opens, so it reads the context directly.
Env((enum) ui_sketch.LayoutLayout.(enum value) ui_sketch.Layout.wide = cast(ubyte)0uwide, (enum) ui_sketch.DensityDensity.(enum value) ui_sketch.Density.comfortable = cast(ubyte)0ucomfortable), ui_sketch.Node app.subtrees(ref ui_sketch.Ui ui, in app.IdsView ids, bool wide) pure nothrow @nogc @safesubtrees((local variable) ui_sketch.Ui subsub, (local variable) const(app.Model) mm.(field) app.IdsView app.Model.idsids, (local variable) bool widewide));
void std.stdio.writefln!(char, bool)(in char[] fmt, bool __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("── subtrees as values (wide = %s) ──", (local variable) bool widewide);
(local variable) ui_sketch.Ui subsub.void ui_sketch.Ui.dump!(void delegate(uint, string) @safe)(scope void delegate(uint, string) @safe write) @safeWrites every root (normally one) and its subtree, indented: kind,
text, fit size, id prefix, key, the env children see, [msg].
dump(&void app.main.line(uint depth, string s) @safeline);
(local variable) ui_sketch.Ui subsub.void ui_sketch.Ui.diagnostics!(void delegate(string) @safe)(scope void delegate(string) @safe write) @systemReports every diagnostic of the frame (debug builds only record them).
diagnostics(&void app.main.diag(string s) @safediag);
}
{
(struct) ui_sketch.UiThe frame's builder, on its owner's stack (or heap-owned for big frames) and
passed ref. Storage as in the inside-out sketch: append-only HeapBuffers
for nodes and messages, a TextPool for text, an InlineBuffer scratch for
ui.text, and an InSituRegion for constant messages' bytes.
Ui (local variable) ui_sketch.Ui badbad;
(local variable) ui_sketch.Ui badbad.void ui_sketch.Ui.expectMsg!(std.sumtype.SumType!(ToggleHash, SetDebounce, CopyName))() pure nothrow @nogc @safeThe app's message type (runApp!(view, update, Msg) in the real host).
expectMsg!StatsMsg;
cast(void) (local variable) ui_sketch.Ui badbad.ui_sketch.Node ui_sketch.Ui.frame(ui_sketch.Env env, ui_sketch.Node delegate() pure nothrow @nogc @safe[] root...) pure nothrow @nogc @safeBuilds the root view under env: the view is a lazy child, so env
and the app's message type are in place before it runs.
frame((struct) ui_sketch.EnvContext pushed by an element on open and popped on close. A child is
evaluated after its parent opens, so it reads the context directly.
Env((enum) ui_sketch.LayoutLayout.(enum value) ui_sketch.Layout.wide = cast(ubyte)0uwide, (enum) ui_sketch.DensityDensity.(enum value) ui_sketch.Density.comfortable = cast(ubyte)0ucomfortable), ui_sketch.Node app.misplaced(ref ui_sketch.Ui ui) pure nothrow @nogc @safeThe hazard: a Node expression outside a children slot is built at once,
under whatever is open (here: the frame's root slot), not where it is used.
misplaced((local variable) ui_sketch.Ui badbad));
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("── hazard: a Node built outside a children slot ──");
(local variable) ui_sketch.Ui badbad.void ui_sketch.Ui.dump!(void delegate(uint, string) @safe)(scope void delegate(uint, string) @safe write) @safeWrites every root (normally one) and its subtree, indented: kind,
text, fit size, id prefix, key, the env children see, [msg].
dump(&void app.main.line(uint depth, string s) @safeline);
(local variable) ui_sketch.Ui badbad.void ui_sketch.Ui.diagnostics!(void delegate(string) @safe)(scope void delegate(string) @safe write) @systemReports every diagnostic of the frame (debug builds only record them).
diagnostics(&void app.main.diag(string s) @safediag);
}
}