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") ## 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"] static var _dice_re: RegEx = null static var _num_re: RegEx = null # ---------------------------------------------------------------- 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). 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 "" 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) -> Array[Dictionary]: var out: Array[Dictionary] = [] for s in Effects.split(text): var m := parse_effect(s) 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: Array of {"t": type, "s": text}, or [] when it ## can't (an unclosed quote or bracket, a stray character, "2x"). Types: ## "var" (@name, lowercased, or @[expr] as written), "prefix" (@name_*), ## "name" (a chain name or function), "num", "dice" (2d6, D3, 2D), "str" (a ## quoted text, quotes included), "op" (+ - * / % ( ) , = == != < <= > >=), ## "kw" (and, or, not; && || ! are read as these). static func tokens(src: String) -> Array: var out: Array = [] var i := 0 var n := src.length() while i < n: var c := src[i] if c == " " or c == "\t" or c == "\n": i += 1 continue if c == "\"" or c == "'": var j := i + 1 while j < n and src[j] != c: if src[j] == "\\": j += 1 j += 1 if j >= n: return [] out.append({"t": "str", "s": src.substr(i, j - i + 1)}) i = j + 1 continue if c == "@": if i + 1 < n and src[i + 1] == "[": var close := Expr.bracket_end(src, i + 1) if close < 0: return [] out.append({"t": "var", "s": "@[%s]" % src.substr(i + 2, close - i - 2).strip_edges()}) i = close + 1 continue var j2 := i + 1 while j2 < n and _is_word(src[j2]): j2 += 1 var nm := src.substr(i + 1, j2 - i - 1).to_lower() if nm == "" or nm[0].is_valid_int(): return [] if j2 < n and src[j2] == "*": out.append({"t": "prefix", "s": "@%s*" % nm}) i = j2 + 1 else: out.append({"t": "var", "s": "@" + nm}) i = j2 continue if _is_word(c): var j3 := i while j3 < n and (_is_word(src[j3]) or (src[j3] == "." and j3 + 1 < n and src[j3 + 1].is_valid_int())): j3 += 1 var w := src.substr(i, j3 - i) i = j3 if _num().search(w) != null: out.append({"t": "num", "s": w}) elif _dice().search(w) != null and w.length() > 1: out.append({"t": "dice", "s": w}) elif w[0].is_valid_int(): return [] elif ["and", "or", "not"].has(w.to_lower()) and w == w.to_lower(): out.append({"t": "kw", "s": w}) else: out.append({"t": "name", "s": w}) continue var two := src.substr(i, 2) if two in [">=", "<=", "!=", "=="]: out.append({"t": "op", "s": two}) i += 2 continue if two == "&&" or two == "||": out.append({"t": "kw", "s": "and" if two == "&&" else "or"}) i += 2 continue if c == "!": out.append({"t": "kw", "s": "not"}) i += 1 continue if c in ["+", "-", "*", "/", "%", "(", ")", ",", "=", "<", ">"]: out.append({"t": "op", "s": c}) i += 1 continue return [] return out static func _is_word(c: String) -> bool: return c == "_" or c.is_valid_int() or (c.to_lower() != c.to_upper()) static func _dice() -> RegEx: if _dice_re == null: _dice_re = RegEx.create_from_string("^(\\d*)[dD](\\d*)$") return _dice_re static func _num() -> RegEx: if _num_re == null: _num_re = RegEx.create_from_string("^\\d+(\\.\\d+)?$") return _num_re ## [count, sides] of a dice token ("2d6" -> [2, 6], "D3" -> [1, 3], "2D" -> ## [2, 6]), or []. static func dice_parts(word: String) -> Array: var m := _dice().search(word) if m == null or word.length() < 2: return [] var a := m.get_string(1) var b := m.get_string(2) return [int(a) if a != "" else 1, int(b) if b != "" else 6] ## True when `s` is one quoted text literal ("Aslan" or 'Aslan'). static func is_text_literal(s: String) -> bool: var t := tokens(s.strip_edges()) return t.size() == 1 and t[0]["t"] == "str" ## A quoted literal's text: "\"Aslan\"" -> "Aslan" (\" and \\ unescaped). ## Anything else comes back as it is. static func unquote(s: String) -> String: s = s.strip_edges() if s.length() < 2 or not ((s.begins_with("\"") and s.ends_with("\"")) or (s.begins_with("'") and s.ends_with("'"))): return s var inner := s.substr(1, s.length() - 2) var out := "" var k := 0 while k < inner.length(): var ch := inner[k] if ch == "\\" and k + 1 < inner.length(): k += 1 ch = inner[k] out += ch k += 1 return out ## Text as a double-quoted literal, escaping \ and ". static func quote(s: String) -> String: return "\"%s\"" % s.replace("\\", "\\\\").replace("\"", "\\\"") # ---------------------------------------------------------------- values ## Every value the board uses, for value pickers: Array of {"name", "label", ## "kind", "source"} with optional extras, variable cards first, then ## collections, then the rest in board order, then chain names. One item per ## name (the first source wins). ## name "@luck" (board value), "@skill_*" (a collection), "tier" (chain) ## label Describe.label(name, board) ## kind "number", "text", "list" or "collection" ## source "variable" (a variable card), "collection", "effect" (an effect ## target), "save_as" (a pipe's or choice's save_as, or ## [[Table -> name]]), "input" (a card input), "read" (only read by ## a rule), "chain" (answer, option, i, total, nat, effect) ## table_id the card that declares, sets or reads it first ## collection on members of a collection: its pattern ("@skill_*") ## Chain names are listed only when the board has a card that sets them ## (answer: number/text choices; option: options from variables; i: loops; ## nat: roll tables and checks; total/effect: checks). static func known_values(board: TowerBoard) -> Array[Dictionary]: var out: Array[Dictionary] = [] if board == null: return out var seen := {} var stems: Array = [] # [stem, pattern] var add := func(name: String, kind: String, source: String, tid: String) -> void: if name == "" or seen.has(name): return seen[name] = true var item := {"name": name, "label": Describe.label(name, board), "kind": kind, "source": source, "table_id": tid} if name.begins_with("@") and not name.ends_with("*"): for sp: Array in stems: if name.begins_with("@" + str(sp[0]) + "_") and name.length() > str(sp[0]).length() + 2: item["collection"] = sp[1] break out.append(item) for t in board.tables: if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and not t.is_collection(): add.call("@" + t.var_name, t.var_type, "variable", t.id) for t in board.tables: if t.is_collection() and t.var_name != "": stems.append([t.var_name, "@%s_*" % t.var_name]) stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length()) for t in board.tables: if t.is_collection() and t.var_name != "": add.call("@%s_*" % t.var_name, "collection", "collection", t.id) var reads: Array = [] var chain := {} for t in board.tables: match t.kind: RollTable.KIND_CHOICE: if t.choice != "pick": chain["answer"] = true if t.save_as != "": add.call(_value_name(t.save_as), "number" if t.choice == "number" else "text", "save_as", t.id) else: if t.is_dynamic(): chain["option"] = true if t.save_as != "": add.call(_value_name(t.save_as), "text", "save_as", t.id) reads.append([t.options_where, t.id]) reads.append([t.min_expr, t.id]) reads.append([t.max_expr, t.id]) RollTable.KIND_LOOP: chain["i"] = true reads.append([t.loop_expr, t.id]) RollTable.KIND_CHECK: chain["nat"] = true chain["total"] = true chain["effect"] = true reads.append([t.check_dice, t.id]) reads.append([t.check_mod, t.id]) reads.append([t.check_target, t.id]) RollTable.KIND_ROLL: chain["nat"] = true if t.is_expr_dice(): reads.append([t.dice, t.id]) for inp: Dictionary in t.inputs: add.call(str(inp.get("name", "")), _kind_of_expr(str(inp.get("default", ""))), "input", t.id) for e in t.entries: for m in parse_effects(e.effects): if not m["ok"]: continue var v := str(m["var"]) if v.begins_with("@[") or v.ends_with("*"): continue var k := "number" match str(m["op"]): "append", "remove": k = "list" "set": k = "text" if is_text_literal(str(m["amount"])) else "number" add.call(v, k, "effect", t.id) if m["op"] != "reset": reads.append([str(m["amount"]), t.id]) for p in e.pipes: var sv := e.save_for(p) if sv != "": add.call(_value_name(sv), "text", "save_as", t.id) reads.append([e.when_for(p), t.id]) reads.append([e.count_expr(p), t.id]) var w := e.with_for(p) for nm: String in w: reads.append([str(w[nm]), t.id]) for ref in JsonIO.find_refs(e.text): if str(ref["var"]) != "": add.call(_value_name(str(ref["var"])), "text", "save_as", t.id) reads.append([e.when, t.id]) reads.append([e.show_if, t.id]) for r: Array in reads: var src := str(r[0]).strip_edges() if src == "" or not src.contains("@"): continue for tk: Dictionary in tokens(src): if tk["t"] == "var" and not str(tk["s"]).begins_with("@["): add.call(str(tk["s"]), "number", "read", str(r[1])) for nm: String in CHAIN_NAMES: if chain.has(nm): add.call(nm, "text" if nm == "option" else "number", "chain", "") return out static func _value_name(s: String) -> String: var t := s.strip_edges() return "@" + t.substr(1).to_lower() if t.begins_with("@") else t static func _kind_of_expr(src: String) -> String: return "text" if is_text_literal(src) else "number"