Expr's rewrite step moves to ExprRewriter; Builder's tokenizer moves to RuleTokens and its value list to BuilderValues; BoardTester's static checks move to BoardChecks and its report text to BoardReportText. The original classes keep one-line delegators, so no caller changes. Expr's dice regex and word test now reuse RuleTokens (one copy). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
260 lines
9.3 KiB
GDScript
260 lines
9.3 KiB
GDScript
class_name Builder
|
|
extends RefCounted
|
|
## Structured models for effect statements and conditions that round-trip
|
|
## with the stored rule text (docs/PLAIN.md §2), plus the list of values a
|
|
## board uses (for value pickers).
|
|
##
|
|
## The stored format stays the text (docs/LOGIC.md). A model is only a view of
|
|
## it: parse_*() give {"ok": false} for anything a row-based builder can't
|
|
## show, and the UI then shows that rule as text.
|
|
##
|
|
## Effect model: {"ok": true, "op", "var", "amount"}
|
|
## op "set" (=), "add" (+=), "subtract" (-=), "multiply" (*=),
|
|
## "divide" (/=), "reset", "append" (+= "text"), "remove" (-= "text"),
|
|
## and for scale values "step_up", "step_down", "toward",
|
|
## "at_least", "at_most" (BuilderScales; step_up/down need `board`)
|
|
## var "@name", a chain name ("name"), "@prefix_*" (reset only) or
|
|
## "@[expr]" (indirect, e.g. "@[option]")
|
|
## amount String: the expression as written ("1", "2d6", "\"Aslan\"",
|
|
## "max(@x, 0)"); for append/remove the item text without quotes
|
|
## ("Psionic"); "" for reset
|
|
## Condition model: {"ok": true, "join": "and" | "or", "clauses": [{"var",
|
|
## "cmp", "value"}]}
|
|
## var "@name", "@[expr]" or a chain name ("option_value", "tier")
|
|
## cmp "eq" "ne" "ge" "le" "gt" "lt" "has" (list contains) "set"
|
|
## (truthy) "unset" (not truthy)
|
|
## value String token as written: a number ("8", "-2", "2.5"), quoted
|
|
## text ("\"Aslan\""), "@name", a chain name, "true"/"false";
|
|
## "" for set/unset
|
|
## An empty condition is {"ok": true, "join": "and", "clauses": []}.
|
|
## Round trips are exact on models: parse_x(x_text(m)) == m for any model a
|
|
## parse gave. Text -> model -> text may normalize spacing and "==" to "=".
|
|
|
|
const EFFECT_OPS := {"set": "=", "add": "+=", "subtract": "-=", "multiply": "*=", "divide": "/="}
|
|
const CMPS := {"eq": "=", "ne": "!=", "ge": ">=", "le": "<=", "gt": ">", "lt": "<"}
|
|
const _CMP_OF := {"=": "eq", "==": "eq", "!=": "ne", ">=": "ge", "<=": "le", ">": "gt", "<": "lt"}
|
|
## Chain values the engine sets, with what sets them.
|
|
const CHAIN_NAMES := ["answer", "option", "i", "total", "nat", "effect"]
|
|
|
|
|
|
# ---------------------------------------------------------------- effects
|
|
|
|
## Parses one effect statement into a model, or {"ok": false, "error"} when
|
|
## it doesn't fit (a parse error, or an amount that isn't an expression).
|
|
## With `board`, += / -= on a scale value read as step_up / step_down.
|
|
static func parse_effect(stmt: String, board: TowerBoard = null) -> Dictionary:
|
|
var m := _parse_effect(stmt)
|
|
return BuilderScales.refine(m, m.get("ok", false) and BuilderScales.is_scale(str(m["var"]), board))
|
|
|
|
|
|
static func _parse_effect(stmt: String) -> Dictionary:
|
|
var src := stmt.strip_edges()
|
|
if src == "":
|
|
return {"ok": false, "error": "Empty statement"}
|
|
var st := Effects.parse_statement(src)
|
|
if st.has("error"):
|
|
return {"ok": false, "error": str(st["error"])}
|
|
var target := str(st["target"])
|
|
if st.has("target_expr"):
|
|
target = "@[%s]" % str(st["target_expr"]).strip_edges()
|
|
if Expr.check(str(st["target_expr"])) != "":
|
|
return {"ok": false, "error": Expr.check(str(st["target_expr"]))}
|
|
var op := str(st["op"])
|
|
if op == "reset":
|
|
return {"ok": true, "op": "reset", "var": target, "amount": ""}
|
|
var amount := str(st["expr"]).strip_edges()
|
|
var err := Expr.check(amount)
|
|
if err != "":
|
|
return {"ok": false, "error": err}
|
|
var name := ""
|
|
match op:
|
|
"=":
|
|
name = "set"
|
|
"+=":
|
|
name = "add"
|
|
"-=":
|
|
name = "subtract"
|
|
"*=":
|
|
name = "multiply"
|
|
"/=":
|
|
name = "divide"
|
|
if (op == "+=" or op == "-=") and is_text_literal(amount):
|
|
return {"ok": true, "op": "append" if op == "+=" else "remove", "var": target, "amount": unquote(amount)}
|
|
return {"ok": true, "op": name, "var": target, "amount": amount}
|
|
|
|
|
|
## The statement for a model ("" when the model isn't valid).
|
|
static func effect_text(m: Dictionary) -> String:
|
|
var op := str(m.get("op", ""))
|
|
var v := str(m.get("var", "")).strip_edges()
|
|
var amount := str(m.get("amount", "")).strip_edges() if m.get("amount") != null else ""
|
|
if v == "":
|
|
return ""
|
|
if BuilderScales.OPS.has(op):
|
|
return BuilderScales.text(op, v, amount)
|
|
match op:
|
|
"reset":
|
|
return "reset " + v
|
|
"append":
|
|
return "%s += %s" % [v, quote(str(m.get("amount", "")))]
|
|
"remove":
|
|
return "%s -= %s" % [v, quote(str(m.get("amount", "")))]
|
|
if not EFFECT_OPS.has(op) or amount == "":
|
|
return ""
|
|
return "%s %s %s" % [v, EFFECT_OPS[op], amount]
|
|
|
|
|
|
## Every statement of an effects field as a model (ok or not), in order.
|
|
static func parse_effects(text: String, board: TowerBoard = null) -> Array[Dictionary]:
|
|
var out: Array[Dictionary] = []
|
|
for s in Effects.split(text):
|
|
var m := parse_effect(s, board)
|
|
m["src"] = s
|
|
out.append(m)
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------- conditions
|
|
|
|
## Parses a condition into a model, or {"ok": false, "error"} for mixed
|
|
## and/or, parentheses, dice, function calls other than has(), or anything
|
|
## else that isn't a list of simple comparisons.
|
|
static func parse_condition(expr: String) -> Dictionary:
|
|
var src := expr.strip_edges()
|
|
if src == "":
|
|
return {"ok": true, "join": "and", "clauses": []}
|
|
var toks := tokens(src)
|
|
if toks.is_empty():
|
|
return {"ok": false, "error": "Can't read this as simple comparisons"}
|
|
var groups: Array = [[]]
|
|
var join := ""
|
|
for tk: Dictionary in toks:
|
|
if tk["t"] == "kw" and (tk["s"] == "and" or tk["s"] == "or"):
|
|
if join != "" and join != tk["s"]:
|
|
return {"ok": false, "error": "Mixes and with or"}
|
|
join = tk["s"]
|
|
groups.append([])
|
|
else:
|
|
(groups.back() as Array).append(tk)
|
|
var clauses: Array = []
|
|
for g: Array in groups:
|
|
var c := _clause(g)
|
|
if c.is_empty():
|
|
return {"ok": false, "error": "Can't read this as simple comparisons"}
|
|
clauses.append(c)
|
|
return {"ok": true, "join": join if join != "" else "and", "clauses": clauses}
|
|
|
|
|
|
## The condition text for a model ("" for no clauses or an invalid model).
|
|
static func condition_text(m: Dictionary) -> String:
|
|
var parts := PackedStringArray()
|
|
for c: Variant in m.get("clauses", []):
|
|
if not (c is Dictionary):
|
|
return ""
|
|
var t := clause_text(c)
|
|
if t == "":
|
|
return ""
|
|
parts.append(t)
|
|
var join := str(m.get("join", "and"))
|
|
if join != "and" and join != "or":
|
|
join = "and"
|
|
return (" %s " % join).join(parts)
|
|
|
|
|
|
## One clause as text: "@str >= 8", "has(@traits, \"Psionic\")", "@x",
|
|
## "not @x". "" when it isn't valid.
|
|
static func clause_text(c: Dictionary) -> String:
|
|
var v := str(c.get("var", "")).strip_edges()
|
|
var cmp := str(c.get("cmp", ""))
|
|
var value := str(c.get("value", "")).strip_edges() if c.get("value") != null else ""
|
|
if v == "":
|
|
return ""
|
|
match cmp:
|
|
"set":
|
|
return v
|
|
"unset":
|
|
return "not " + v
|
|
"has":
|
|
return "has(%s, %s)" % [v, value] if value != "" else ""
|
|
if not CMPS.has(cmp) or value == "":
|
|
return ""
|
|
return "%s %s %s" % [v, CMPS[cmp], value]
|
|
|
|
|
|
static func _clause(g: Array) -> Dictionary:
|
|
var n := g.size()
|
|
if n == 1 and _is_subject(g[0]):
|
|
return {"var": g[0]["s"], "cmp": "set", "value": ""}
|
|
if n == 2 and g[0]["t"] == "kw" and g[0]["s"] == "not" and _is_subject(g[1]):
|
|
return {"var": g[1]["s"], "cmp": "unset", "value": ""}
|
|
if n == 3 and _is_subject(g[0]) and g[1]["t"] == "op" and _CMP_OF.has(g[1]["s"]):
|
|
var val := _value(g, 2)
|
|
if val != "":
|
|
return {"var": g[0]["s"], "cmp": _CMP_OF[g[1]["s"]], "value": val}
|
|
if n == 4 and _is_subject(g[0]) and g[1]["t"] == "op" and _CMP_OF.has(g[1]["s"]) and g[2]["s"] == "-" and g[3]["t"] == "num":
|
|
return {"var": g[0]["s"], "cmp": _CMP_OF[g[1]["s"]], "value": "-" + str(g[3]["s"])}
|
|
# has(@list, value)
|
|
if (n == 6 or n == 7) and g[0]["t"] == "name" and g[0]["s"] == "has" and g[1]["s"] == "(" and _is_subject(g[2]) \
|
|
and g[3]["s"] == "," and g[n - 1]["s"] == ")":
|
|
var hv := ""
|
|
if n == 6:
|
|
hv = _value(g, 4)
|
|
elif g[4]["s"] == "-" and g[5]["t"] == "num":
|
|
hv = "-" + str(g[5]["s"])
|
|
if hv != "":
|
|
return {"var": g[2]["s"], "cmp": "has", "value": hv}
|
|
return {}
|
|
|
|
|
|
static func _is_subject(tk: Dictionary) -> bool:
|
|
return tk["t"] == "var" or (tk["t"] == "name" and not ["has", "true", "false"].has(tk["s"]))
|
|
|
|
|
|
static func _value(g: Array, k: int) -> String:
|
|
var tk: Dictionary = g[k]
|
|
match str(tk["t"]):
|
|
"num", "str", "var":
|
|
return tk["s"]
|
|
"name":
|
|
return tk["s"]
|
|
return ""
|
|
|
|
|
|
# ---------------------------------------------------------------- tokens
|
|
|
|
## Splits a rule into tokens (RuleTokens.tokenize): Array of {"t": type,
|
|
## "s": text}, or [] when it can't.
|
|
static func tokens(src: String) -> Array:
|
|
return RuleTokens.tokenize(src)
|
|
|
|
|
|
static func _is_word(ch: String) -> bool:
|
|
return RuleTokens.is_word(ch)
|
|
|
|
|
|
## [count, sides] of a dice token (RuleTokens.dice_parts), or [].
|
|
static func dice_parts(word: String) -> Array:
|
|
return RuleTokens.dice_parts(word)
|
|
|
|
|
|
## True when `text` is one quoted text literal ("Aslan" or 'Aslan').
|
|
static func is_text_literal(text: String) -> bool:
|
|
return RuleTokens.is_text_literal(text)
|
|
|
|
|
|
## A quoted literal's text (RuleTokens.unquote).
|
|
static func unquote(text: String) -> String:
|
|
return RuleTokens.unquote(text)
|
|
|
|
|
|
## Text as a double-quoted literal, escaping \ and ".
|
|
static func quote(text: String) -> String:
|
|
return RuleTokens.quote(text)
|
|
|
|
|
|
# ---------------------------------------------------------------- values
|
|
|
|
## Every value the board uses, for value pickers (BuilderValues.known_values
|
|
## lists the item keys).
|
|
static func known_values(board: TowerBoard) -> Array[Dictionary]:
|
|
return BuilderValues.known_values(board)
|