TableTower/core/expr_rewriter.gd

240 lines
8.4 KiB
GDScript3
Raw Normal View History

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())