Merge branch 'worktree-agent-a0e26080a92828227' into pipe-board

This commit is contained in:
RobinFiredrake 2026-11-08 12:14:05 -06:00
commit 51f2cc9e6d
8 changed files with 852 additions and 0 deletions

256
core/formatter.gd Normal file
View file

@ -0,0 +1,256 @@
class_name Formatter
extends RefCounted
## BBCode helpers for Godot 4 RichTextLabel text: closing open tags, removing
## tags for plain-text spots, export without internal markers, and the allowed-tag
## filter for imported files.
##
## A "tag" here is only a tag Godot's RichTextLabel recognizes (see KNOWN_TAGS).
## Anything else in brackets, such as [x] or [optional], is ordinary text: Godot
## shows it as typed, and every function here leaves it alone.
##
## Internal markers (added by TextExpander, never typed by users) are url tags
## whose parameter starts with one of INTERNAL_META_PREFIXES, for example
## [url=table:loot]…[/url] or [url=missing:Gems]⚠ Gems[/url].
## Every tag name Godot 4's RichTextLabel parses.
const KNOWN_TAGS: Array[String] = [
"b", "i", "u", "s", "code", "char", "p", "center", "left", "right", "fill",
"indent", "url", "hint", "img", "font", "font_size", "opentype_features", "otf",
"lang", "dropcap", "color", "bgcolor", "fgcolor", "outline_size", "outline_color",
"table", "cell", "ul", "ol", "lb", "rb", "br", "hr", "lrm", "rlm", "lre", "rle",
"lro", "rlo", "pdf", "alm", "lri", "rli", "fsi", "pdi", "zwj", "zwnj", "wj", "shy",
"wave", "tornado", "shake", "fade", "rainbow", "pulse",
]
## Tags that stand alone and never take a closing tag.
const STANDALONE_TAGS: Array[String] = [
"lb", "rb", "br", "hr", "char", "lrm", "rlm", "lre", "rle", "lro", "rlo", "pdf",
"alm", "lri", "rli", "fsi", "pdi", "zwj", "zwnj", "wj", "shy",
]
## Tags kept by sanitize_import(). Godot lists have no item tag: inside [ul]/[ol]
## each line is one item.
const IMPORT_ALLOWED_TAGS: Array[String] = [
"b", "i", "u", "s", "code", "color", "font_size", "ul", "ol",
"center", "left", "right", "fill", "indent", "lb", "rb",
]
## url parameters with these prefixes are TextExpander's internal markers.
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:"]
## Matches one tag: [name], [/name], [name=param] or [name key=value ...].
## Parameters may contain quoted strings, so [url={"a":1}] is one tag.
const _TAG_PATTERN := "\\[(/?)([a-z_]+)((?:=|\\s)(?:\"[^\"\\n]*\"|[^\\[\\]\"\\n])*)?\\]"
static var _tag_re: RegEx = null
static var _param_res: Dictionary = {}
## Splits text into tokens, in order. Each token is a Dictionary:
## kind: "text" | "open" | "close" | "single"
## raw: String (the exact source text of the token)
## name: String (tag name, "" for text)
## param: String (everything after the name, such as "=red" or " bullet=*", "" if none)
static func tokenize(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var pos: int = 0
for m: RegExMatch in _tag_regex().search_all(text):
var name: String = m.get_string(2)
if not KNOWN_TAGS.has(name):
continue
var closing: bool = m.get_string(1) == "/"
var param: String = m.get_string(3)
if closing and param != "":
continue
if m.get_start() > pos:
out.append(_text_token(text.substr(pos, m.get_start() - pos)))
var kind: String = "close" if closing else ("single" if STANDALONE_TAGS.has(name) else "open")
out.append({"kind": kind, "raw": m.get_string(), "name": name, "param": param})
pos = m.get_end()
if pos < text.length():
out.append(_text_token(text.substr(pos)))
return out
## Returns the known tag that starts exactly at `pos`, as a token Dictionary
## (see tokenize), or an empty Dictionary when there is none.
static func tag_at(text: String, pos: int) -> Dictionary:
var m: RegExMatch = _tag_regex().search(text, pos)
if m == null or m.get_start() != pos:
return {}
var name: String = m.get_string(2)
if not KNOWN_TAGS.has(name):
return {}
var closing: bool = m.get_string(1) == "/"
if closing and m.get_string(3) != "":
return {}
var kind: String = "close" if closing else ("single" if STANDALONE_TAGS.has(name) else "open")
return {"kind": kind, "raw": m.get_string(), "name": name, "param": m.get_string(3)}
## Closes every tag left open at the end of `text`, so one entry's formatting
## can't spill into the rest of a result. A closing tag that skips over inner open
## tags ([b][i]x[/b]) first closes the inner ones. A closing tag with no matching
## open tag is escaped ([lb]/b]) so it can't close an outer tag from another entry.
static func close_open_tags(text: String) -> String:
var out: String = ""
var stack: Array[String] = []
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if kind == "open":
stack.append(name)
out += t["raw"]
elif kind == "close":
var at: int = stack.rfind(name)
if at < 0:
out += "[lb]" + (t["raw"] as String).substr(1)
continue
while stack.size() - 1 > at:
out += "[/%s]" % stack.pop_back()
stack.pop_back()
out += t["raw"]
else:
out += t["raw"]
while not stack.is_empty():
out += "[/%s]" % stack.pop_back()
return out
## Plain text for window titles, search, autocomplete and "Copy as text".
## Removes every known tag, turns [lb]/[rb] into brackets, [br] into a newline and
## [char=XXXX] into its character, drops [img] paths, and keeps unknown bracket
## text such as [x]. Internal markers become readable: a missing-table marker
## reads "⚠ Gems (missing table)", an unset variable "{hero?}".
static func strip_tags(text: String) -> String:
var out: String = ""
var urls: Array[String] = []
var in_img: int = 0
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if kind == "text":
if in_img == 0:
out += t["raw"]
elif kind == "single":
match name:
"lb": out += "["
"rb": out += "]"
"br": out += "\n"
"char":
var code: String = (t["param"] as String).trim_prefix("=").strip_edges()
if code.is_valid_hex_number():
out += String.chr(code.hex_to_int())
elif name == "img":
in_img = maxi(0, in_img + (1 if kind == "open" else -1))
elif name == "url":
if kind == "open":
urls.append(_meta_of(t["param"]))
elif not urls.is_empty():
if (urls.pop_back() as String).begins_with("missing:"):
out += " (missing table)"
return out
## Formatted text for "Copy as BBCode": keeps the user's formatting but removes
## the internal [url=table:/var:/missing:/unset:/deep:] wrappers (keeping the text
## inside them).
static func to_export_bbcode(text: String) -> String:
var out: String = ""
var urls: Array[bool] = []
for t: Dictionary in tokenize(text):
if t["name"] == "url":
if t["kind"] == "open":
var internal: bool = is_internal_meta(_meta_of(t["param"]))
urls.append(internal)
if internal:
continue
elif not urls.is_empty() and urls.pop_back():
continue
out += t["raw"]
return out
## Cleans text from an imported file. Only IMPORT_ALLOWED_TAGS survive, and only
## with harmless parameters ([color=red], [color=#ff0000], [font_size=20],
## [ul bullet=*], [ol type=a]). Every other tag is removed but its text is kept,
## except [img]…[/img], whose content (a path) is removed too. This means imported
## text can't load files, open links or forge internal markers. Unknown bracket
## text like [x] is kept. Open tags are closed at the end.
static func sanitize_import(text: String) -> String:
var out: String = ""
var in_img: int = 0
var kept: Array[String] = []
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if name == "img" and kind != "text":
in_img = maxi(0, in_img + (1 if kind == "open" else -1))
continue
if in_img > 0:
continue
if kind == "text":
out += t["raw"]
elif not IMPORT_ALLOWED_TAGS.has(name):
continue
elif kind == "close":
# Keep a closing tag only if its opening tag was kept.
var at: int = kept.rfind(name)
if at >= 0:
kept.remove_at(at)
out += t["raw"]
elif kind == "single" or _param_ok(name, t["param"]):
if kind == "open":
kept.append(name)
out += t["raw"]
return close_open_tags(out)
## Makes text show literally, so a real tag such as [b] is displayed as typed.
## Every "[" becomes "[lb]", which also stops [[references]] from expanding.
static func escape_literal(text: String) -> String:
return text.replace("[", "[lb]")
## True when a url parameter is one of TextExpander's internal markers.
static func is_internal_meta(meta: String) -> bool:
for p in INTERNAL_META_PREFIXES:
if meta.begins_with(p):
return true
return false
static func _meta_of(param: String) -> String:
var m: String = param.trim_prefix("=").strip_edges()
if m.length() >= 2 and m.begins_with("\"") and m.ends_with("\""):
m = m.substr(1, m.length() - 2)
return m
static func _param_ok(name: String, param: String) -> bool:
if param == "":
return name != "color" and name != "font_size"
var pattern: String = ""
match name:
"color": pattern = "^=(#[0-9A-Fa-f]{3,8}|[A-Za-z_]+)$"
"font_size": pattern = "^=\\d{1,3}$"
"ul": pattern = "^ bullet=[^\\[\\]\\s]{1,4}$"
"ol": pattern = "^ type=[1aAiI]$"
"indent": pattern = "^=\\d{1,2}$"
_: return false
if not _param_res.has(pattern):
var re := RegEx.new()
re.compile(pattern)
_param_res[pattern] = re
return (_param_res[pattern] as RegEx).search(param) != null
static func _tag_regex() -> RegEx:
if _tag_re == null:
_tag_re = RegEx.new()
_tag_re.compile(_TAG_PATTERN)
return _tag_re
static func _text_token(s: String) -> Dictionary:
return {"kind": "text", "raw": s, "name": "", "param": ""}

1
core/formatter.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b7qide1wl5alk

114
core/roll_context.gd Normal file
View file

@ -0,0 +1,114 @@
class_name RollContext
extends RefCounted
## State for one top-level roll: chain variables, the collection's persistent
## variables, the RNG, the current depth and the hooks back into the roller.
##
## Create one per top-level roll and share it with every table rolled in that
## chain (inline references and pipes alike).
##
## [b]Hooks the roller must set:[/b]
## - [member resolve_table]: [code]func(name_or_id: String) -> String[/code]. Returns
## the table id, or "" when there is no such table. It should match the id
## exactly or the name case-insensitively, ignoring BBCode in names;
## [method normalize_name] does the name cleanup.
## - [member roll_table]: [code]func(table_id: String, depth: int) -> Dictionary[/code].
## Rolls the table at the given depth and returns a result node.
##
## [b]Node contract for roll_table:[/b]
## - Returns [code]{}[/code] (empty) if the table doesn't exist; it is then shown
## with the missing-table marker.
## - Otherwise the node must have [code]"summary": String[/code], the BBCode text
## that replaces the reference inline (normally the node's expanded entry text).
## It may contain internal [url] markers from deeper expansions.
## - Every other key (table, entry, value, children, stop, ...) belongs to the
## roller; TextExpander only collects the nodes in its "children" output.
## - When the roller itself stops (depth limit, empty table), it still returns a
## node whose summary explains why, for example [method TextExpander.deep_marker].
## - roll_table may change [member depth] while it runs; TextExpander restores it.
const DEFAULT_MAX_DEPTH := 32
## Chain variables: name (no "@") -> String value. Fresh for every top-level roll.
var chain_vars: Dictionary = {}
## The collection's persistent variables, owned and saved elsewhere:
## name (without the "@") -> {"value": String, "source": table_id}.
## This is the caller's Dictionary itself, not a copy, so saves show up there.
var persistent_vars: Dictionary = {}
## True once save() has written a persistent variable in this roll, so the caller
## knows local state needs saving.
var persistent_changed: bool = false
## Depth of the text currently being expanded. References in that text are
## rolled at this depth. The roller sets it (depth + 1 for an entry's text).
var depth: int = 0
## References at a depth greater than this show the "chain too deep" marker.
var max_depth: int = DEFAULT_MAX_DEPTH
var rng: RandomNumberGenerator = null
## func(name_or_id: String) -> String (table id or "").
var resolve_table: Callable = Callable()
## func(table_id: String, depth: int) -> Dictionary (a result node).
var roll_table: Callable = Callable()
func _init(p_persistent: Dictionary = {}, p_rng: RandomNumberGenerator = null) -> void:
persistent_vars = p_persistent
rng = p_rng if p_rng != null else RandomNumberGenerator.new()
## True for names that start with "@" (persistent variables).
static func is_persistent(name: String) -> bool:
return name.strip_edges().begins_with("@")
## Saves a value. Names starting with "@" go to the persistent variables
## (stored without the "@", with the source table id); others to the chain.
func save(name: String, value: String, source_id: String = "") -> void:
var n: String = name.strip_edges()
if n.begins_with("@"):
n = n.substr(1)
if n == "":
return
persistent_vars[n] = {"value": value, "source": source_id}
persistent_changed = true
elif n != "":
chain_vars[n] = value
## Returns the saved String value, or null when the variable isn't set.
## "@name" reads a persistent variable, "name" a chain variable.
func lookup(name: String) -> Variant:
var n: String = name.strip_edges()
if n.begins_with("@"):
var entry: Variant = persistent_vars.get(n.substr(1))
if entry is Dictionary:
return str((entry as Dictionary).get("value", ""))
if entry != null:
return str(entry)
return null
if chain_vars.has(n):
return str(chain_vars[n])
return null
## Calls resolve_table, returning "" if the hook isn't set.
func resolve(name_or_id: String) -> String:
if not resolve_table.is_valid():
return ""
return str(resolve_table.call(name_or_id))
## Calls roll_table at the current depth and restores depth afterwards.
## Returns {} if the hook isn't set or the roller returned something that isn't
## a Dictionary.
func roll(table_id: String) -> Dictionary:
if not roll_table.is_valid():
return {}
var d: int = depth
var result: Variant = roll_table.call(table_id, d)
depth = d
return result as Dictionary if result is Dictionary else {}
## Lowercase, trimmed, BBCode-free form of a table name, for matching
## [[references]] against names: normalize_name("[b]Gems[/b] ") == "gems".
static func normalize_name(name: String) -> String:
return Formatter.strip_tags(name).strip_edges().to_lower()

1
core/roll_context.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dpcaah4i7iu88

259
core/text_expander.gd Normal file
View file

@ -0,0 +1,259 @@
class_name TextExpander
extends RefCounted
## Expands inline table references and variables in entry text.
##
## Syntax (expanded strictly left to right, so a chain variable must be saved
## before it's used):
## [[Table]] roll on Table and insert the result
## [[Table -> var]] ...and save it as chain variable "var"
## [[Table -> @var]] ...and save it as persistent variable "@var"
## [[3x Gems]] roll 3 times, joined with ", "
## [[1d4 Coins]] roll 1d4 for the count (NdM, NdM+K, NdM-K)
## {var} {@var} insert a saved value
## {@var|Table} use the saved value, else roll on Table, save, insert
##
## Inserted pieces are wrapped in internal url tags so the UI can show hover
## pop-ups through RichTextLabel's meta_hover_started signal:
## [url=table:<id>]<summary>[/url] one roll on a table
## [url=var:<name>]<value>[/url] a variable ("@town" for persistent ones)
## [url=missing:<name>]⚠ <name>[/url] a table that doesn't exist
## [url=unset:<name>]{<name>?}[/url] a variable that isn't set
## [url=deep:<id>]⚠ chain too deep[/url] the depth limit was reached
##
## BBCode is untouched: known tags (including ones with parameters such as
## [url={"a":1}]) are copied as-is, and ordinary bracket text like [x] stays text.
## A reference's name can't contain "[" or "]", so "[[b]x[/b]]" is not one.
## Use [lb] to write a literal "[[".
## Upper limit for [[Nx Table]] and [[NdM Table]] counts.
const MAX_REPEAT := 100
const DEEP_TEXT := "⚠ chain too deep"
const _VAR_PATTERN := "\\{(@?[A-Za-z_][A-Za-z0-9_]*)(?:\\|([^{}\\[\\]\\n]+))?\\}"
const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*)[dD](\\d+)(?:\\s*([+-])\\s*(\\d+))?)\\s+(\\S.*)$"
const _SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
static var _res: Dictionary = {}
## Expands `text` and returns:
## text: String the expanded BBCode, with open tags closed at the end
## children: Array the result nodes rolled inline, in order (one per roll,
## so [[3x Gems]] adds three)
static func expand(text: String, ctx: RollContext) -> Dictionary:
var out: String = ""
var children: Array = []
var i: int = 0
var n: int = text.length()
while i < n:
var c: String = text[i]
if c == "[":
if i + 1 < n and text[i + 1] == "[":
var ref: Dictionary = _ref_at(text, i)
if not ref.is_empty():
out += _expand_ref(ref, ctx, children)
i = ref["end"]
continue
out += c
i += 1
continue
var tag: Dictionary = Formatter.tag_at(text, i)
if not tag.is_empty():
out += tag["raw"]
i += (tag["raw"] as String).length()
continue
elif c == "{":
var m: RegExMatch = _re(_VAR_PATTERN).search(text, i)
if m != null and m.get_start() == i:
out += _expand_var(m.get_string(1), m.get_string(2).strip_edges(), ctx, children)
i = m.get_end()
continue
out += c
i += 1
return {"text": Formatter.close_open_tags(out), "children": children}
## Names of the tables referenced in `text`, without rolling, in order of first
## appearance and without duplicates. Covers [[...]] references (minus any count
## prefix and "-> var" part) and the table in {@var|Table}. With a resolver
## (func(name) -> id), a name like "3x Gems" that is itself a table name is kept
## whole, the same way expand() decides.
static func references(text: String, resolve: Callable = Callable()) -> Array[String]:
var out: Array[String] = []
var i: int = 0
var n: int = text.length()
while i < n:
var c: String = text[i]
var name: String = ""
if c == "[" and i + 1 < n and text[i + 1] == "[":
var ref: Dictionary = _ref_at(text, i)
if not ref.is_empty():
var whole: String = ref["name"]
name = whole
var count: Dictionary = _parse_count(whole)
if not count.is_empty():
var whole_ok: bool = resolve.is_valid() and str(resolve.call(whole)) != ""
if not whole_ok:
name = count["name"]
i = ref["end"]
elif c == "[":
var tag: Dictionary = Formatter.tag_at(text, i)
if not tag.is_empty():
i += (tag["raw"] as String).length()
continue
elif c == "{":
var m: RegExMatch = _re(_VAR_PATTERN).search(text, i)
if m != null and m.get_start() == i:
name = m.get_string(2).strip_edges()
i = m.get_end()
if name != "":
if not out.has(name):
out.append(name)
continue
i += 1
return out
## The marker for a reference to a table that doesn't exist.
static func missing_marker(name: String) -> String:
return "[url=missing:%s]⚠ %s[/url]" % [name, name]
## The marker for a variable that hasn't been saved. `name` includes any "@".
static func unset_marker(name: String) -> String:
return "[url=unset:%s]{%s?}[/url]" % [name, name]
## The marker for a reference past the depth limit. The roller can use it as the
## summary of a node it stopped for depth.
static func deep_marker(table_id: String) -> String:
return "[url=deep:%s]%s[/url]" % [table_id, DEEP_TEXT]
## Rolls an NdM+K expression ("1d4", "d6", "2d6+1", "3d8-2") with `rng`.
## Returns -1 when the expression isn't valid.
static func roll_dice(expr: String, rng: RandomNumberGenerator) -> int:
var m: RegExMatch = _re("^\\s*(\\d*)[dD](\\d+)\\s*(?:([+-])\\s*(\\d+))?\\s*$").search(expr)
if m == null:
return -1
return _roll_parts(m.get_string(1), m.get_string(2), m.get_string(3), m.get_string(4), rng)
static func _roll_parts(num: String, sides: String, op: String, mod: String, rng: RandomNumberGenerator) -> int:
var dice: int = int(num) if num != "" else 1
var faces: int = int(sides)
if faces < 1 or dice > MAX_REPEAT:
return -1
var total: int = 0
for _k in dice:
total += rng.randi_range(1, faces)
if mod != "":
total += int(mod) if op == "+" else -int(mod)
return total
## Parses "[[...]]" at `pos`. Returns {name, save, end} or {} if it isn't a
## valid reference (no closing "]]", empty, or containing "[", "]" or a newline).
static func _ref_at(text: String, pos: int) -> Dictionary:
var close: int = text.find("]]", pos + 2)
if close < 0:
return {}
var body: String = text.substr(pos + 2, close - pos - 2)
if body.strip_edges() == "" or body.contains("[") or body.contains("]") or body.contains("\n"):
return {}
var name: String = body
var save_as: String = ""
var arrow: int = body.rfind("->")
if arrow >= 0:
var target: String = body.substr(arrow + 2).strip_edges()
if _re(_SAVE_PATTERN).search(target) != null:
save_as = target
name = body.substr(0, arrow)
name = name.strip_edges()
if name == "":
return {}
return {"name": name, "save": save_as, "end": close + 2}
## Splits "3x Gems" / "1d4+1 Coins" into {kind: "times"|"dice", ...parts, name}.
static func _parse_count(name: String) -> Dictionary:
var m: RegExMatch = _re(_COUNT_PATTERN).search(name)
if m == null:
return {}
if m.get_string(1) != "":
return {"kind": "times", "times": int(m.get_string(1)), "name": m.get_string(6).strip_edges()}
return {
"kind": "dice", "num": m.get_string(2), "sides": m.get_string(3),
"sign": m.get_string(4), "mod": m.get_string(5), "name": m.get_string(6).strip_edges(),
}
static func _expand_ref(ref: Dictionary, ctx: RollContext, children: Array) -> String:
var name: String = ref["name"]
var times: int = 1
var id: String = ctx.resolve(name)
if id == "":
var count: Dictionary = _parse_count(name)
if not count.is_empty():
name = count["name"]
id = ctx.resolve(name)
if count["kind"] == "times":
times = count["times"]
else:
times = _roll_parts(count["num"], count["sides"], count["sign"], count["mod"], ctx.rng)
times = clampi(times, 0, MAX_REPEAT)
if id == "":
return missing_marker(name)
var pieces: PackedStringArray = []
var plain: PackedStringArray = []
for _k in times:
var piece: Dictionary = _roll_one(id, ctx, children)
pieces.append(piece["text"])
plain.append(piece["value"])
var save_as: String = ref["save"]
if save_as != "":
ctx.save(save_as, ", ".join(plain), id)
return ", ".join(pieces)
static func _expand_var(name: String, table: String, ctx: RollContext, children: Array) -> String:
var value: Variant = ctx.lookup(name)
if value != null:
return "[url=var:%s]%s[/url]" % [name, Formatter.close_open_tags(str(value))]
if table == "":
return unset_marker(name)
var id: String = ctx.resolve(table)
if id == "":
return missing_marker(table)
var piece: Dictionary = _roll_one(id, ctx, children)
if not piece["rolled"]:
return piece["text"]
ctx.save(name, piece["value"], id)
return "[url=var:%s]%s[/url]" % [name, piece["value"]]
## One roll on a resolved table. Returns {text (wrapped for display), value
## (export BBCode, for saving), rolled (false for depth/missing markers)}.
static func _roll_one(id: String, ctx: RollContext, children: Array) -> Dictionary:
if ctx.depth > ctx.max_depth:
var deep: String = deep_marker(id)
return {"text": deep, "value": DEEP_TEXT, "rolled": false}
var node: Dictionary = ctx.roll(id)
if node.is_empty():
var missing: String = missing_marker(id)
return {"text": missing, "value": "", "rolled": false}
children.append(node)
var summary: String = Formatter.close_open_tags(str(node.get("summary", "")))
return {
"text": "[url=table:%s]%s[/url]" % [id, summary],
"value": Formatter.to_export_bbcode(summary),
"rolled": true,
}
static func _re(pattern: String) -> RegEx:
if not _res.has(pattern):
var re := RegEx.new()
re.compile(pattern)
_res[pattern] = re
return _res[pattern]

View file

@ -0,0 +1 @@
uid://bdynv8jvjraa1

219
tests/test_text.gd Normal file
View file

@ -0,0 +1,219 @@
extends SceneTree
## Headless checks for RollContext, TextExpander and Formatter.
## Run: godot --headless --path . -s res://tests/test_text.gd
const TABLES := {
"names": "Names",
"gems": "[b]Gems[/b]",
"towns": "Towns",
"loop": "Loop",
"bold": "Bold",
}
## Each stub table returns its results in order, cycling.
const RESULTS := {
"names": ["Alice", "Bob", "Cora"],
"gems": ["Ruby", "Opal", "Jade", "Onyx"],
"towns": ["Riverton", "Hilltop"],
"bold": ["[b]heavy"],
}
var _failures := 0
var _ctx: RollContext
var _rolls: Dictionary = {}
func _init() -> void:
_test_expander()
_test_formatter()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _new_ctx(persistent: Dictionary = {}) -> RollContext:
var rng := RandomNumberGenerator.new()
rng.seed = 7
_ctx = RollContext.new(persistent, rng)
_ctx.resolve_table = _resolve
_ctx.roll_table = _roll
_rolls = {}
return _ctx
func _resolve(name_or_id: String) -> String:
if TABLES.has(name_or_id):
return name_or_id
var want := RollContext.normalize_name(name_or_id)
for id: String in TABLES:
if RollContext.normalize_name(TABLES[id]) == want:
return id
return ""
func _roll(table_id: String, depth: int) -> Dictionary:
if not TABLES.has(table_id):
return {}
var k: int = int(_rolls.get(table_id, 0))
_rolls[table_id] = k + 1
if table_id == "loop":
_ctx.depth = depth + 1
var r := TextExpander.expand("again [[Loop]]", _ctx)
return {"summary": r["text"], "children": r["children"], "depth": depth}
var list: Array = RESULTS[table_id]
return {"summary": list[k % list.size()], "table": table_id, "depth": depth}
func _x(text: String, ctx: RollContext) -> String:
return TextExpander.expand(text, ctx)["text"]
func _test_expander() -> void:
var ctx := _new_ctx()
# Plain reference, by name, case-insensitive, BBCode in the table name ignored.
var r := TextExpander.expand("A [[gems]] ring", ctx)
_eq(r["text"], "A [url=table:gems]Ruby[/url] ring", "reference by name")
_check((r["children"] as Array).size() == 1, "reference adds one child")
_eq(_x("[[Names]]", ctx), "[url=table:names]Alice[/url]", "reference by name, plain")
# Left to right: a chain var used before it's saved is unset, after it's set.
ctx = _new_ctx()
_eq(_x("{hero} [[Names -> hero]] {hero}", ctx),
"[url=unset:hero]{hero?}[/url] [url=table:names]Alice[/url] [url=var:hero]Alice[/url]",
"left to right ordering")
_eq(ctx.lookup("hero"), "Alice", "chain var saved")
_check(ctx.lookup("nobody") == null, "unset lookup is null")
r = TextExpander.expand("[[Names]] then [[Gems]] then [[Names]]", ctx)
var kids: Array = r["children"]
_check(kids.size() == 3 and kids[0]["summary"] == "Bob" and kids[1]["summary"] == "Ruby" and kids[2]["summary"] == "Cora",
"children in text order")
# Chain vs persistent scope.
var store := {}
ctx = _new_ctx(store)
_x("[[Towns -> @town]] [[Names -> hero]]", ctx)
_check(store.has("town") and store["town"]["value"] == "Riverton" and store["town"]["source"] == "towns",
"persistent var saved into the caller's dictionary: %s" % store)
_check(not store.has("hero") and ctx.chain_vars.has("hero"), "chain var stays in the chain")
_check(ctx.persistent_changed, "persistent_changed set")
ctx = _new_ctx(store)
_eq(_x("{hero} in {@town}", ctx), "[url=unset:hero]{hero?}[/url] in [url=var:@town]Riverton[/url]",
"new roll: chain var gone, persistent kept")
_check(not ctx.persistent_changed, "reading doesn't set persistent_changed")
# {@var|Table}: existing value is reused without rolling.
_eq(_x("{@town|Towns}", ctx), "[url=var:@town]Riverton[/url]", "{@var|Table} uses the saved value")
_check(not _rolls.has("towns"), "{@var|Table} didn't reroll")
ctx = _new_ctx({})
r = TextExpander.expand("{@town|Towns}, again {@town|Towns}", ctx)
_eq(r["text"], "[url=var:@town]Riverton[/url], again [url=var:@town]Riverton[/url]", "{@var|Table} rolls once when unset")
_check(int(_rolls.get("towns", 0)) == 1 and (r["children"] as Array).size() == 1, "{@var|Table} rolled exactly once")
_eq(ctx.lookup("@town"), "Riverton", "{@var|Table} saved")
_eq(_x("{@port|Nowhere}", ctx), "[url=missing:Nowhere]⚠ Nowhere[/url]", "{@var|Missing} shows missing marker")
_check(ctx.lookup("@port") == null, "{@var|Missing} saves nothing")
# Count forms.
ctx = _new_ctx()
r = TextExpander.expand("[[3x Gems]]", ctx)
_eq(r["text"], "[url=table:gems]Ruby[/url], [url=table:gems]Opal[/url], [url=table:gems]Jade[/url]", "3x")
_check((r["children"] as Array).size() == 3, "3x adds three children")
ctx = _new_ctx()
_x("[[2 x Gems -> loot]]", ctx)
_eq(ctx.lookup("loot"), "Ruby, Opal", "Nx with save joins the values")
for s in 20:
ctx = _new_ctx()
ctx.rng.seed = s
r = TextExpander.expand("[[1d4 Gems]]", ctx)
var c: int = (r["children"] as Array).size()
_check(c >= 1 and c <= 4, "1d4 rolls 1–4 times (got %d)" % c)
_check((r["text"] as String).count("[url=table:gems]") == c, "1d4 inserts one piece per roll")
ctx = _new_ctx()
_check(TextExpander.roll_dice("2d6+3", ctx.rng) >= 5 and TextExpander.roll_dice("2d6+3", ctx.rng) <= 15, "NdM+K in range")
_check(TextExpander.roll_dice("d1-1", ctx.rng) == 0, "dM-K")
_check(TextExpander.roll_dice("banana", ctx.rng) == -1, "bad dice expression")
_eq(TextExpander.expand("[[0x Gems]]", ctx)["text"], "", "0x inserts nothing")
# Missing tables, unset vars, depth.
ctx = _new_ctx()
r = TextExpander.expand("A [[Dragons]] and [[2x Dragons]].", ctx)
_eq(r["text"], "A [url=missing:Dragons]⚠ Dragons[/url] and [url=missing:Dragons]⚠ Dragons[/url].", "missing table marker")
_check((r["children"] as Array).is_empty(), "missing table adds no children")
_eq(_x("{@nope}", ctx), "[url=unset:@nope]{@nope?}[/url]", "unset persistent marker")
ctx = _new_ctx()
ctx.max_depth = 5
var deep := _x("[[Loop]]", ctx)
_check(deep.contains(TextExpander.deep_marker("loop")), "depth marker present")
_eq(int(_rolls.get("loop", 0)), 6, "loop rolled depths 0..5 then stopped")
_eq(deep.count("again"), 6, "six levels of text")
_eq(ctx.depth, 0, "depth restored after expansion")
ctx = _new_ctx()
ctx.depth = 40
_eq(_x("[[Names]]", ctx), "[url=deep:names]⚠ chain too deep[/url]", "default max depth 32")
# Brackets and BBCode.
ctx = _new_ctx()
_eq(_x("[x] marks [optional] spot", ctx), "[x] marks [optional] spot", "ordinary brackets untouched")
_eq(_x("[b][[Names]][/b] [i]{hero}[/i]", ctx), "[b][url=table:names]Alice[/url][/b] [i][url=unset:hero]{hero?}[/url][/i]",
"BBCode around references")
_eq(_x("[color=red][[Gems]][/color]", ctx), "[color=red][url=table:gems]Ruby[/url][/color]", "reference inside color")
_eq(_x("[url={\"a\":1}]x[/url]", ctx), "[url={\"a\":1}]x[/url]", "braces in a tag parameter aren't variables")
_eq(_x("[[b]x[/b]] and [lb][lb]Names]]", ctx), "[[b]x[/b]] and [lb][lb]Names]]", "not references")
_eq(_x("{not a var} {} {1x}", ctx), "{not a var} {} {1x}", "braces that aren't variables")
_eq(_x("A [[Bold]] thing", ctx), "A [url=table:bold][b]heavy[/b][/url] thing", "child's open tag closed inside its piece")
_eq(_x("[i]left open [[Names]]", ctx), "[i]left open [url=table:names]Bob[/url][/i]", "entry's open tag closed at end")
# references()
_new_ctx()
var refs := TextExpander.references("[[Names -> hero]] [[3x Gems]] {@town|Towns} [[1d4+1 Coins]] [x] [b]y[/b] [[Names]] {hero}")
_check(refs == (["Names", "Gems", "Towns", "Coins"] as Array[String]), "references: %s" % [refs])
var tricky := TextExpander.references("[[3x Gems]]", func(n: String) -> String: return "t" if n == "3x Gems" else "")
_check(tricky == (["3x Gems"] as Array[String]), "references keeps a whole name that resolves: %s" % [tricky])
_check(_rolls.is_empty(), "references doesn't roll")
func _test_formatter() -> void:
# close_open_tags
_eq(Formatter.close_open_tags("[b]bold"), "[b]bold[/b]", "close one")
_eq(Formatter.close_open_tags("[b][i]x"), "[b][i]x[/i][/b]", "close nested in order")
_eq(Formatter.close_open_tags("[b][i]x[/b] y"), "[b][i]x[/i][/b] y", "mismatched close fixes inner")
_eq(Formatter.close_open_tags("x[/b] y"), "x[lb]/b] y", "stray close escaped")
_eq(Formatter.close_open_tags("[color=#ff0000]r[font_size=20]big"), "[color=#ff0000]r[font_size=20]big[/font_size][/color]", "params")
_eq(Formatter.close_open_tags("[x] [lb] [b]ok[/b]"), "[x] [lb] [b]ok[/b]", "balanced and unknown untouched")
_eq(Formatter.close_open_tags("[ul bullet=*]\na\nb"), "[ul bullet=*]\na\nb[/ul]", "list closed")
# strip_tags
_eq(Formatter.strip_tags("[b]Bold[/b] [color=red]red[/color] [x] [lb]b]"), "Bold red [x] [b]", "strip basic")
_eq(Formatter.strip_tags("[url=table:gems]Ruby[/url] and [url=missing:Dragons]⚠ Dragons[/url] for [url=unset:hero]{hero?}[/url]"),
"Ruby and ⚠ Dragons (missing table) for {hero?}", "strip markers")
_eq(Formatter.strip_tags("a[img]res://icon.svg[/img]b[br]c[char=41]"), "ab\ncA", "strip img, br, char")
_eq(Formatter.strip_tags("[url={\"a\":1}]link[/url]"), "link", "strip JSON url")
# to_export_bbcode
_eq(Formatter.to_export_bbcode("[b][url=table:gems]Ruby[/url][/b] [url=var:@town]Hilltop[/url] [url=https://x.org]site[/url]"),
"[b]Ruby[/b] Hilltop [url=https://x.org]site[/url]", "export drops only internal urls")
_eq(Formatter.to_export_bbcode("[url=table:a]x [url=table:b]y[/url] z[/url]"), "x y z", "export nested internal urls")
# sanitize_import
_eq(Formatter.sanitize_import("[img]/etc/passwd[/img]hi [url=file:///x]there[/url]"), "hi there", "import strips img and url")
_eq(Formatter.sanitize_import("[img=10x10]a.png[/img][font=res://f.ttf]t[/font]"), "t", "import strips img with param and font")
_eq(Formatter.sanitize_import("[b]b[/b] [color=red]r[/color] [color=#ff0000]h[/color] [font_size=20]s[/font_size] [x]"),
"[b]b[/b] [color=red]r[/color] [color=#ff0000]h[/color] [font_size=20]s[/font_size] [x]", "import keeps allowed tags")
_eq(Formatter.sanitize_import("[url=missing:Fake]⚠ Fake[/url]"), "⚠ Fake", "import can't forge markers")
_eq(Formatter.sanitize_import("[color=red onclick]x[/color][b]open"), "x[b]open[/b]", "bad params dropped, open closed")
_eq(Formatter.sanitize_import("[ul bullet=*]\na\n[/ul][lb]b]"), "[ul bullet=*]\na\n[/ul][lb]b]", "import keeps lists and lb")
# escape_literal
_eq(Formatter.escape_literal("[b]x[/b]"), "[lb]b]x[lb]/b]", "escape tags")
_eq(Formatter.strip_tags(Formatter.escape_literal("[b]x[/b] [[Gems]]")), "[b]x[/b] [[Gems]]", "escaped text strips back")
_eq(TextExpander.expand(Formatter.escape_literal("[[Gems]]"), _new_ctx())["text"], "[lb][lb]Gems]]", "escaped reference not expanded")
_eq(RollContext.normalize_name(" [b]Gems[/b] "), "gems", "normalize_name")
func _eq(got: Variant, want: Variant, what: String) -> void:
_check(got == want, "%s\n got: %s\n want: %s" % [what, got, want])
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

1
tests/test_text.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bepb7t5s0bsdc