TableTower/core/describe.gd
RobinFiredrake 44a814cba9 Plain Build display: plain rules on cards, pipes and tray, Why this?, check/collection/inputs visuals
- RulesView (ui/rules_view.gd): plain-or-text helpers over Describe, reading
  Main.rules_plain() when present (else StateStore, else plain; --rules=text
  for screenshots) and refreshing on Main.rules_view_changed.
- Cards: effect chips, router cases, option sources, show_if, loop rules,
  expression dice and variable kinds read in plain words. Build cards drop the
  inline effects / show_if / condition / details editors for plain chips;
  result text and names stay inline. Row clicks call main.select_result();
  the selected row gets a copper bar (set_selected_entry / inspector_selection).
- Check cards: 2D badge, the rule as a sentence, Success / Failure outlets.
  Collection cards: live members and "+ Add" (main.select_card). Inputs:
  a dashed "Input Tier · starts at 1" box.
- Pipe labels via Describe.pipe, nudged apart and cut to the gap.
- Tray: plain captions (inputs, checks, cases), effect lines from why facts,
  and a "Why this?" button opening a WhyPopover; hovers show the same reasons.
- Previews and the choice pop-up read conditions, effects and option sources
  in plain words. Style.rules_switch() for the Plain words / Text switch.
- Describe: empty text reads "empty" ("Loot is not empty").
- tests/test_plain_display.gd; option and choice tests pin the Text view
  where they check stored text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:30:55 -06:00

675 lines
24 KiB
GDScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class_name Describe
extends RefCounted
## Rules in plain words (docs/PLAIN.md §1): pure functions that turn stored
## rule text into short phrases, using value labels (§3). Anything they can't
## read comes back as the original text; they never fail and keep phrases
## short (MAX_LEN characters, else the original text or a cut with "…").
##
## Labels: a value's label is its variable card's name, else the collection
## it belongs to names it by the rest of its name ("@skill_gun_combat" in the
## Skills collection -> "Gun Combat"), else a pretty form of its name ("soc"
## -> "Soc"). Card inputs are labelled by their declared label. `board` may be
## null everywhere (pretty names only).
## Longest phrase before falling back to the original text (or a cut).
const MAX_LEN := 90
const MINUS := "−"
const _CHAIN_LABELS := {"answer": "Answer", "i": "Pass", "nat": "Natural roll", "total": "Total",
"effect": "Effect", "option": "Chosen option", "option_label": "Chosen option",
"option_value": "Chosen value"}
const _OPS := {"*": "×", "/": "÷", "-": MINUS, "==": "=", "!=": "≠", ">=": "≥", "<=": "≤"}
# ---------------------------------------------------------------- labels
## The label of a value: "@luck", "@skill_pilot", "@skill_*" (a collection
## or prefix: "Skills", or "Skill values" without a collection card), "@[…]"
## ("Chosen value"), or a chain name ("answer" -> "Answer", an input's label).
static func label(name: String, board: TowerBoard) -> String:
return _label(name, _labels(board))
## Label table for a board: {"vars": {name: label}, "stems": [[stem, label]]
## longest first, "inputs": {name: label}}.
static func _labels(board: TowerBoard) -> Dictionary:
var vars := {}
var stems: Array = []
var inputs := {}
if board != null:
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "":
var lab := Formatter.strip_tags(t.name).strip_edges()
if t.var_type == RollTable.VAR_COLLECTION:
stems.append([t.var_name, lab if lab != "" else RollContext.pretty_name(t.var_name)])
elif lab != "" and not vars.has(t.var_name):
vars[t.var_name] = lab
for inp: Dictionary in t.inputs:
var il := str(inp.get("label", "")).strip_edges()
if il != "" and not inputs.has(str(inp.get("name", ""))):
inputs[str(inp.get("name", ""))] = il
stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length())
return {"vars": vars, "stems": stems, "inputs": inputs}
static func _label(name: String, L: Dictionary) -> String:
var n := name.strip_edges()
if n.begins_with("@["):
return "Chosen value"
if n.begins_with("@"):
n = n.substr(1).to_lower()
if n.ends_with("*"):
var stem := n.trim_suffix("*").trim_suffix("_")
for sp: Array in L["stems"]:
if sp[0] == stem:
return sp[1]
return "%s values" % RollContext.pretty_name(stem)
if L["vars"].has(n):
return L["vars"][n]
for sp: Array in L["stems"]:
var pre := str(sp[0]) + "_"
if n.begins_with(pre) and n.length() > pre.length():
return RollContext.pretty_name(n.substr(pre.length()))
return RollContext.pretty_name(n)
if L["inputs"].has(n):
return L["inputs"][n]
if _CHAIN_LABELS.has(n):
return _CHAIN_LABELS[n]
return RollContext.pretty_name(n)
## The collection a value belongs to ({"stem", "label"}) or {}.
static func _collection_of(name: String, L: Dictionary) -> Dictionary:
var n := name.strip_edges().trim_prefix("@").to_lower()
for sp: Array in L["stems"]:
var pre := str(sp[0]) + "_"
if n.begins_with(pre):
return {"stem": sp[0], "label": sp[1]}
return {}
# ---------------------------------------------------------------- effects
## One effect statement in plain words: "@luck -= 1" -> "Luck −1",
## "@town = \"Millbrook\"" -> "Town = Millbrook", "reset @skill_*" -> "Clear
## all Skills", "@traits += \"Psionic\"" -> "Add Psionic to Traits",
## "@[option] += 1" -> "Chosen skill +1" when `table` is a pick card taking
## options from a collection (else "Chosen value +1").
static func effect(stmt: String, board: TowerBoard, table: RollTable = null) -> String:
return _effect(stmt, _labels(board), table)
## One phrase per statement of an effects field.
static func effects(text: String, board: TowerBoard, table: RollTable = null) -> Array[String]:
var L := _labels(board)
var out: Array[String] = []
for s in Effects.split(text):
out.append(_effect(s, L, table))
return out
static func _effect(stmt: String, L: Dictionary, table: RollTable) -> String:
var src := stmt.strip_edges()
var m := Builder.parse_effect(src)
if not m["ok"]:
return src
var v := str(m["var"])
var subj := _chosen(table, L) if v.begins_with("@[") else _label(v, L)
var amount := str(m["amount"])
var out := ""
match str(m["op"]):
"reset":
if v.ends_with("*"):
out = "Clear all " + _label(v, L)
elif L["vars"].has(v.trim_prefix("@")):
out = "Reset " + subj
else:
out = "Clear " + subj
"set":
out = "%s = %s" % [subj, _expr(amount, L)]
"add", "subtract":
var sub: bool = m["op"] == "subtract"
if amount.is_valid_float() and not amount.to_lower().contains("e") and not amount.to_lower().contains("n"):
var x: Variant = Expr.to_value(amount)
if x < 0:
sub = not sub
x = -x
out = "%s %s%s" % [subj, MINUS if sub else "+", Expr.format_value(x)]
else:
out = "%s %s %s" % [subj, MINUS if sub else "+", _expr(amount, L)]
"multiply":
out = "%s ×%s" % [subj, _compact(amount, L)]
"divide":
out = "%s ÷%s" % [subj, _compact(amount, L)]
"append":
out = "Add %s to %s" % [amount, subj]
"remove":
out = "Remove %s from %s" % [amount, subj]
return _short(out, src)
static func _compact(amount: String, L: Dictionary) -> String:
var t := Builder.tokens(amount)
var e := _expr(amount, L)
return e if t.size() == 1 else " " + e
## "Chosen skill" on a pick card whose options come from a collection, else
## "Chosen value".
static func _chosen(table: RollTable, L: Dictionary) -> String:
if table != null and table.is_dynamic():
var p := RollTable.parse_options_from(table.options_from)
if str(p["kind"]) == "prefix":
var stem := str(p["name"]).trim_suffix("_")
for sp: Array in L["stems"]:
if sp[0] == stem:
return "Chosen " + _singular(str(sp[1]).to_lower())
return "Chosen value"
static func _singular(s: String) -> String:
if s.length() > 3 and s.ends_with("s") and not s.ends_with("ss"):
return s.substr(0, s.length() - 1)
return s
# ---------------------------------------------------------------- conditions
## A condition in plain words: "@str >= 8" -> "Strength is 8 or more",
## "@x = 0 and @soc >= 9" -> "X is 0 and Social Standing is 9 or more",
## "has(@traits, \"Psionic\")" -> "Traits include Psionic". "" for an empty
## condition; the original text for anything Builder.parse_condition() can't
## read.
static func condition(expr: String, board: TowerBoard) -> String:
return _condition(expr, _labels(board))
static func _condition(expr: String, L: Dictionary) -> String:
var src := expr.strip_edges()
var m := Builder.parse_condition(src)
if not m["ok"]:
return src
var parts := PackedStringArray()
for c: Dictionary in m["clauses"]:
parts.append(_clause(c, L))
return _short((" %s " % m["join"]).join(parts), src)
static func _clause(c: Dictionary, L: Dictionary) -> String:
var subj := _label(str(c["var"]), L)
var cmp := str(c["cmp"])
match cmp:
"set":
return subj + " is set"
"unset":
return subj + " is not set"
"has":
return "%s include %s" % [subj, _value(str(c["value"]), L)]
return "%s %s" % [subj, _tail(cmp, str(c["value"]), L)]
## The comparison after a value name: "is 8 or more", "is at most 3", "is
## Aslan", "is not 0", "is more than 2", "is less than 2".
static func _tail(cmp: String, value: String, L: Dictionary) -> String:
var v := _value(value, L)
var num := Expr.is_number(value) or (value.begins_with("-") and Expr.is_number(value.substr(1)))
match cmp:
"eq":
return "is " + v
"ne":
return "is not " + v
"ge":
return ("is %s or more" % v) if num else "is at least " + v
"le":
return "is at most " + v
"gt":
return "is more than " + v
"lt":
return "is less than " + v
"has":
return "includes " + v
"set":
return "is set"
"unset":
return "is not set"
return "%s %s" % [cmp, v]
## A value token in words: numbers as they are, quoted text without quotes,
## @names and chain names by label, true/false as yes/no.
static func _value(tok: String, L: Dictionary) -> String:
var s := tok.strip_edges()
if s == "true":
return "yes"
if s == "false":
return "no"
if Builder.is_text_literal(s):
var u := Builder.unquote(s)
return u if u != "" else "empty"
if s.begins_with("-") and Expr.is_number(s.substr(1)):
return MINUS + s.substr(1)
if Expr.is_number(s):
return s
if s.begins_with("@") or Builder._is_word(s.substr(0, 1)):
return _label(s, L)
return s
# ---------------------------------------------------------------- dice
## A dice or count expression in plain words: "2d6 + dm(@str)" -> "2D +
## Strength modifier", "1d6 + tier" -> "1D + Tier", "@terms" -> "Terms".
## d6 dice read as "ND"; other dice as "dN" / "NdM". Text that can't be read
## comes back as it is.
static func dice(expr: String, board: TowerBoard) -> String:
return _expr(expr, _labels(board))
static func _expr(expr: String, L: Dictionary) -> String:
var src := expr.strip_edges()
if src == "":
return ""
var toks := Builder.tokens(src)
if toks.is_empty():
return src
var pieces: Array = [] # [kind, text]; kinds: val fn op neg ( ) ,
var k := 0
while k < toks.size():
var tk: Dictionary = toks[k]
var t := str(tk["t"])
var s := str(tk["s"])
var prevk := str(pieces.back()[0]) if not pieces.is_empty() else ""
# dm(x) with one value inside: "X modifier".
if t == "name" and s == "dm" and k + 3 < toks.size() and toks[k + 1]["s"] == "(" and toks[k + 3]["s"] == ")" \
and ["var", "name", "num"].has(str(toks[k + 2]["t"])):
pieces.append(["val", _value(str(toks[k + 2]["s"]), L) + " modifier"])
k += 4
continue
k += 1
match t:
"dice":
var dp := Builder.dice_parts(s)
if int(dp[1]) == 6:
pieces.append(["val", "%dD" % int(dp[0])])
elif int(dp[0]) == 1:
pieces.append(["val", "d%d" % int(dp[1])])
else:
pieces.append(["val", "%dd%d" % [int(dp[0]), int(dp[1])]])
"var", "prefix":
pieces.append(["val", _label(s, L)])
"name":
if k < toks.size() and toks[k]["s"] == "(":
pieces.append(["fn", s])
else:
pieces.append(["val", _value(s, L)])
"num":
pieces.append(["val", s])
"str":
pieces.append(["val", Builder.unquote(s)])
"kw":
pieces.append(["op", s])
_:
if s == "(" or s == ")" or s == ",":
pieces.append([s, s])
elif s == "-" and (prevk == "" or prevk == "op" or prevk == "(" or prevk == "," or prevk == "neg"):
pieces.append(["neg", MINUS])
else:
pieces.append(["op", _OPS.get(s, s)])
var out := ""
var prev := ""
for pc: Array in pieces:
var kind := str(pc[0])
var space := false
match kind:
"op":
space = out != ""
"val", "fn":
space = prev in ["op", ",", "val", ")"]
"(", "neg":
space = prev in ["op", ","]
if space:
out += " "
out += str(pc[1])
prev = kind
return _short(out, src)
# ---------------------------------------------------------------- cards and pipes
## A pick card's dynamic options source: "your Skills, level 1 or more",
## "your Contacts", "your Skill values, where Chosen option is not Pilot".
## "" for a card without options_from; the pattern as written when it's bad.
static func options(table: RollTable, board: TowerBoard) -> String:
if table == null or table.options_from.strip_edges() == "":
return ""
var L := _labels(board)
var p := RollTable.parse_options_from(table.options_from)
var s := ""
match str(p["kind"]):
"prefix":
s = "your " + _label("@%s*" % p["name"], L)
"list":
s = "your " + _label("@" + str(p["name"]), L)
_:
return table.options_from.strip_edges()
var w := _where(table.options_where, L)
if w != "":
s += ", " + w
return _short(s, table.options_description())
## The options_where filter as a short tail: "level 1 or more" for one
## comparison on option_value, else "where <condition>"; "" when empty.
static func _where(where: String, L: Dictionary) -> String:
var src := where.strip_edges()
if src == "":
return ""
var m := Builder.parse_condition(src)
if m["ok"] and (m["clauses"] as Array).size() == 1:
var c: Dictionary = m["clauses"][0]
if str(c["var"]) == "option_value" and ["eq", "ge", "le", "gt", "lt"].has(str(c["cmp"])):
var tail := _tail(str(c["cmp"]), str(c["value"]), L).trim_prefix("is ")
return "level " + tail
return "where " + _condition(src, L)
## A pipe's label in plain words, parts joined with " · ": its inputs ("Tier
## 3"), "only if <condition>" or "otherwise", the count ("×2", "×Terms") and
## "saves <name>". "" for a plain pipe.
static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> String:
if entry == null:
return ""
var L := _labels(board)
var parts := PackedStringArray()
var w := entry.with_for(target_id)
for nm: String in w:
parts.append("%s %s" % [_label(nm, L), _expr(str(w[nm]), L)])
var cond := entry.when_for(target_id)
if cond != "":
parts.append("only if " + _condition(cond, L))
elif entry.is_otherwise(target_id):
parts.append("otherwise")
var ce := entry.count_expr(target_id)
if ce != "":
parts.append("×" + _expr(ce, L))
elif entry.count_for(target_id) != 1:
parts.append("×%d" % entry.count_for(target_id))
var sv := entry.save_for(target_id)
if sv != "":
parts.append("saves " + _label(sv, L))
return " · ".join(parts)
## A check card: "Roll 2D + Strength modifier, need 8 or more" ("need 5 or
## less" for a roll-under check). "" for other kinds.
static func check(table: RollTable, board: TowerBoard) -> String:
if table == null or table.kind != RollTable.KIND_CHECK:
return ""
var L := _labels(board)
var roll := _expr(table.check_dice, L)
var mod := table.check_mod.strip_edges()
if mod != "":
var mt := Builder.tokens(mod)
if not mt.is_empty() and mt[0]["s"] == "-":
roll += " %s %s" % [MINUS, _expr(mod.substr(1), L)]
else:
roll += " + " + _expr(mod, L)
var target := _expr(table.check_target, L)
var num := Expr.is_number(table.check_target.strip_edges())
var need := ""
if table.check_cmp == "le":
need = ("%s or less" % target) if num else "at most " + target
else:
need = ("%s or more" % target) if num else "at least " + target
return _short("Roll %s, need %s" % [roll, need], "Roll %s %s vs %s" % [table.check_dice, mod, table.check_target])
# ---------------------------------------------------------------- why
## One trace fact (Roller node/step "why") as a sentence. Plain mode uses
## labels and words ("Skipped Tier 3 because Luck was 1 (needs 2 or more)");
## text mode (plain = false) shows the rules as written ("Skipped tier3: when
## @luck >= 2 was false (@luck = 1)"). Unknown facts give a short dump.
static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> String:
if fact == null:
return ""
var L := _labels(board)
var s := ""
match str(fact.get("type", "")):
"roll":
s = _why_roll(fact, plain)
"check":
s = _why_check(fact, L, plain)
"when":
s = _why_when(fact, board, L, plain)
"otherwise":
var to := _table(str(fact.get("to", "")), board, plain)
if bool(fact.get("result", false)):
s = "Took %s because no condition was true" % to if plain else "%s: otherwise, ran (no condition was true)" % to
else:
s = "Skipped %s because a condition was true" % to if plain else "%s: otherwise, skipped" % to
"case":
s = _why_case(fact, L, plain)
"show_if":
var h := int(fact.get("hidden", 0))
var parts := PackedStringArray()
if h > 0:
parts.append(("%d option hidden by its condition" if h == 1 else "%d options hidden by their conditions") % h)
if bool(fact.get("chosen_hidden", false)):
parts.append("the options from values were hidden")
s = ", and ".join(parts)
if s != "":
s = s.substr(0, 1).to_upper() + s.substr(1)
if not plain:
s = "show_if hid %d option(s)%s" % [h, ", and the Chosen entry" if bool(fact.get("chosen_hidden", false)) else ""]
"options_where":
var kept := int(fact.get("kept", 0))
var total := int(fact.get("total", 0))
if plain:
var from := str(fact.get("from", ""))
var p := RollTable.parse_options_from(from)
var what := _label("@%s*" % p["name"], L) if str(p["kind"]) == "prefix" else (_label("@" + str(p["name"]), L) if str(p["kind"]) == "list" else "options")
s = "Offered %d of %d %s (%s)" % [kept, total, what, _where(str(fact.get("expr", "")), L)]
else:
s = "options_where %s kept %d of %d" % [fact.get("expr", ""), kept, total]
"effect":
s = _why_effect(fact, L, plain)
"input":
var nm := str(fact.get("name", ""))
var val := Expr.format_value(fact.get("value"))
var from_pipe := str(fact.get("from", "")) == "pipe"
if plain:
s = "%s was %s (%s)" % [_label(nm, L), val, "from the pipe" if from_pipe else "default"]
else:
s = "input %s = %s (%s)" % [nm, val, "with" if from_pipe else "default"]
_:
s = JSON.stringify(fact)
if s.length() > MAX_LEN * 2:
s = s.substr(0, MAX_LEN * 2 - 1) + "…"
return s
static func _table(id: String, board: TowerBoard, plain: bool) -> String:
if not plain or board == null:
return id
var t := board.get_table(id)
if t == null:
return id
var n := Formatter.strip_tags(t.name).strip_edges()
return n if n != "" else id
## "3 + 4 = 7" (or "5" for one die).
static func _faces(faces: Variant) -> String:
if not (faces is Array) or (faces as Array).is_empty():
return ""
var parts := PackedStringArray()
var sum := 0.0
for f: Variant in faces:
parts.append(Expr.format_value(f))
sum += float(Expr.to_value(f)) if Expr.is_number(f) else 0.0
if parts.size() == 1:
return parts[0]
return "%s = %s" % [" + ".join(parts), Expr.format_value(sum)]
static func _nonzero(v: Variant) -> bool:
var n: Variant = Expr.to_value(v)
return Expr.is_number(n) and n != 0
static func _signed(v: Variant) -> String:
var n: Variant = Expr.to_value(v)
if not Expr.is_number(n):
return str(v)
return ("+" + Expr.format_value(n)) if n >= 0 else (MINUS + Expr.format_value(-n))
static func _why_roll(f: Dictionary, plain: bool) -> String:
var total := Expr.format_value(f.get("total"))
match str(f.get("pick", "dice")):
"weighted":
return "Rolled %s on %s" % [total, f.get("dice", "")] if plain else "roll %s: %s" % [f.get("dice", ""), total]
"card":
return "Drew card %s" % total if plain else "draw: card %s" % total
var faces := _faces(f.get("faces"))
if not plain:
var t := "roll %s: %s" % [f.get("dice", ""), faces if faces != "" else total]
if f.has("mod") and _nonzero(f["mod"]):
t += " %s = %s" % [_signed(f["mod"]).replace(MINUS, "-"), total]
return t
if faces == "":
return "Worked out %s" % total
var s := "Rolled " + faces
if f.has("mod") and _nonzero(f["mod"]):
s += ", %s = %s" % [_signed(f["mod"]), total]
return s
static func _why_check(f: Dictionary, L: Dictionary, plain: bool) -> String:
var faces := _faces(f.get("faces"))
var nat := Expr.format_value(f.get("nat"))
var total := Expr.format_value(f.get("total"))
var target := Expr.format_value(f.get("target"))
var le := str(f.get("cmp", "ge")) == "le"
var ok := bool(f.get("success", false))
if not plain:
return "check %s%s vs %s (%s): %s %s = %s → %s" % [f.get("dice", ""),
(" + " + str(f.get("mod_expr", ""))) if str(f.get("mod_expr", "")) != "" else "", f.get("target_expr", target),
f.get("cmp", "ge"), nat, _signed(f.get("mod", 0)).replace(MINUS, "-"), total, "success" if ok else "failure"]
var s := "Rolled " + (faces if faces != "" else nat)
if _nonzero(f.get("mod", 0)):
s += ", %s = %s" % [_signed(f.get("mod", 0)), total]
s += ": needed %s or %s, %s" % [target, "less" if le else "more", "success" if ok else "failure"]
return s
## "Luck was 1 and Social Standing was 9" from a fact's values.
static func _values(values: Variant, L: Dictionary, plain: bool) -> String:
if not (values is Dictionary) or (values as Dictionary).is_empty():
return ""
var parts := PackedStringArray()
for key: Variant in values:
var nm := str(key)
var v: Variant = values[key]
if plain:
parts.append(("%s wasn't set" % _label(nm, L)) if v == null else "%s was %s" % [_label(nm, L), _shown(v)])
else:
parts.append("%s = %s" % [nm, "unset" if v == null else Expr.format_value(v)])
if not plain:
return ", ".join(parts)
if parts.size() == 1:
return parts[0]
return ", ".join(parts.slice(0, parts.size() - 1)) + " and " + parts[parts.size() - 1]
static func _shown(v: Variant) -> String:
var s := Expr.format_value(v)
return s if s != "" else "empty"
## "(needs 2 or more)" for one comparison on a value that was read, else
## "(rule: <condition>)".
static func _needs(expr: String, values: Variant, L: Dictionary) -> String:
var m := Builder.parse_condition(expr)
if m["ok"] and (m["clauses"] as Array).size() == 1:
var c: Dictionary = m["clauses"][0]
if values is Dictionary and (values as Dictionary).has(str(c["var"])):
var tail := _tail(str(c["cmp"]), str(c["value"]), L)
if tail.begins_with("is "):
tail = tail.substr(3)
elif tail.begins_with("includes "):
tail = "to include " + tail.substr(9)
return "(needs %s)" % tail
return "(rule: %s)" % _condition(expr, L)
static func _why_when(f: Dictionary, board: TowerBoard, L: Dictionary, plain: bool) -> String:
var to := _table(str(f.get("to", "")), board, plain)
var expr := str(f.get("expr", ""))
var ok := bool(f.get("result", false))
if not plain:
var t := "%s %s: when %s was %s" % ["Took" if ok else "Skipped", to, expr, "true" if ok else "false"]
if f.has("error"):
t = "Skipped %s: when %s failed: %s" % [to, expr, f["error"]]
var vals := _values(f.get("values"), L, false)
return t + (" (%s)" % vals if vals != "" else "")
if f.has("error"):
return "Skipped %s: its condition couldn't be worked out (%s)" % [to, f["error"]]
var vals2 := _values(f.get("values"), L, true)
var verb := "Took" if ok else "Skipped"
if vals2 == "":
return "%s %s: %s was %s" % [verb, to, _condition(expr, L), "true" if ok else "false"]
return "%s %s because %s %s" % [verb, to, vals2, _needs(expr, f.get("values"), L)]
static func _why_case(f: Dictionary, L: Dictionary, plain: bool) -> String:
var n := int(f.get("index", 0)) + 1
var expr := str(f.get("expr", ""))
var ok := bool(f.get("result", false))
if expr == "":
return "Otherwise (case %d): no case before it matched" % n if plain else "case %d: otherwise" % n
if not plain:
var t := "case %d: %s → %s" % [n, expr, "error: " + str(f["error"]) if f.has("error") else ("true" if ok else "false")]
var vals := _values(f.get("values"), L, false)
return t + (" (%s)" % vals if vals != "" else "")
if f.has("error"):
return "Case %d couldn't be worked out (%s)" % [n, f["error"]]
var vals2 := _values(f.get("values"), L, true)
var verb := "matched" if ok else "didn't match"
if vals2 == "":
return "Case %d %s: %s was %s" % [n, verb, _condition(expr, L), "true" if ok else "false"]
return "Case %d %s because %s %s" % [n, verb, vals2, _needs(expr, f.get("values"), L)]
static func _why_effect(f: Dictionary, L: Dictionary, plain: bool) -> String:
var v := str(f.get("var", ""))
var op := str(f.get("op", ""))
if not plain:
if f.has("count"):
return "reset %s (%s)" % [v, Expr.format_value(f["count"])]
return "%s %s: %s → %s" % [v, op, _raw(f.get("before")), _raw(f.get("after"))]
var lab := _label(v, L)
if f.has("count"):
return "Cleared all %s (%s)" % [lab, Expr.format_value(f["count"])]
var before: Variant = f.get("before")
var after: Variant = f.get("after")
if op == "reset" and after == null:
return "%s was cleared" % lab
if before == null:
return "%s became %s" % [lab, _shown(after)]
return "%s went from %s to %s" % [lab, _shown(before), _shown(after)]
static func _raw(v: Variant) -> String:
return "unset" if v == null else Expr.format_value(v)
# ---------------------------------------------------------------- helpers
## `s`, or when it's too long the original text (if that's shorter) or a cut.
static func _short(s: String, original: String) -> String:
if s.length() <= MAX_LEN:
return s
if original.length() <= MAX_LEN:
return original
return s.substr(0, MAX_LEN - 1) + "…"