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 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 ## 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])) if v == null: unset.append(k) v = "" if text_side[k] else 0 else: v = to_value(v) values.append(v) var base := _Base.new() base.ctx = ctx 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(_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 := _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 ## 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 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) out += lit toks.append(["str", 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 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()) ## The base instance Expression calls helper functions on. class _Base: extends RefCounted var ctx: RollContext = null var error: String = "" func _d(n: int, sides: int) -> int: if ctx != null and ctx.faces != null: var total := 0 for k in n: var f := ctx.rng.randi_range(1, sides) (ctx.faces as Array).append(f) total += f return total return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null) func dm(x: Variant) -> int: return Expr.dm(x) func _if(cond: Variant, then_value: Variant, else_value: Variant) -> Variant: return then_value if Expr.truthy(cond) else else_value func has(list: Variant, item: Variant) -> bool: return Expr.has_item(list, item) func _iv(name: Variant) -> Variant: return _indirect(name, 0) func _ivt(name: Variant) -> Variant: return _indirect(name, "") func _indirect(name: Variant, unset: Variant) -> Variant: var r := Expr.indirect_name(name) if r["error"] != "": if error == "": error = r["error"] return unset if ctx == null: return unset var v: Variant = ctx.get_value("@" + str(r["name"])) return unset if v == null else Expr.to_value(v) func count(prefix: Variant) -> int: if ctx == null: return 0 return ctx.count_vars(str(prefix))