Implements docs/PLAIN.md sections 1-5 (the engine half of the usability pass): - core/describe.gd (Describe): rules in plain words, labelled from variable cards, collections and card inputs, falling back to the original text. - core/builder.gd (Builder): effect and condition models that round-trip with the rule text, a rule tokenizer, and known_values(board). - Collections: variable cards with var_type "collection" label their members and don't declare their stem. - Check cards (kind "check"): dice + modifier vs target, Success/Failure, chain values nat/total/effect, node "check" info, lint and static checks. - Card inputs and pipe "with" values, scoped over the pipe's subtree on the explicit work stack (OP_RESTORE frames), with defaults and snapshot evaluation. - nat on every roll-table roll; dice faces recorded through ctx.faces. - Why trace: facts on nodes and steps (input, roll, check, case, show_if, options_where, effect, when, otherwise). - StateStore rules_view setting; JSON for the new keys; LOGIC.md and PLAIN.md updated (deviations in PLAIN.md 5a). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
310 lines
12 KiB
GDScript
310 lines
12 KiB
GDScript
class_name Effects
|
||
extends RefCounted
|
||
## Effect statements on entries (docs/LOGIC.md §5.2): one per line or
|
||
## separated by ";".
|
||
##
|
||
## @str = 2d6 set
|
||
## @terms += 1 add a number, or append ", item" to text/list if absent
|
||
## @credits -= 1000 subtract a number, or remove the item from text/list
|
||
## @age *= 2 multiply (/= divides, rounding down)
|
||
## reset @name back to the variable card's starting value, or deleted
|
||
## reset @skill_* every variable with that prefix
|
||
## @[expr] += 1 the variable named by expr (indirect), e.g.
|
||
## @[option] += 1, reset @["skill_" + option]
|
||
##
|
||
## A target without "@" is a chain variable. Unset counts as 0 (or "" when the
|
||
## value added is text). run() never stops on a bad statement: it logs an error
|
||
## line and carries on.
|
||
|
||
const OPS := ["+=", "-=", "*=", "/=", "="]
|
||
|
||
static var _stmt_re: RegEx = null
|
||
static var _reset_re: RegEx = null
|
||
|
||
|
||
## Splits effect text into statements: lines, and ";" outside quotes. Empty
|
||
## statements are dropped.
|
||
static func split(text: String) -> Array[String]:
|
||
var out: Array[String] = []
|
||
var cur := ""
|
||
var quote := ""
|
||
for c in text:
|
||
if quote != "":
|
||
cur += c
|
||
if c == quote:
|
||
quote = ""
|
||
elif c == "\"" or c == "'":
|
||
quote = c
|
||
cur += c
|
||
elif c == ";" or c == "\n":
|
||
if cur.strip_edges() != "":
|
||
out.append(cur.strip_edges())
|
||
cur = ""
|
||
else:
|
||
cur += c
|
||
if cur.strip_edges() != "":
|
||
out.append(cur.strip_edges())
|
||
return out
|
||
|
||
|
||
## Parses one statement. Returns {src, op ("=", "+=", "-=", "*=", "/=" or
|
||
## "reset"), target ("@name", "name", or "@prefix_*" for reset), expr} or
|
||
## {src, error}.
|
||
static func parse_statement(src: String) -> Dictionary:
|
||
_compile()
|
||
var s := src.strip_edges()
|
||
var ind := _parse_indirect(s)
|
||
if not ind.is_empty():
|
||
return ind
|
||
var m := _reset_re.search(s)
|
||
if m != null:
|
||
var target := "@" + m.get_string(1).to_lower() + m.get_string(2)
|
||
return {"src": s, "op": "reset", "target": target, "expr": ""}
|
||
if s.to_lower().begins_with("reset"):
|
||
return {"src": s, "error": "Write reset @name or reset @prefix_*"}
|
||
m = _stmt_re.search(s)
|
||
if m == null:
|
||
return {"src": s, "error": "Not a statement; try @name = value"}
|
||
var t := m.get_string(1)
|
||
if t.begins_with("@"):
|
||
t = t.to_lower()
|
||
var expr := m.get_string(3).strip_edges()
|
||
if expr == "":
|
||
return {"src": s, "error": "Nothing after %s" % m.get_string(2)}
|
||
return {"src": s, "op": m.get_string(2), "target": t, "expr": expr}
|
||
|
||
|
||
## An indirect statement ("@[expr] op value" or "reset @[expr]"), parsed into
|
||
## the same shape with "target_expr" (the expression naming the variable) and
|
||
## target "@[expr]"; {} when `s` isn't one.
|
||
static func _parse_indirect(s: String) -> Dictionary:
|
||
var at := -1
|
||
var is_reset := false
|
||
if s.begins_with("@["):
|
||
at = 1
|
||
elif s.to_lower().begins_with("reset") and s.substr(5).strip_edges().begins_with("@["):
|
||
is_reset = true
|
||
at = s.find("@[") + 1
|
||
if at < 0:
|
||
return {}
|
||
var close := Expr.bracket_end(s, at)
|
||
if close < 0:
|
||
return {"src": s, "error": "@[ is missing its closing ]"}
|
||
var inner := s.substr(at + 1, close - at - 1).strip_edges()
|
||
if inner == "":
|
||
return {"src": s, "error": "Write an expression inside @[ ], e.g. @[option]"}
|
||
var target := s.substr(at - 1, close - at + 2)
|
||
var rest := s.substr(close + 1).strip_edges()
|
||
if is_reset:
|
||
if rest != "":
|
||
return {"src": s, "error": "Write reset @[expr]"}
|
||
return {"src": s, "op": "reset", "target": target, "target_expr": inner, "expr": ""}
|
||
for op: String in ["+=", "-=", "*=", "/=", "="]:
|
||
if rest.begins_with(op) and not (op == "=" and rest.begins_with("==")):
|
||
var expr := rest.substr(op.length()).strip_edges()
|
||
if expr == "":
|
||
return {"src": s, "error": "Nothing after %s" % op}
|
||
return {"src": s, "op": op, "target": target, "target_expr": inner, "expr": expr}
|
||
return {"src": s, "error": "Not a statement; try @[name] = value"}
|
||
|
||
|
||
## The real target of a statement: its "target", or for an indirect one
|
||
## "@name" from its expression. {"target", "error"}: the error is set when
|
||
## the expression fails or doesn't give a valid name.
|
||
static func resolve_target(st: Dictionary, ctx: RollContext) -> Dictionary:
|
||
if not st.has("target_expr"):
|
||
return {"target": st["target"], "error": ""}
|
||
var r := Expr.evaluate(str(st["target_expr"]), ctx)
|
||
if r["error"] != "":
|
||
return {"target": "", "error": str(r["error"])}
|
||
var nm := Expr.indirect_name(r["value"])
|
||
if nm["error"] != "":
|
||
return {"target": "", "error": str(nm["error"])}
|
||
return {"target": "@" + str(nm["name"]), "error": ""}
|
||
|
||
|
||
## Problems in effect text for the Build-mode editor: Array of {index (0-based
|
||
## statement number), src, error}. Empty when everything parses.
|
||
static func validate(text: String) -> Array[Dictionary]:
|
||
var out: Array[Dictionary] = []
|
||
var list := split(text)
|
||
for k in list.size():
|
||
var st := parse_statement(list[k])
|
||
var err := str(st.get("error", ""))
|
||
if err == "" and st.has("target_expr"):
|
||
err = Expr.check(st["target_expr"])
|
||
if err == "" and st["op"] != "reset":
|
||
err = Expr.check(st["expr"])
|
||
if err != "":
|
||
out.append({"index": k, "src": list[k], "error": err})
|
||
return out
|
||
|
||
|
||
## Runs every statement against the context. Returns the log, one line per
|
||
## statement: Array of {"text": String, "error": bool (only when true)}.
|
||
## `source_id` is stored as the variables' source table. `facts`, when given,
|
||
## gets one why-trace fact per statement that changed something:
|
||
## {"type": "effect", "var": "@name" (or "@prefix_*" / a chain name), "op":
|
||
## "=" | "+=" | "-=" | "*=" | "/=" | "reset", "before": value or null,
|
||
## "after": value or null} ("count" instead of before/after for a prefix reset).
|
||
static func run(text: String, ctx: RollContext, source_id: String = "", facts: Variant = null) -> Array[Dictionary]:
|
||
var log: Array[Dictionary] = []
|
||
if text.strip_edges() == "":
|
||
return log
|
||
for src in split(text):
|
||
var st := parse_statement(src)
|
||
if st.has("error"):
|
||
log.append({"text": "%s: %s" % [src, st["error"]], "error": true})
|
||
continue
|
||
if st.has("target_expr"):
|
||
var rt := resolve_target(st, ctx)
|
||
if rt["error"] != "":
|
||
log.append({"text": "%s: %s" % [src, rt["error"]], "error": true})
|
||
continue
|
||
st["target"] = rt["target"]
|
||
if st["op"] == "reset":
|
||
log.append(_reset(st["target"], ctx, facts))
|
||
else:
|
||
log.append(_assign(st, ctx, source_id, facts))
|
||
return log
|
||
|
||
|
||
## Plain log lines (errors included), for copying and history.
|
||
static func log_text(log: Array) -> PackedStringArray:
|
||
var out := PackedStringArray()
|
||
for l: Variant in log:
|
||
out.append(str((l as Dictionary).get("text", "")) if l is Dictionary else str(l))
|
||
return out
|
||
|
||
|
||
static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts: Variant = null) -> Dictionary:
|
||
var target: String = st["target"]
|
||
var op: String = st["op"]
|
||
var r := Expr.evaluate(st["expr"], ctx)
|
||
if r["error"] != "":
|
||
return {"text": "%s: %s" % [st["src"], r["error"]], "error": true}
|
||
var rhs: Variant = Expr.normalize(r["value"])
|
||
var label := ctx.display_name(target) if target.begins_with("@") else target
|
||
var cur: Variant = ctx.get_value(target)
|
||
var type := ""
|
||
if target.begins_with("@"):
|
||
var card := ctx.declared(target)
|
||
if card != null:
|
||
type = card.var_type
|
||
var as_list := false
|
||
if op == "+=" or op == "-=":
|
||
if type == "text" or type == "list":
|
||
as_list = true
|
||
elif type == "number":
|
||
as_list = false
|
||
else:
|
||
as_list = not Expr.is_number(rhs) or (cur != null and not Expr.is_number(cur) and str(cur).strip_edges() != "")
|
||
var value: Variant
|
||
var line: String
|
||
match op:
|
||
"=":
|
||
if type == "number" and not Expr.is_number(rhs):
|
||
return {"text": "%s: %s is a number, not \"%s\"" % [st["src"], label, Expr.format_value(rhs)], "error": true}
|
||
value = Expr.to_value(rhs) if type == "number" else rhs
|
||
line = "%s = %s" % [label, _shown(value)]
|
||
"+=", "-=":
|
||
if as_list:
|
||
var items := Expr.list_items(cur if cur != null else "")
|
||
var item := Expr.format_value(rhs).strip_edges()
|
||
var at := -1
|
||
for k in items.size():
|
||
if items[k].to_lower() == item.to_lower():
|
||
at = k
|
||
break
|
||
if op == "+=" and at < 0 and item != "":
|
||
items.append(item)
|
||
elif op == "-=" and at >= 0:
|
||
items.remove_at(at)
|
||
value = ", ".join(items)
|
||
line = "%s %s %s → %s" % [label, "+" if op == "+=" else "−", item, _shown(value)]
|
||
else:
|
||
var a: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
|
||
var b: Variant = Expr.to_value(rhs)
|
||
if not Expr.is_number(a) or not Expr.is_number(b):
|
||
return {"text": "%s: %s needs a number" % [st["src"], label], "error": true}
|
||
var delta: Variant = b if op == "+=" else -b
|
||
value = Expr.normalize(a + delta)
|
||
line = "%s %s → %s" % [label, _signed(delta), _shown(value)]
|
||
"*=", "/=":
|
||
var a2: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
|
||
var b2: Variant = Expr.to_value(rhs)
|
||
if not Expr.is_number(a2) or not Expr.is_number(b2):
|
||
return {"text": "%s: %s needs a number" % [st["src"], label], "error": true}
|
||
if op == "*=":
|
||
value = Expr.normalize(a2 * b2)
|
||
line = "%s ×%s → %s" % [label, Expr.format_value(b2), _shown(value)]
|
||
else:
|
||
if b2 == 0:
|
||
return {"text": "%s: can't divide by 0" % st["src"], "error": true}
|
||
value = floori(float(a2) / float(b2))
|
||
line = "%s ÷%s → %s" % [label, Expr.format_value(b2), _shown(value)]
|
||
ctx.save(target, value, source_id)
|
||
if facts != null:
|
||
(facts as Array).append({"type": "effect", "var": target, "op": op, "before": cur, "after": ctx.get_value(target)})
|
||
return {"text": line}
|
||
|
||
|
||
static func _reset(target: String, ctx: RollContext, facts: Variant = null) -> Dictionary:
|
||
if target.ends_with("*"):
|
||
var prefix := target.trim_prefix("@").trim_suffix("*")
|
||
var names := {}
|
||
for n: String in ctx.persistent_vars:
|
||
if n.begins_with(prefix):
|
||
names[n] = true
|
||
for n in ctx.declared_names():
|
||
if n.begins_with(prefix):
|
||
names[n] = true
|
||
var errors := PackedStringArray()
|
||
for n: String in names:
|
||
var r := reset_one(n, ctx)
|
||
if r != "":
|
||
errors.append(r)
|
||
if not errors.is_empty():
|
||
return {"text": "reset %s: %s" % [target, "; ".join(errors)], "error": true}
|
||
if facts != null:
|
||
(facts as Array).append({"type": "effect", "var": target, "op": "reset", "count": names.size()})
|
||
return {"text": "Reset %s (%d)" % [target, names.size()]}
|
||
var name := target.trim_prefix("@")
|
||
var before: Variant = ctx.get_value("@" + name)
|
||
var err := reset_one(name, ctx)
|
||
if err != "":
|
||
return {"text": "reset %s: %s" % [target, err], "error": true}
|
||
var v: Variant = ctx.get_value("@" + name)
|
||
if facts != null:
|
||
(facts as Array).append({"type": "effect", "var": "@" + name, "op": "reset", "before": before, "after": v})
|
||
if v == null:
|
||
return {"text": "Reset %s (cleared)" % ctx.display_name(name)}
|
||
return {"text": "Reset %s → %s" % [ctx.display_name(name), _shown(v)]}
|
||
|
||
|
||
## Resets one board variable (no "@"): a declared one goes back to its starting
|
||
## value, an undeclared one is deleted. Returns an error message or "".
|
||
static func reset_one(name: String, ctx: RollContext) -> String:
|
||
var card := ctx.declared(name)
|
||
if card == null:
|
||
ctx.erase("@" + name)
|
||
return ""
|
||
var r := card.initial_value(ctx)
|
||
ctx.save("@" + name, r["value"], card.id)
|
||
return str(r["error"])
|
||
|
||
|
||
static func _shown(v: Variant) -> String:
|
||
var s := Expr.format_value(v)
|
||
return s if s != "" else "(none)"
|
||
|
||
|
||
static func _signed(v: Variant) -> String:
|
||
var s := Expr.format_value(v)
|
||
return s if s.begins_with("-") else "+" + s
|
||
|
||
|
||
static func _compile() -> void:
|
||
if _stmt_re == null:
|
||
_stmt_re = RegEx.create_from_string("^(@?[A-Za-z_][A-Za-z0-9_]*)\\s*(\\+=|-=|\\*=|/=|=)(?!=)\\s*(.*)$")
|
||
_reset_re = RegEx.create_from_string("^(?i:reset)\\s+@([A-Za-z_][A-Za-z0-9_]*|)(\\*?)\\s*$")
|