diff --git a/core/board_checks.gd b/core/board_checks.gd new file mode 100644 index 0000000..eba132d --- /dev/null +++ b/core/board_checks.gd @@ -0,0 +1,131 @@ +class_name BoardChecks +extends RefCounted +## Checks a board without rolling anything: bad expressions and effects, +## range gaps, threads to missing tables, choice cards with no options and +## endless cycles. Also picks the tables worth starting a test from. +## BoardTester delegates here. + + +## Problems found without rolling anything. Array of {kind, table_id, +## entry_id ("" for the card), table (display name), text}, in board order. +## kinds: expression, effect, range, cycle, missing_pipe, empty_choice, pipes, +## check (check cards: bad dice, modifier or target, missing results) and +## inputs (card inputs and pipe "with" values; see Roller.lint_inputs()). +## Items from Roller.lint_pipes() also carry its "level" when it has one +## ("error" or "hint"). +static func static_checks(board: TowerBoard) -> Array[Dictionary]: + var out: Array[Dictionary] = [] + var add := func(kind: String, table: RollTable, entry_id: String, text: String) -> void: + out.append({"kind": kind, "table_id": table.id, "entry_id": entry_id, "table": Formatter.strip_tags(table.name), "text": text}) + for table in board.tables: + _check_table(board, table, add) + for id in Roller.endless_cycles(board): + var table := board.get_table(id) + add.call("cycle", table, "", "Can never finish: every result leads back into an endless cycle.") + _add_lint(board, out, add) + return out + + +## The checks for one card and its results; `add` records each problem. +static func _check_table(board: TowerBoard, table: RollTable, add: Callable) -> void: + var expr := func(what: String, src: String, entry_id: String = "") -> void: + if src.strip_edges() == "": + return + var err := Expr.check(src) + if err != "": + add.call("expression", table, entry_id, "%s \"%s\": %s" % [what, src, err]) + if table.is_expr_dice(): + expr.call("Dice", table.dice) + if table.is_ranged(): + expr.call("Modifier", table.dice_mod) + if table.is_ranged(): + var range_problem := table.range_problems() + if range_problem != "": + add.call("range", table, "", range_problem) + match table.kind: + RollTable.KIND_LOOP: + expr.call("Repeat rule", table.loop_expr) + RollTable.KIND_CHOICE: + if table.choice == "pick" and table.entries.is_empty(): + add.call("empty_choice", table, "", "Choice card has no options.") + if table.choice == "number": + expr.call("Minimum", table.min_expr) + expr.call("Maximum", table.max_expr) + _check_braces(table.prompt, func(src: String) -> void: expr.call("Prompt", src)) + RollTable.KIND_VARIABLE: + var init := table.initial.strip_edges() + if table.var_type == "number" and init != "" and not init.is_valid_float(): + expr.call("Initial value", init) + for entry in table.entries: + _check_braces(entry.text, func(src: String) -> void: expr.call("Text", src, entry.id)) + for problem in Effects.validate(entry.effects): + add.call("effect", table, entry.id, "Change \"%s\": %s" % [problem["src"], problem["error"]]) + for target in entry.pipes: + if board.get_table(target) == null: + add.call("missing_pipe", table, entry.id, "Thread to a table that doesn't exist (%s)." % target) + var count_expr := entry.count_expr(target) + if count_expr != "": + expr.call("Thread count", count_expr, entry.id) + + +## Adds the items from Roller.lint_pipes(), when the Roller has it. +static func _add_lint(board: TowerBoard, out: Array[Dictionary], add: Callable) -> void: + var roller: GDScript = Roller + var has_lint := false + for method in roller.get_script_method_list(): + if method["name"] == "lint_pipes": + has_lint = true + if not has_lint: + return + var lint: Variant = roller.call("lint_pipes", board) + if not (lint is Array): + return + for item: Variant in lint: + var table: RollTable = null + var entry_id := "" + var text := str(item) + var lint_kind := "pipes" + var level := "" + if item is Dictionary: + var details: Dictionary = item + table = board.get_table(str(details.get("table_id", details.get("table", "")))) + entry_id = str(details.get("entry_id", details.get("entry", ""))) + text = str(details.get("text", details.get("message", details.get("problem", text)))) + lint_kind = str(details.get("kind", "pipes")) + level = str(details.get("level", "")) + if table == null: + table = RollTable.new("", "") + add.call(lint_kind, table, entry_id, text) + if level != "": + out.back()["level"] = level + + +## Calls `on_expr(src)` for each `{= expr}` in the text. +static func _check_braces(text: String, on_expr: Callable) -> void: + var brace_re := RegEx.create_from_string("\\{=([^}]*)\\}") + for found in brace_re.search_all(text): + on_expr.call(found.get_string(1)) + + +## Tables worth starting a test from: not variable cards, with nothing piping +## into them and nothing referencing them by [[name]]. If `last_rolled` is a +## table it comes first (even if it isn't a root). Ids in board order. +static func start_candidates(board: TowerBoard, last_rolled: String = "") -> Array[String]: + var used := {} + for table in board.tables: + for entry in table.entries: + for pipe in entry.pipes: + used[pipe] = true + for ref in Roller.ref_targets(board, entry.text): + used[ref] = true + for ref in Roller.ref_targets(board, table.prompt): + used[ref] = true + var out: Array[String] = [] + for table in board.tables: + if table.kind != RollTable.KIND_VARIABLE and not used.has(table.id): + out.append(table.id) + var last_table := board.get_table(last_rolled) + if last_table != null and last_table.kind != RollTable.KIND_VARIABLE: + out.erase(last_table.id) + out.push_front(last_table.id) + return out diff --git a/core/board_checks.gd.uid b/core/board_checks.gd.uid new file mode 100644 index 0000000..abf07c1 --- /dev/null +++ b/core/board_checks.gd.uid @@ -0,0 +1 @@ +uid://burrp8dm7hha0 diff --git a/core/board_report_text.gd b/core/board_report_text.gd new file mode 100644 index 0000000..55eb7f5 --- /dev/null +++ b/core/board_report_text.gd @@ -0,0 +1,96 @@ +class_name BoardReportText +extends RefCounted +## Turns a board test's results into plain text lines: the static problems +## and the simulation report (runs, halts, errors, dead ends, tables never +## reached ...). Used by the Test board window and tools/simulate_board.gd. +## BoardTester delegates here. + + +## True when no run hit an error, a dead end or the action limit. +static func is_clean(report: Dictionary) -> bool: + return (report["errors"] as Array).is_empty() and (report["dead_ends"] as Array).is_empty() \ + and not (report["halted"] as Dictionary).has("Action limit") + + +## The static problems as text lines (for the CLI's --check and Copy report). +static func format_problems(problems: Array, list: int = 40) -> PackedStringArray: + var out := PackedStringArray() + out.append("Static problems: %d" % problems.size()) + for i in mini(list, problems.size()): + var problem: Dictionary = problems[i] + var where: String = "%s (%s)" % [problem["table"], problem["table_id"]] + if str(problem["entry_id"]) != "": + where += ", result " + str(problem["entry_id"]) + out.append(" %s: %s" % [where, problem["text"]]) + if problems.size() > list: + out.append(" ... and %d more" % (problems.size() - list)) + return out + + +## The simulation report as text; `list` caps each section's lines. +static func format_report(report: Dictionary, list: int = 40, show_sheet: bool = true) -> String: + var out := PackedStringArray() + var actions: Dictionary = report["actions"] + out.append("Runs: %d completed: %d prompts per run: %.1f" % [report["runs"], report["completed"], report["prompts_mean"]]) + var halt_parts := PackedStringArray() + for reason: String in report["halted"]: + halt_parts.append("%s %d" % [reason, report["halted"][reason]]) + out.append("Halted: %s" % (", ".join(halt_parts) if not halt_parts.is_empty() else "none")) + out.append("Actions: max %d, mean %.1f, p95 %d" % [actions["max"], actions["mean"], actions["p95"]]) + var longest: Dictionary = report.get("longest", {}) + if not (longest.get("top", []) as Array).is_empty(): + var parts := PackedStringArray() + for hit: Dictionary in longest["top"]: + parts.append("%s %d" % [hit["table"], hit["count"]]) + out.append("Longest run (#%d) most-rolled tables: %s" % [longest["run"], ", ".join(parts)]) + var track: Dictionary = report.get("track", {}) + for name: String in track: + var stats: Dictionary = track[name] + if int(stats["n"]) == 0: + out.append("@%s: never a number" % name) + else: + out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(stats["min"]), stats["sum"] / stats["n"], Expr.format_value(stats["max"]), stats["n"]]) + _section(out, "Change / expression errors", report["errors"], list, func(item: Dictionary) -> String: + return "%dx %s, result \"%s\": %s" % [item["count"], item["table"], item["entry"], item["text"]]) + _section(out, "Dead ends (rolls that stopped)", report["dead_ends"], list, func(item: Dictionary) -> String: + return "%dx %s: %s" % [item["count"], item["table"], item["text"]]) + _section(out, "Unset variables, missing tables and {= } errors in text", report["unset_markers"], list, func(item: Dictionary) -> String: + return "%dx %s, result \"%s\": %s" % [item["count"], item["table"], item["entry"], item["text"]]) + var unreached: Array = report["unreached"] + out.append("Tables never reached: %d" % unreached.size()) + for i in mini(list, unreached.size()): + out.append(" " + str(unreached[i])) + if unreached.size() > list: + out.append(" ... and %d more" % (unreached.size() - list)) + _unchosen_lines(out, report["unchosen"], list) + if show_sheet: + out.append("Sample final sheet%s:" % (" (" + str(report["sample_halted"]) + ")" if str(report["sample_halted"]) != "" else "")) + out.append(str(report["sample_sheet"]) if str(report["sample_sheet"]) != "" else " (no sheet card was reached)") + return "\n".join(out) + + +## The "Results never chosen" lines: {table id: [entry texts]}. +static func _unchosen_lines(out: PackedStringArray, unchosen: Dictionary, list: int) -> void: + var entry_count := 0 + for table_id: String in unchosen: + entry_count += (unchosen[table_id] as Array).size() + out.append("Results never chosen: %d in %d reached cards" % [entry_count, unchosen.size()]) + var shown := 0 + for table_id: String in unchosen: + if shown >= list: + out.append(" ... and %d more tables" % (unchosen.size() - shown)) + break + var items: Array = unchosen[table_id] + var names := PackedStringArray() + for i in mini(4, items.size()): + names.append("\"%s\"" % items[i]) + out.append(" %s: %d (%s%s)" % [table_id, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""]) + shown += 1 + + +static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void: + out.append("%s: %d" % [title, items.size()]) + for i in mini(list, items.size()): + out.append(" " + str(fmt.call(items[i]))) + if items.size() > list: + out.append(" ... and %d more" % (items.size() - list)) diff --git a/core/board_report_text.gd.uid b/core/board_report_text.gd.uid new file mode 100644 index 0000000..746591b --- /dev/null +++ b/core/board_report_text.gd.uid @@ -0,0 +1 @@ +uid://dnt3w5wbp4rb4 diff --git a/core/board_tester.gd b/core/board_tester.gd index 98b76ac..297f847 100644 --- a/core/board_tester.gd +++ b/core/board_tester.gd @@ -248,119 +248,17 @@ func report() -> Dictionary: } -# ---------- Static checks ---------- +# ---------- Static checks (BoardChecks) ---------- -## Problems found without rolling anything. Array of {kind, table_id, -## entry_id ("" for the card), table (display name), text}, in board order. -## kinds: expression, effect, range, cycle, missing_pipe, empty_choice, pipes, -## check (check cards: bad dice, modifier or target, missing results) and -## inputs (card inputs and pipe "with" values; see Roller.lint_inputs()). -## Items from Roller.lint_pipes() also carry its "level" when it has one -## ("error" or "hint"). -static func static_checks(b: TowerBoard) -> Array[Dictionary]: - var out: Array[Dictionary] = [] - var add := func(kind: String, t: RollTable, eid: String, text: String) -> void: - out.append({"kind": kind, "table_id": t.id, "entry_id": eid, "table": Formatter.strip_tags(t.name), "text": text}) - for t in b.tables: - var expr := func(what: String, src: String, eid: String = "") -> void: - if src.strip_edges() == "": - return - var err := Expr.check(src) - if err != "": - add.call("expression", t, eid, "%s \"%s\": %s" % [what, src, err]) - if t.is_expr_dice(): - expr.call("Dice", t.dice) - if t.is_ranged(): - expr.call("Modifier", t.dice_mod) - if t.is_ranged(): - var rp := t.range_problems() - if rp != "": - add.call("range", t, "", rp) - match t.kind: - RollTable.KIND_LOOP: - expr.call("Repeat rule", t.loop_expr) - RollTable.KIND_CHOICE: - if t.choice == "pick" and t.entries.is_empty(): - add.call("empty_choice", t, "", "Choice card has no options.") - if t.choice == "number": - expr.call("Minimum", t.min_expr) - expr.call("Maximum", t.max_expr) - _check_braces(t.prompt, func(src: String) -> void: expr.call("Prompt", src)) - RollTable.KIND_VARIABLE: - var init := t.initial.strip_edges() - if t.var_type == "number" and init != "" and not init.is_valid_float(): - expr.call("Initial value", init) - for e in t.entries: - _check_braces(e.text, func(src: String) -> void: expr.call("Text", src, e.id)) - for p in Effects.validate(e.effects): - add.call("effect", t, e.id, "Change \"%s\": %s" % [p["src"], p["error"]]) - for target in e.pipes: - if b.get_table(target) == null: - add.call("missing_pipe", t, e.id, "Thread to a table that doesn't exist (%s)." % target) - var ce := e.count_expr(target) - if ce != "": - expr.call("Thread count", ce, e.id) - for id in Roller.endless_cycles(b): - var t := b.get_table(id) - add.call("cycle", t, "", "Can never finish: every result leads back into an endless cycle.") - var roller: GDScript = Roller - var has_lint := false - for m in roller.get_script_method_list(): - if m["name"] == "lint_pipes": - has_lint = true - if has_lint: - var lint: Variant = roller.call("lint_pipes", b) - if lint is Array: - for item: Variant in lint: - var t: RollTable = null - var eid := "" - var text := str(item) - var lkind := "pipes" - var level := "" - if item is Dictionary: - var d: Dictionary = item - t = b.get_table(str(d.get("table_id", d.get("table", "")))) - eid = str(d.get("entry_id", d.get("entry", ""))) - text = str(d.get("text", d.get("message", d.get("problem", text)))) - lkind = str(d.get("kind", "pipes")) - level = str(d.get("level", "")) - if t == null: - t = RollTable.new("", "") - add.call(lkind, t, eid, text) - if level != "": - out.back()["level"] = level - return out +## Problems found without rolling anything (BoardChecks.static_checks lists +## the item keys and kinds). +static func static_checks(board_to_check: TowerBoard) -> Array[Dictionary]: + return BoardChecks.static_checks(board_to_check) -## Calls `f(src)` for each `{= expr}` in the text. -static func _check_braces(text: String, f: Callable) -> void: - var re := RegEx.create_from_string("\\{=([^}]*)\\}") - for m in re.search_all(text): - f.call(m.get_string(1)) - - -## Tables worth starting a test from: not variable cards, with nothing piping -## into them and nothing referencing them by [[name]]. If `last_rolled` is a -## table it comes first (even if it isn't a root). Ids in board order. -static func start_candidates(b: TowerBoard, last_rolled: String = "") -> Array[String]: - var used := {} - for t in b.tables: - for e in t.entries: - for p in e.pipes: - used[p] = true - for r in Roller.ref_targets(b, e.text): - used[r] = true - for r in Roller.ref_targets(b, t.prompt): - used[r] = true - var out: Array[String] = [] - for t in b.tables: - if t.kind != RollTable.KIND_VARIABLE and not used.has(t.id): - out.append(t.id) - var lr := b.get_table(last_rolled) - if lr != null and lr.kind != RollTable.KIND_VARIABLE: - out.erase(lr.id) - out.push_front(lr.id) - return out +## Tables worth starting a test from (BoardChecks.start_candidates). +static func start_candidates(board_to_check: TowerBoard, last_rolled: String = "") -> Array[String]: + return BoardChecks.start_candidates(board_to_check, last_rolled) # ---------- Answers and report text ---------- @@ -392,87 +290,17 @@ static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx = ## True when no run hit an error, a dead end or the action limit. static func is_clean(r: Dictionary) -> bool: - return (r["errors"] as Array).is_empty() and (r["dead_ends"] as Array).is_empty() \ - and not (r["halted"] as Dictionary).has("Action limit") + return BoardReportText.is_clean(r) -## The static problems as text lines (for the CLI's --check and Copy report). +## The static problems as text lines (BoardReportText.format_problems). static func format_problems(problems: Array, list: int = 40) -> PackedStringArray: - var out := PackedStringArray() - out.append("Static problems: %d" % problems.size()) - for k in mini(list, problems.size()): - var p: Dictionary = problems[k] - var where: String = "%s (%s)" % [p["table"], p["table_id"]] - if str(p["entry_id"]) != "": - where += ", result " + str(p["entry_id"]) - out.append(" %s: %s" % [where, p["text"]]) - if problems.size() > list: - out.append(" ... and %d more" % (problems.size() - list)) - return out + return BoardReportText.format_problems(problems, list) +## The report as text (BoardReportText.format_report). static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String: - var out := PackedStringArray() - var a: Dictionary = r["actions"] - out.append("Runs: %d completed: %d prompts per run: %.1f" % [r["runs"], r["completed"], r["prompts_mean"]]) - var hl := PackedStringArray() - for k: String in r["halted"]: - hl.append("%s %d" % [k, r["halted"][k]]) - out.append("Halted: %s" % (", ".join(hl) if not hl.is_empty() else "none")) - out.append("Actions: max %d, mean %.1f, p95 %d" % [a["max"], a["mean"], a["p95"]]) - var lg: Dictionary = r.get("longest", {}) - if not (lg.get("top", []) as Array).is_empty(): - var parts := PackedStringArray() - for x: Dictionary in lg["top"]: - parts.append("%s %d" % [x["table"], x["count"]]) - out.append("Longest run (#%d) most-rolled tables: %s" % [lg["run"], ", ".join(parts)]) - var tr: Dictionary = r.get("track", {}) - for name: String in tr: - var t: Dictionary = tr[name] - if int(t["n"]) == 0: - out.append("@%s: never a number" % name) - else: - out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(t["min"]), t["sum"] / t["n"], Expr.format_value(t["max"]), t["n"]]) - _section(out, "Change / expression errors", r["errors"], list, func(e: Dictionary) -> String: - return "%dx %s, result \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]]) - _section(out, "Dead ends (rolls that stopped)", r["dead_ends"], list, func(e: Dictionary) -> String: - return "%dx %s: %s" % [e["count"], e["table"], e["text"]]) - _section(out, "Unset variables, missing tables and {= } errors in text", r["unset_markers"], list, func(e: Dictionary) -> String: - return "%dx %s, result \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]]) - var un: Array = r["unreached"] - out.append("Tables never reached: %d" % un.size()) - for k in mini(list, un.size()): - out.append(" " + str(un[k])) - if un.size() > list: - out.append(" ... and %d more" % (un.size() - list)) - var uc: Dictionary = r["unchosen"] - var n_entries := 0 - for k: String in uc: - n_entries += (uc[k] as Array).size() - out.append("Results never chosen: %d in %d reached cards" % [n_entries, uc.size()]) - var shown := 0 - for k: String in uc: - if shown >= list: - out.append(" ... and %d more tables" % (uc.size() - shown)) - break - var items: Array = uc[k] - var names := PackedStringArray() - for x in mini(4, items.size()): - names.append("\"%s\"" % items[x]) - out.append(" %s: %d (%s%s)" % [k, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""]) - shown += 1 - if show_sheet: - out.append("Sample final sheet%s:" % (" (" + str(r["sample_halted"]) + ")" if str(r["sample_halted"]) != "" else "")) - out.append(str(r["sample_sheet"]) if str(r["sample_sheet"]) != "" else " (no sheet card was reached)") - return "\n".join(out) - - -static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void: - out.append("%s: %d" % [title, items.size()]) - for k in mini(list, items.size()): - out.append(" " + str(fmt.call(items[k]))) - if items.size() > list: - out.append(" ... and %d more" % (items.size() - list)) + return BoardReportText.format_report(r, list, show_sheet) static func _sorted_by_count(list: Array) -> Array: diff --git a/core/builder.gd b/core/builder.gd index 1e74181..4f14269 100644 --- a/core/builder.gd +++ b/core/builder.gd @@ -36,9 +36,6 @@ const _CMP_OF := {"=": "eq", "==": "eq", "!=": "ne", ">=": "ge", "<=": "le", ">" ## 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 @@ -225,279 +222,39 @@ static func _value(g: Array, k: int) -> String: # ---------------------------------------------------------------- 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). +## Splits a rule into tokens (RuleTokens.tokenize): Array of {"t": type, +## "s": text}, or [] when it can't. 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 + return RuleTokens.tokenize(src) -static func _is_word(c: String) -> bool: - return c == "_" or c.is_valid_int() or (c.to_lower() != c.to_upper()) +static func _is_word(ch: String) -> bool: + return RuleTokens.is_word(ch) -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 []. +## [count, sides] of a dice token (RuleTokens.dice_parts), 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] + return RuleTokens.dice_parts(word) -## 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" +## 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: "\"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 +## 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(s: String) -> String: - return "\"%s\"" % s.replace("\\", "\\\\").replace("\"", "\\\"") +static func quote(text: String) -> String: + return RuleTokens.quote(text) # ---------------------------------------------------------------- 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", "collection" or "scale" -## 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). +## Every value the board uses, for value pickers (BuilderValues.known_values +## lists the item keys). 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: - for col: Dictionary in t.columns: - if str(col.get("save_as", "")) != "": - add.call(_value_name(str(col["save_as"])), "text", "save_as", t.id) - reads.append([str(col.get("when", "")), t.id]) - 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]) - if t.has_mod(): - reads.append([t.dice_mod, 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" + return BuilderValues.known_values(board) diff --git a/core/builder_values.gd b/core/builder_values.gd new file mode 100644 index 0000000..03ced5d --- /dev/null +++ b/core/builder_values.gd @@ -0,0 +1,153 @@ +class_name BuilderValues +extends RefCounted +## Finds every value a board uses (variable cards, collections, effect +## targets, saved answers, card inputs, values rules only read, and chain +## names), so value pickers can offer them. Builder.known_values() delegates +## here. + + +## 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", "collection" or "scale" +## 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, table_id: 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": table_id} + if name.begins_with("@") and not name.ends_with("*"): + for stem_pair: Array in stems: + if name.begins_with("@" + str(stem_pair[0]) + "_") and name.length() > str(stem_pair[0]).length() + 2: + item["collection"] = stem_pair[1] + break + out.append(item) + for table in board.tables: + if table.kind == RollTable.KIND_VARIABLE and table.var_name != "" and not table.is_collection(): + add.call("@" + table.var_name, table.var_type, "variable", table.id) + for table in board.tables: + if table.is_collection() and table.var_name != "": + stems.append([table.var_name, "@%s_*" % table.var_name]) + stems.sort_custom(func(left: Array, right: Array) -> bool: return str(left[0]).length() > str(right[0]).length()) + for table in board.tables: + if table.is_collection() and table.var_name != "": + add.call("@%s_*" % table.var_name, "collection", "collection", table.id) + var reads: Array = [] + var chain := {} + for table in board.tables: + _add_table_values(table, add, reads, chain) + for read: Array in reads: + var src := str(read[0]).strip_edges() + if src == "" or not src.contains("@"): + continue + for token: Dictionary in RuleTokens.tokenize(src): + if token["t"] == "var" and not str(token["s"]).begins_with("@["): + add.call(str(token["s"]), "number", "read", str(read[1])) + for name: String in Builder.CHAIN_NAMES: + if chain.has(name): + add.call(name, "text" if name == "option" else "number", "chain", "") + return out + + +## One card's values: calls `add` for what it sets, appends [rule, table id] +## to `reads` for every rule it reads, and marks in `chain` which chain +## names it sets. +static func _add_table_values(table: RollTable, add: Callable, reads: Array, chain: Dictionary) -> void: + for col: Dictionary in table.columns: + if str(col.get("save_as", "")) != "": + add.call(_value_name(str(col["save_as"])), "text", "save_as", table.id) + reads.append([str(col.get("when", "")), table.id]) + match table.kind: + RollTable.KIND_CHOICE: + if table.choice != "pick": + chain["answer"] = true + if table.save_as != "": + add.call(_value_name(table.save_as), "number" if table.choice == "number" else "text", "save_as", table.id) + else: + if table.is_dynamic(): + chain["option"] = true + if table.save_as != "": + add.call(_value_name(table.save_as), "text", "save_as", table.id) + reads.append([table.options_where, table.id]) + reads.append([table.min_expr, table.id]) + reads.append([table.max_expr, table.id]) + RollTable.KIND_LOOP: + chain["i"] = true + reads.append([table.loop_expr, table.id]) + RollTable.KIND_CHECK: + chain["nat"] = true + chain["total"] = true + chain["effect"] = true + reads.append([table.check_dice, table.id]) + reads.append([table.check_mod, table.id]) + reads.append([table.check_target, table.id]) + RollTable.KIND_ROLL: + chain["nat"] = true + if table.is_expr_dice(): + reads.append([table.dice, table.id]) + if table.has_mod(): + reads.append([table.dice_mod, table.id]) + for inp: Dictionary in table.inputs: + add.call(str(inp.get("name", "")), _kind_of_expr(str(inp.get("default", ""))), "input", table.id) + for entry in table.entries: + _add_entry_values(table, entry, add, reads) + + +## One result's values: its effect targets, saved pipe answers and +## [[Table -> name]] saves, and the rules it reads. +static func _add_entry_values(table: RollTable, entry: TableEntry, add: Callable, reads: Array) -> void: + for model in Builder.parse_effects(entry.effects): + if not model["ok"]: + continue + var target := str(model["var"]) + if target.begins_with("@[") or target.ends_with("*"): + continue + var kind := "number" + match str(model["op"]): + "append", "remove": + kind = "list" + "set": + kind = "text" if RuleTokens.is_text_literal(str(model["amount"])) else "number" + add.call(target, kind, "effect", table.id) + if model["op"] != "reset": + reads.append([str(model["amount"]), table.id]) + for pipe in entry.pipes: + var save_name := entry.save_for(pipe) + if save_name != "": + add.call(_value_name(save_name), "text", "save_as", table.id) + reads.append([entry.when_for(pipe), table.id]) + reads.append([entry.count_expr(pipe), table.id]) + var with_values := entry.with_for(pipe) + for name: String in with_values: + reads.append([str(with_values[name]), table.id]) + for ref in JsonIO.find_refs(entry.text): + if str(ref["var"]) != "": + add.call(_value_name(str(ref["var"])), "text", "save_as", table.id) + reads.append([entry.when, table.id]) + reads.append([entry.show_if, table.id]) + + +static func _value_name(text: String) -> String: + var trimmed := text.strip_edges() + return "@" + trimmed.substr(1).to_lower() if trimmed.begins_with("@") else trimmed + + +static func _kind_of_expr(src: String) -> String: + return "text" if RuleTokens.is_text_literal(src) else "number" diff --git a/core/builder_values.gd.uid b/core/builder_values.gd.uid new file mode 100644 index 0000000..036b746 --- /dev/null +++ b/core/builder_values.gd.uid @@ -0,0 +1 @@ +uid://bol1fdcr805ca diff --git a/core/expr.gd b/core/expr.gd index 7086033..bad3355 100644 --- a/core/expr.gd +++ b/core/expr.gd @@ -19,14 +19,10 @@ extends RefCounted const MAX_DICE := 100 const MAX_SIDES := 1000 -const _KEYWORDS := ["and", "or", "not", "in", "true", "false", "null", "if", "else", - "PI", "TAU", "INF", "NAN", "self"] - ## source text -> {expr: Expression or null, inputs: Array[String] (input ## names in order), vars: Array of [kind, name] per input ("@" board, "" chain), ## text_side: Array[bool] per input (an unset value reads as ""), error: String} static var _cache: Dictionary = {} -static var _dice_re: RegEx = null static var _name_re: RegEx = null @@ -280,7 +276,7 @@ static func roll_dice(n: int, sides: int, rng: RandomNumberGenerator) -> int: ## The rewritten source (for tests and debugging). static func rewrite(src: String) -> String: - return str(_rewrite(src)["text"]) + return str(ExprRewriter.rewrite(src)["text"]) static func _parsed(src: String) -> Dictionary: @@ -290,7 +286,7 @@ static func _parsed(src: String) -> Dictionary: if src.strip_edges() == "": p["error"] = "Empty expression" else: - var rw := _rewrite(src) + var rw := ExprRewriter.rewrite(src) if rw["error"] != "": p["error"] = rw["error"] else: @@ -308,215 +304,3 @@ static func _parsed(src: String) -> Dictionary: _cache.clear() _cache[src] = p return p - - -## Rewrites the user's syntax into Godot Expression syntax. Returns {text, -## inputs, vars, text_side, error}. -static func _rewrite(src: String) -> Dictionary: - var out := "" - var inputs: Array = [] - var vars: Array = [] - var text_side: Array = [] - var slot := {} # "@name" / "name" -> input index - # Open brackets: true for an indirect @[ (closes with ")"), false for a - # plain "[". - var brackets: Array[bool] = [] - var n_ind := 0 - # Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side). - var toks: Array = [] - var lits: Array[String] = [] - var i := 0 - var n := src.length() - while i < n: - var c := src[i] - 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 {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "A text value is missing its closing quote"} - var lit := src.substr(i, j - i + 1) - # A placeholder: a step name beside a scale value becomes its number - # (ExprBase._lit), worked out below once the variables are known. - out += "\u0002%d\u0002" % lits.size() - toks.append(["str", lit, lits.size()]) - lits.append(lit) - i = j + 1 - continue - if c == "@" and i + 1 < n and src[i + 1] == "[": - # @[expr]: an indirect variable, read through _iv() (or _ivt() when - # it sits beside text, so unset reads as ""). - out += "\u0001%d\u0001" % n_ind - toks.append(["ivo", n_ind]) - brackets.append(true) - n_ind += 1 - i += 2 - continue - if c == "[": - brackets.append(false) - elif c == "]" and not brackets.is_empty(): - if brackets.pop_back(): - var id := -1 - var depth := 0 - for t in range(toks.size() - 1, -1, -1): - if toks[t][0] == "ivc": - depth += 1 - elif toks[t][0] == "ivo": - if depth == 0: - id = toks[t][1] - break - depth -= 1 - out += ")" - toks.append(["ivc", id]) - i += 1 - continue - if c == "@": - var j := i + 1 - while j < n and _is_word(src[j]): - j += 1 - var name := src.substr(i + 1, j - i - 1).to_lower() - if name == "" or not _is_word_start(name[0]): - return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "\"@\" must be followed by a variable name"} - if j < n and src[j] == "*": - # @prefix_* as an argument, e.g. count(@skill_*): the prefix as text. - var lit := "\"%s\"" % name - out += lit - toks.append(["str", lit]) - i = j + 1 - continue - var key := "@" + name - if not slot.has(key): - slot[key] = inputs.size() - inputs.append("_v%d" % inputs.size()) - vars.append(["@", name]) - text_side.append(false) - out += inputs[slot[key]] - toks.append(["var", slot[key]]) - i = j - continue - if _is_word(c): - var j := i - while j < n and (_is_word(src[j]) or (src[j] == "." and j + 1 < n and src[j + 1].is_valid_int() and src.substr(i, j - i).is_valid_int())): - j += 1 - var word := src.substr(i, j - i) - var dice := _dice_of(word) - if not dice.is_empty(): - if dice[0] < 1 or dice[0] > MAX_DICE or dice[1] < 1 or dice[1] > MAX_SIDES: - return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "%s isn't a dice roll this can make" % word} - out += "_d(%d, %d)" % [dice[0], dice[1]] - toks.append(["other", word]) - elif word[0].is_valid_int(): - out += word - toks.append(["other", word]) - else: - # A function call, a keyword or a chain variable. - var k := j - while k < n and src[k] == " ": - k += 1 - var is_call := k < n and src[k] == "(" - if word == "if" and is_call: - # Spreadsheet-style if(condition, then, else). Both branches - # are evaluated, so dice in either one are rolled. - out += "_if" - toks.append(["other", word]) - elif word == "if" or word == "else": - # Godot's Expression parses "a if c else b" but returns the - # wrong branch, so refuse it rather than give silent nonsense. - return {"text": "", "inputs": [], "vars": [], "text_side": [], - "error": "Write if(condition, then, else) instead of \"… if … else …\""} - elif is_call or _KEYWORDS.has(word): - out += word - toks.append(["op" if word == "in" else "other", word]) - else: - if not slot.has(word): - slot[word] = inputs.size() - inputs.append("_v%d" % inputs.size()) - vars.append(["", word]) - text_side.append(false) - out += inputs[slot[word]] - toks.append(["var", slot[word]]) - i = j - continue - if c == "=": - var prev := src[i - 1] if i > 0 else "" - var next := src[i + 1] if i + 1 < n else "" - if next == "=": - out += "==" - toks.append(["op", "=="]) - i += 2 - continue - if prev != "=" and prev != "!" and prev != "<" and prev != ">": - out += "==" - toks.append(["op", "=="]) - i += 1 - continue - if c != " " and c != "\t" and c != "\n": - toks.append(["op", c]) - out += c - i += 1 - if brackets.has(true): - return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "@[ is missing its closing ]"} - # An indirect @[…] beside a text literal (or `in`) reads as "" when unset. - var beside := func(u: int) -> bool: - return u >= 0 and u < toks.size() and (toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in")) - for t in toks.size(): - if toks[t][0] != "ivo": - continue - var id: int = toks[t][1] - var close := t - for u in range(t + 1, toks.size()): - if toks[u][0] == "ivc" and toks[u][1] == id: - close = u - break - var text_side_ind: bool = beside.call(t - 1) or beside.call(t - 2) or beside.call(close + 1) or beside.call(close + 2) - out = out.replace("\u0001%d\u0001" % id, "_ivt(" if text_side_ind else "_iv(") - # A variable directly beside a text literal (or `in`) reads as "" when unset. - for t in toks.size(): - if toks[t][0] != "var": - continue - for d in [-2, -1, 1, 2]: - var u: int = t + d - if u < 0 or u >= toks.size(): - continue - if toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in"): - text_side[toks[t][1]] = true - # Each text literal goes beside the nearest @variable (left first), so a - # step name can read as its number when that variable is a scale. - for t in toks.size(): - if toks[t][0] != "str" or (toks[t] as Array).size() < 3: - continue - var near := -1 - for d in range(1, toks.size()): - for u: int in [t - d, t + d]: - if near < 0 and u >= 0 and u < toks.size() and toks[u][0] == "var" and vars[toks[u][1]][0] == "@": - near = toks[u][1] - if near >= 0: - break - var lit_s: String = toks[t][1] - var put := lit_s if near < 0 else "_lit(%d, %s)" % [near, lit_s] - out = out.replace("\u0002%d\u0002" % toks[t][2], put) - return {"text": out, "inputs": inputs, "vars": vars, "text_side": text_side, "error": ""} - - -## [count, sides] for a dice word ("2d6", "d20", "3D", "D3", "2D"), or []. -static func _dice_of(word: String) -> Array: - if _dice_re == null: - _dice_re = RegEx.create_from_string("^(\\d*)[dD](\\d*)$") - var m := _dice_re.search(word) - if m == null: - return [] - var a := m.get_string(1) - var b := m.get_string(2) - if a == "" and b == "": - return [] - return [int(a) if a != "" else 1, int(b) if b != "" else 6] - - -static func _is_word(c: String) -> bool: - return c == "_" or c.is_valid_int() or (c.to_lower() != c.to_upper()) - - -static func _is_word_start(c: String) -> bool: - return c == "_" or (c.to_lower() != c.to_upper()) diff --git a/core/expr_rewriter.gd b/core/expr_rewriter.gd new file mode 100644 index 0000000..4583c69 --- /dev/null +++ b/core/expr_rewriter.gd @@ -0,0 +1,239 @@ +class_name ExprRewriter +extends RefCounted +## Turns an expression as the user writes it (@luck >= 8, 2d6 + 1, @[option]) +## into text that Godot's Expression class can run. Board and chain +## variables become numbered inputs (_v0, _v1 ...), dice become _d() calls, +## a lone "=" becomes "==", and text beside a variable is marked so an unset +## value reads as "". Expr calls this once per new expression and caches it. + +const _KEYWORDS := ["and", "or", "not", "in", "true", "false", "null", "if", "else", + "PI", "TAU", "INF", "NAN", "self"] + + +## Rewrites the user's syntax into Godot Expression syntax. Returns {text, +## inputs, vars, text_side, error}. +static func rewrite(src: String) -> Dictionary: + var out := "" + var inputs: Array = [] + var vars: Array = [] + var text_side: Array = [] + var slot := {} # "@name" / "name" -> input index + # Open brackets: true for an indirect @[ (closes with ")"), false for a + # plain "[". + var brackets: Array[bool] = [] + var indirect_count := 0 + # Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side). + var toks: Array = [] + var lits: Array[String] = [] + var i := 0 + var src_len := src.length() + while i < src_len: + var ch := src[i] + if ch == "\"" or ch == "'": + var j := i + 1 + while j < src_len and src[j] != ch: + if src[j] == "\\": + j += 1 + j += 1 + if j >= src_len: + return _fail("A text value is missing its closing quote") + var lit := src.substr(i, j - i + 1) + # A placeholder: a step name beside a scale value becomes its number + # (ExprBase._lit), worked out below once the variables are known. + out += "\u0002%d\u0002" % lits.size() + toks.append(["str", lit, lits.size()]) + lits.append(lit) + i = j + 1 + continue + if ch == "@" and i + 1 < src_len and src[i + 1] == "[": + # @[expr]: an indirect variable, read through _iv() (or _ivt() when + # it sits beside text, so unset reads as ""). + out += "\u0001%d\u0001" % indirect_count + toks.append(["ivo", indirect_count]) + brackets.append(true) + indirect_count += 1 + i += 2 + continue + if ch == "[": + brackets.append(false) + elif ch == "]" and not brackets.is_empty(): + if brackets.pop_back(): + out += ")" + toks.append(["ivc", _open_indirect_id(toks)]) + i += 1 + continue + if ch == "@": + var j := i + 1 + while j < src_len and RuleTokens.is_word(src[j]): + j += 1 + var name := src.substr(i + 1, j - i - 1).to_lower() + if name == "" or not _is_word_start(name[0]): + return _fail("\"@\" must be followed by a variable name") + if j < src_len and src[j] == "*": + # @prefix_* as an argument, e.g. count(@skill_*): the prefix as text. + var lit := "\"%s\"" % name + out += lit + toks.append(["str", lit]) + i = j + 1 + continue + var key := "@" + name + if not slot.has(key): + slot[key] = inputs.size() + inputs.append("_v%d" % inputs.size()) + vars.append(["@", name]) + text_side.append(false) + out += inputs[slot[key]] + toks.append(["var", slot[key]]) + i = j + continue + if RuleTokens.is_word(ch): + var j := i + while j < src_len and (RuleTokens.is_word(src[j]) or (src[j] == "." and j + 1 < src_len and src[j + 1].is_valid_int() and src.substr(i, j - i).is_valid_int())): + j += 1 + var word := src.substr(i, j - i) + var dice := dice_of(word) + if not dice.is_empty(): + if dice[0] < 1 or dice[0] > Expr.MAX_DICE or dice[1] < 1 or dice[1] > Expr.MAX_SIDES: + return _fail("%s isn't a dice roll this can make" % word) + out += "_d(%d, %d)" % [dice[0], dice[1]] + toks.append(["other", word]) + elif word[0].is_valid_int(): + out += word + toks.append(["other", word]) + else: + # A function call, a keyword or a chain variable. + var after := j + while after < src_len and src[after] == " ": + after += 1 + var is_call := after < src_len and src[after] == "(" + if word == "if" and is_call: + # Spreadsheet-style if(condition, then, else). Both branches + # are evaluated, so dice in either one are rolled. + out += "_if" + toks.append(["other", word]) + elif word == "if" or word == "else": + # Godot's Expression parses "a if c else b" but returns the + # wrong branch, so refuse it rather than give silent nonsense. + return _fail("Write if(condition, then, else) instead of \"… if … else …\"") + elif is_call or _KEYWORDS.has(word): + out += word + toks.append(["op" if word == "in" else "other", word]) + else: + if not slot.has(word): + slot[word] = inputs.size() + inputs.append("_v%d" % inputs.size()) + vars.append(["", word]) + text_side.append(false) + out += inputs[slot[word]] + toks.append(["var", slot[word]]) + i = j + continue + if ch == "=": + var prev := src[i - 1] if i > 0 else "" + var next := src[i + 1] if i + 1 < src_len else "" + if next == "=": + out += "==" + toks.append(["op", "=="]) + i += 2 + continue + if prev != "=" and prev != "!" and prev != "<" and prev != ">": + out += "==" + toks.append(["op", "=="]) + i += 1 + continue + if ch != " " and ch != "\t" and ch != "\n": + toks.append(["op", ch]) + out += ch + i += 1 + if brackets.has(true): + return _fail("@[ is missing its closing ]") + out = _place_indirect_reads(out, toks) + _mark_text_side(toks, text_side) + out = _place_literals(out, toks, vars) + return {"text": out, "inputs": inputs, "vars": vars, "text_side": text_side, "error": ""} + + +## [count, sides] for a dice word ("2d6", "d20", "3D", "D3", "2D"), or []. +static func dice_of(word: String) -> Array: + var found := RuleTokens.dice_regex().search(word) + if found == null: + return [] + var count_text := found.get_string(1) + var sides_text := found.get_string(2) + if count_text == "" and sides_text == "": + return [] + return [int(count_text) if count_text != "" else 1, int(sides_text) if sides_text != "" else 6] + + +static func _fail(message: String) -> Dictionary: + return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": message} + + +## The id of the innermost indirect @[ that is still open in `toks`. +static func _open_indirect_id(toks: Array) -> int: + var depth := 0 + for tok_index in range(toks.size() - 1, -1, -1): + if toks[tok_index][0] == "ivc": + depth += 1 + elif toks[tok_index][0] == "ivo": + if depth == 0: + return toks[tok_index][1] + depth -= 1 + return -1 + + +## True when the token at `tok_index` is a text literal or `in`. +static func _is_text_token(toks: Array, tok_index: int) -> bool: + return tok_index >= 0 and tok_index < toks.size() \ + and (toks[tok_index][0] == "str" or (toks[tok_index][0] == "op" and toks[tok_index][1] == "in")) + + +## An indirect @[…] beside a text literal (or `in`) reads as "" when unset: +## its placeholder becomes _ivt( there, and _iv( everywhere else. +static func _place_indirect_reads(out: String, toks: Array) -> String: + for tok_index in toks.size(): + if toks[tok_index][0] != "ivo": + continue + var id: int = toks[tok_index][1] + var close := tok_index + for other in range(tok_index + 1, toks.size()): + if toks[other][0] == "ivc" and toks[other][1] == id: + close = other + break + var beside_text := _is_text_token(toks, tok_index - 1) or _is_text_token(toks, tok_index - 2) \ + or _is_text_token(toks, close + 1) or _is_text_token(toks, close + 2) + out = out.replace("\u0001%d\u0001" % id, "_ivt(" if beside_text else "_iv(") + return out + + +## A variable directly beside a text literal (or `in`) reads as "" when unset. +static func _mark_text_side(toks: Array, text_side: Array) -> void: + for tok_index in toks.size(): + if toks[tok_index][0] != "var": + continue + for offset in [-2, -1, 1, 2]: + if _is_text_token(toks, tok_index + offset): + text_side[toks[tok_index][1]] = true + + +## Each text literal goes beside the nearest @variable (left first), so a +## step name can read as its number when that variable is a scale. +static func _place_literals(out: String, toks: Array, vars: Array) -> String: + for tok_index in toks.size(): + if toks[tok_index][0] != "str" or (toks[tok_index] as Array).size() < 3: + continue + var near := -1 + for distance in range(1, toks.size()): + for other: int in [tok_index - distance, tok_index + distance]: + if near < 0 and other >= 0 and other < toks.size() and toks[other][0] == "var" and vars[toks[other][1]][0] == "@": + near = toks[other][1] + if near >= 0: + break + var lit_text: String = toks[tok_index][1] + var put := lit_text if near < 0 else "_lit(%d, %s)" % [near, lit_text] + out = out.replace("\u0002%d\u0002" % toks[tok_index][2], put) + return out + + +static func _is_word_start(ch: String) -> bool: + return ch == "_" or (ch.to_lower() != ch.to_upper()) diff --git a/core/expr_rewriter.gd.uid b/core/expr_rewriter.gd.uid new file mode 100644 index 0000000..6dce7cc --- /dev/null +++ b/core/expr_rewriter.gd.uid @@ -0,0 +1 @@ +uid://cm0xg4ul6rfm diff --git a/core/rule_tokens.gd b/core/rule_tokens.gd new file mode 100644 index 0000000..0ae793f --- /dev/null +++ b/core/rule_tokens.gd @@ -0,0 +1,153 @@ +class_name RuleTokens +extends RefCounted +## Splits rule text into small pieces ("tokens") such as @luck, >=, 8 or +## "Aslan", so the Builder can read conditions and effects as rows. Also +## holds the small text helpers that go with it: is a character part of a +## word, dice words like 2d6, and quoting text. Builder delegates here. + +static var _dice_re: RegEx = null +static var _num_re: RegEx = null + + +## 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 tokenize(src: String) -> Array: + var out: Array = [] + var i := 0 + var src_len := src.length() + while i < src_len: + var ch := src[i] + if ch == " " or ch == "\t" or ch == "\n": + i += 1 + continue + if ch == "\"" or ch == "'": + var j := i + 1 + while j < src_len and src[j] != ch: + if src[j] == "\\": + j += 1 + j += 1 + if j >= src_len: + return [] + out.append({"t": "str", "s": src.substr(i, j - i + 1)}) + i = j + 1 + continue + if ch == "@": + if i + 1 < src_len 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 name_end := i + 1 + while name_end < src_len and is_word(src[name_end]): + name_end += 1 + var name := src.substr(i + 1, name_end - i - 1).to_lower() + if name == "" or name[0].is_valid_int(): + return [] + if name_end < src_len and src[name_end] == "*": + out.append({"t": "prefix", "s": "@%s*" % name}) + i = name_end + 1 + else: + out.append({"t": "var", "s": "@" + name}) + i = name_end + continue + if is_word(ch): + var word_end := i + while word_end < src_len and (is_word(src[word_end]) or (src[word_end] == "." and word_end + 1 < src_len and src[word_end + 1].is_valid_int())): + word_end += 1 + var word := src.substr(i, word_end - i) + i = word_end + if _num().search(word) != null: + out.append({"t": "num", "s": word}) + elif dice_regex().search(word) != null and word.length() > 1: + out.append({"t": "dice", "s": word}) + elif word[0].is_valid_int(): + return [] + elif ["and", "or", "not"].has(word.to_lower()) and word == word.to_lower(): + out.append({"t": "kw", "s": word}) + else: + out.append({"t": "name", "s": word}) + 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 ch == "!": + out.append({"t": "kw", "s": "not"}) + i += 1 + continue + if ch in ["+", "-", "*", "/", "%", "(", ")", ",", "=", "<", ">"]: + out.append({"t": "op", "s": ch}) + i += 1 + continue + return [] + return out + + +## True when `ch` can be part of a name or number: a letter, a digit or "_". +static func is_word(ch: String) -> bool: + return ch == "_" or ch.is_valid_int() or (ch.to_lower() != ch.to_upper()) + + +## The pattern for a dice word: an optional count, d or D, optional sides. +static func dice_regex() -> 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 found := dice_regex().search(word) + if found == null or word.length() < 2: + return [] + var count_text := found.get_string(1) + var sides_text := found.get_string(2) + return [int(count_text) if count_text != "" else 1, int(sides_text) if sides_text != "" else 6] + + +## True when `text` is one quoted text literal ("Aslan" or 'Aslan'). +static func is_text_literal(text: String) -> bool: + var toks := tokenize(text.strip_edges()) + return toks.size() == 1 and toks[0]["t"] == "str" + + +## A quoted literal's text: "\"Aslan\"" -> "Aslan" (\" and \\ unescaped). +## Anything else comes back as it is. +static func unquote(text: String) -> String: + text = text.strip_edges() + if text.length() < 2 or not ((text.begins_with("\"") and text.ends_with("\"")) or (text.begins_with("'") and text.ends_with("'"))): + return text + var inner := text.substr(1, text.length() - 2) + var out := "" + var pos := 0 + while pos < inner.length(): + var ch := inner[pos] + if ch == "\\" and pos + 1 < inner.length(): + pos += 1 + ch = inner[pos] + out += ch + pos += 1 + return out + + +## Text as a double-quoted literal, escaping \ and ". +static func quote(text: String) -> String: + return "\"%s\"" % text.replace("\\", "\\\\").replace("\"", "\\\"") diff --git a/core/rule_tokens.gd.uid b/core/rule_tokens.gd.uid new file mode 100644 index 0000000..4c55ea2 --- /dev/null +++ b/core/rule_tokens.gd.uid @@ -0,0 +1 @@ +uid://0hqt0mqmpit4