class_name Expr extends RefCounted ## Expressions for logic cards (docs/LOGIC.md §4), evaluated with Godot's ## Expression after a small rewrite: ## @name a board variable (unset reads as 0, or "" next to text) ## name a chain variable (answer, i, or anything saved with -> name) ## 2d6 d20 3D D3 dice, rolled fresh every time (a missing count is 1, missing ## sides are 6) ## @[expr] the board variable named by expr (indirect), e.g. ## @[option] or @["skill_" + option] ## a = b a lone "=" means equals ## dm(x) has(list, item) count(prefix), plus Expression's built-ins ## (min max clamp abs floor ceil round ...) ## ## Errors never crash: evaluate() returns {"value", "error"} and the error text ## is "" on success. Parsed expressions are cached by source text. ## Most dice one token may roll (a typo like 1000d6 is refused, not hung on). const MAX_DICE := 100 const MAX_SIDES := 1000 ## 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 _name_re: RegEx = null ## Evaluates `src` against a roll context. `ctx` may be null (variables then ## read as unset and dice use a fresh RNG). Returns {"value": Variant, ## "error": String}; whole floats come back as ints. static func evaluate(src: String, ctx: RollContext) -> Dictionary: var p := _parsed(src) if p["error"] != "": return {"value": null, "error": p["error"]} var inputs: Array = p["inputs"] var kinds: Array = p["vars"] var text_side: Array = p["text_side"] var values: Array = [] var unset: Array[int] = [] for k in inputs.size(): var pair: Array = kinds[k] var v: Variant = null if ctx != null: v = ctx.get_value(("@" if pair[0] == "@" else "") + str(pair[1])) # A scale value reads as its step's number (unset: 0). var steps: Array[String] = [] if pair[0] == "@": steps = ctx.scale_steps(str(pair[1])) if not steps.is_empty(): v = Scales.position_of(steps, v) if v != null else 0 if v == null: unset.append(k) v = "" if text_side[k] else 0 else: v = to_value(v) values.append(v) var base := ExprBase.new() base.ctx = ctx base.var_names = kinds var e: Expression = p["expr"] var out: Variant = e.execute(values, base, false) if e.has_execute_failed() and not unset.is_empty(): # An unset variable next to text: try again with "" for the unset ones. var again := values.duplicate() for k in unset: again[k] = "" var out2: Variant = e.execute(again, base, false) if not e.has_execute_failed(): return {"value": normalize(out2), "error": ""} if e.has_execute_failed(): var msg := e.get_error_text() return {"value": null, "error": msg if msg != "" else "Can't work out %s" % src} if base.error != "": return {"value": null, "error": base.error} return {"value": normalize(out), "error": ""} ## The value as an int: numbers are floored, true/false are 1/0, numeric text ## is parsed. `fallback` when it can't be a number or has an error. static func as_int(r: Dictionary, fallback: int = 0) -> int: if str(r.get("error", "")) != "": return fallback var v: Variant = to_value(r.get("value")) if v is bool: return 1 if v else 0 if v is int: return v if v is float: return floori(v) return fallback ## Evaluates and converts in one step (see as_int). static func eval_int(src: String, ctx: RollContext, fallback: int = 0) -> int: return as_int(evaluate(src, ctx), fallback) ## Truthiness for loop and pipe conditions: false, 0, "" and null are false. static func truthy(v: Variant) -> bool: v = to_value(v) if v == null: return false if v is bool: return v if v is int or v is float: return v != 0 if v is String: return v != "" return true ## Checks that `src` parses, without running it. "" when it's fine. static func check(src: String) -> String: return str(_parsed(src)["error"]) ## The variables an expression reads, in order of first use: "@name" for ## board variables, "name" for chain variables (indirect @[…] names aren't ## known until it runs, so they're left out). [] when it doesn't parse. static func names_in(src: String) -> Array: var p := _parsed(src) if p["error"] != "": return [] var out: Array = [] for pair: Array in p["vars"]: out.append(("@" if pair[0] == "@" else "") + str(pair[1])) return out ## {name: value} for names_in(src), read from `ctx` now (null when unset). static func values_read(src: String, ctx: RollContext) -> Dictionary: var out := {} for nm: String in names_in(src): out[nm] = ctx.get_value(nm) if ctx != null else null return out ## Number-like text becomes a number ("12" -> 12, "2.5" -> 2.5); whole floats ## become ints; anything else is unchanged. static func to_value(v: Variant) -> Variant: if v is String: var s := (v as String).strip_edges() if s.is_valid_int(): return s.to_int() if s.is_valid_float() and not s.to_lower().contains("n"): return normalize(s.to_float()) return v return normalize(v) ## Whole floats (as JSON gives back) become ints. static func normalize(v: Variant) -> Variant: if v is float and is_finite(v) and is_equal_approx(v, roundf(v)) and absf(v) < 1e15: return int(roundf(v)) return v static func is_number(v: Variant) -> bool: v = to_value(v) return v is int or v is float ## A value for display: 9, 2.5, "Aslan"; no ".0" on whole numbers. static func format_value(v: Variant) -> String: if v == null: return "" if v is bool: return "yes" if v else "no" v = normalize(v) if v is int: return str(v) if v is float: var s := "%.4f" % v s = s.rstrip("0").rstrip(".") return s return str(v) ## The 2D-game characteristic modifier. static func dm(x: Variant) -> int: var n := 0 var v: Variant = to_value(x) if v is int: n = v elif v is float: n = floori(v) if n <= 0: return -3 if n <= 2: return -2 if n <= 5: return -1 if n <= 8: return 0 if n <= 11: return 1 if n <= 14: return 2 return 3 ## Items of a comma-separated list (trimmed, empty ones dropped). static func list_items(list: Variant) -> Array[String]: var out: Array[String] = [] if list is Array: for x: Variant in list: var s := format_value(x).strip_edges() if s != "": out.append(s) return out for part in format_value(list).split(","): var s := part.strip_edges() if s != "": out.append(s) return out ## Whether a comma-separated list contains an item (case-insensitive). static func has_item(list: Variant, item: Variant) -> bool: var want := format_value(item).strip_edges().to_lower() for s in list_items(list): if s.to_lower() == want: return true return false ## The board variable name an indirect @[expr] computed: {"name": String ## (no "@"), "error": String}. Names are lowercase letters, digits and "_" ## (a leading "@" is dropped and capitals are lowered). static func indirect_name(v: Variant) -> Dictionary: var s := format_value(v).strip_edges().trim_prefix("@").to_lower() if s == "": return {"name": "", "error": "@[…] gave an empty variable name"} if _name_re == null: _name_re = RegEx.create_from_string("^[a-z_][a-z0-9_]*$") if _name_re.search(s) == null: return {"name": "", "error": "@[…] gave \"%s\", which isn't a variable name (lowercase letters, digits and _)" % format_value(v)} return {"name": s, "error": ""} ## Index of the "]" that closes the "[" at `open` in `s`, skipping quoted text ## and nested brackets; -1 when there isn't one. static func bracket_end(s: String, open: int) -> int: var depth := 0 var quote := "" var k := open while k < s.length(): var c := s[k] if quote != "": if c == "\\": k += 1 elif c == quote: quote = "" elif c == "\"" or c == "'": quote = c elif c == "[": depth += 1 elif c == "]": depth -= 1 if depth == 0: return k k += 1 return -1 ## Rolls NdM with `rng` (a fresh one when null). static func roll_dice(n: int, sides: int, rng: RandomNumberGenerator) -> int: if rng == null: rng = RandomNumberGenerator.new() var total := 0 for k in n: total += rng.randi_range(1, sides) return total ## The rewritten source (for tests and debugging). static func rewrite(src: String) -> String: return str(ExprRewriter.rewrite(src)["text"]) static func _parsed(src: String) -> Dictionary: if _cache.has(src): return _cache[src] var p := {"expr": null, "inputs": [], "vars": [], "text_side": [], "error": ""} if src.strip_edges() == "": p["error"] = "Empty expression" else: var rw := ExprRewriter.rewrite(src) if rw["error"] != "": p["error"] = rw["error"] else: var e := Expression.new() var names: Array = rw["inputs"] var err := e.parse(rw["text"], PackedStringArray(names)) if err != OK: p["error"] = e.get_error_text() if e.get_error_text() != "" else "Can't read %s" % src else: p["expr"] = e p["inputs"] = names p["vars"] = rw["vars"] p["text_side"] = rw["text_side"] if _cache.size() > 4000: _cache.clear() _cache[src] = p return p