1
1
mirror of https://github.com/KenanZhu/AutoLibrary.git synced 2026-06-17 23:13:03 +08:00

Compare commits

...

3 Commits

6 changed files with 241 additions and 42 deletions
+60 -13
View File
@@ -65,8 +65,6 @@ def _errPos(
# Pre-compiled regex patterns for value resolution
_RE_TIME = re.compile(r"^TIME\((\d{1,2}):(\d{2})\)$", re.IGNORECASE)
_RE_DATE = re.compile(r"^DATE\((\d{4})-(\d{2})-(\d{2})\)$", re.IGNORECASE)
_RE_CUR_DATE_OFFSET = re.compile(r"^CURRENT_DATE\s*\+\s*(\d+)$", re.IGNORECASE)
_RE_CUR_TIME_OFFSET = re.compile(r"^CURRENT_TIME\s*\+\s*(\d+)$", re.IGNORECASE)
def splitTopLevel(
@@ -169,7 +167,7 @@ def _resolveValue(
- DATE(yyyy-mm-dd)
- .TRUE. / .FALSE.
- Single/double quoted strings (with escaped single quotes)
- CURRENT_DATE + N / CURRENT_TIME + N (relative offsets)
- Arithmetic expressions: operand (+|-) operand (Date ± Int, Int ± Int, etc.)
- Numeric literals (int / float)
- Field references (resolved via _resolveFieldObj)
@@ -197,14 +195,6 @@ def _resolveValue(
return s[1:-1].replace("''", "'")
if s.startswith('"') and s.endswith('"'):
return s[1:-1]
m = _RE_CUR_DATE_OFFSET.match(s)
if m:
days = int(m.group(1))
return datetime.now().date() + timedelta(days=days)
m = _RE_CUR_TIME_OFFSET.match(s)
if m:
hours = int(m.group(1))
return (datetime.now() + timedelta(hours=hours)).time()
try:
return int(s)
except ValueError:
@@ -213,6 +203,9 @@ def _resolveValue(
return float(s)
except ValueError:
pass
arith_result = _resolveArithExpr(s, target_data)
if arith_result is not None:
return arith_result
obj = _resolveFieldObj(s)
if obj:
return obj.getValue(target_data)
@@ -250,6 +243,55 @@ def _resolveAsObject(
return ASObject._makeTemp(value, inferred)
def _resolveArithExpr(
expr: str,
target_data: dict,
line: int = 0
):
"""
Try to evaluate expr as a two-operand arithmetic expression: left (+|-) right.
Each operand is resolved via _resolveAsObject, reusing the full literal /
field / script-variable resolution stack. The left operand's value is
copied into a temporary ASObject and ASOperator.apply() performs the
type-safe calculation on the copy, so the original variable is never
mutated.
Returns the computed Python value, or None if expr is not a recognised
arithmetic pattern.
"""
s = expr.strip()
m = re.match(r'^(.+?)\s+([+-])\s+(.+)$', s)
if not m:
# Fallback for no-space expressions like RESERVE_DATE+1
# (e.g. when extracted from IF(RESERVE_DATE.EQ.CURRENT_DATE+1)).
# Left operand must be an identifier (letter/underscore start) to
# avoid false-matching date strings like 2026-05-20.
m = re.match(r'^([A-Za-z_]\w*)([+-])(\d+|[A-Za-z_]\w*)$', s)
if not m:
return None
left_expr = m.group(1).strip()
op_symbol = m.group(2).strip()
right_expr = m.group(3).strip()
if " + " in left_expr or " - " in left_expr:
return None
if " + " in right_expr or " - " in right_expr:
return None
left_obj = _resolveAsObject(left_expr, target_data)
right_obj = _resolveAsObject(right_expr, target_data)
op = ".ADD." if op_symbol == "+" else ".SUB."
left_val = left_obj.getValue(target_data)
result_type = left_obj.var_type
if left_obj.var_type == "Int" and right_obj.var_type == "Float":
result_type = "Float"
elif left_obj.var_type == "Float" and right_obj.var_type == "Int":
result_type = "Float"
temp = ASObject._makeTemp(left_val, result_type)
ASOperator.apply(temp, right_obj, op, target_data)
return temp.getValue(target_data)
def _evaluateCondition(
condition_str: str,
target_data: dict,
@@ -349,7 +391,12 @@ def _executeSet(
resolved = _resolveValue(value_str, target_data)
stripped = value_str.strip()
if resolved == "" and stripped not in ("''", '""') and len(stripped.split()) > 1:
raise ValueError(_errPos(line, f"SET 值中存在多余内容 '{stripped}'"))
try:
resolved = _resolveArithExpr(stripped, target_data, line)
except ValueError as e:
raise ValueError(_errPos(line, str(e)))
if resolved is None:
raise ValueError(_errPos(line, f"SET 值中存在多余内容 '{stripped}'"))
upper_name = field_name.upper().strip()
obj = _FIELD_MAP.get(upper_name)
if not obj:
@@ -567,7 +614,7 @@ class _EngineExecutor(NodeVisitor):
paren_open = upper.find("(")
if paren_open < 0:
raise ValueError(_errPos(self._line, "ELSE IF 缺少左括号"))
_executeOperation(_node.raw_line, self._target_data, self._line)
raise ValueError(_errPos(self._line, f"无法识别的语法 '{_node.raw_line}'"))
def execute(
+1 -1
View File
@@ -115,7 +115,7 @@ class ASOperator:
"""Apply arithmetic per type."""
tp = target.var_type
raw_op = operand._value
raw_op = operand.getValue(target_data)
if tp == "Date":
if not isinstance(target_val, date):
+14 -5
View File
@@ -46,8 +46,8 @@ _RE_ELSE_IF = re.compile(r"^ELSE\s+IF\((.+)\)(?:\s+THEN\s*)?$", re.IGNORECASE)
_RE_ELSE = re.compile(r"^ELSE\s*$", re.IGNORECASE)
_RE_ENDIF = re.compile(r"^(ENDIF|END IF)$", re.IGNORECASE)
_RE_SET = re.compile(r"^SET\s+(\w+)\s*=\s*(.+)$", re.IGNORECASE)
_RE_ADD = re.compile(r"^(\w+)\s+\.ADD\.\s+(\d+)$", re.IGNORECASE)
_RE_SUB = re.compile(r"^(\w+)\s+\.SUB\.\s+(\d+)$", re.IGNORECASE)
_RE_ADD = re.compile(r"^(\w+)\s+\.ADD\.\s+(-?\d+(?:\.\d+)?|\w+)$", re.IGNORECASE)
_RE_SUB = re.compile(r"^(\w+)\s+\.SUB\.\s+(-?\d+(?:\.\d+)?|\w+)$", re.IGNORECASE)
_RE_PASS = re.compile(r"^\s*PASS\s*$", re.IGNORECASE)
@@ -388,11 +388,20 @@ class ASTokenizer:
) -> str:
in_single = False
for i, ch in enumerate(line):
if ch == "'":
in_double = False
i = 0
while i < len(line):
ch = line[i]
if ch == "'" and not in_double:
if i + 1 < len(line) and line[i + 1] == "'":
i += 2
continue
in_single = not in_single
elif ch == "/" and i + 1 < len(line) and line[i + 1] == "/" and not in_single:
elif ch == '"' and not in_single:
in_double = not in_double
elif ch == "/" and i + 1 < len(line) and line[i + 1] == "/" and not in_single and not in_double:
return line[:i].rstrip()
i += 1
return line
@classmethod
+23 -5
View File
@@ -321,11 +321,11 @@ class _DateInputContainer(QWidget):
s = expr.strip().upper()
_RELATIVE_MAP = {
"CURRENT_DATE": 0, "TODAY": 0,
"CURRENT_DATE + 1": 1, "TOMORROW": 1,
"CURRENT_DATE + 2": 2,
"CURRENT_DATE - 1": 3,
"CURRENT_DATE - 2": 4,
"CURRENT_DATE": 2, "TODAY": 2,
"CURRENT_DATE + 1": 3, "TOMORROW": 3,
"CURRENT_DATE + 2": 4,
"CURRENT_DATE - 1": 1,
"CURRENT_DATE - 2": 0,
}
idx = _RELATIVE_MAP.get(s)
if idx is not None:
@@ -560,6 +560,8 @@ def encodeValueStr(
var_type: str
) -> str:
if isArithExpr(raw_value):
return raw_value
if var_type == "Time":
if raw_value.startswith("+") or raw_value.startswith("-"):
return raw_value
@@ -609,6 +611,20 @@ def stripOuterParens(
return s
# Pre-compiled pattern for detecting arithmetic expressions like "A + B" / "C - D"
_RE_ARITH_EXPR = re.compile(r'^.+?\s+[+-]\s+.+$')
def isArithExpr(
expr: str
) -> bool:
"""
Return True if expr looks like a two-operand arithmetic expression (A ± B).
"""
return bool(_RE_ARITH_EXPR.match(expr.strip()))
def isVarReference(
expr: str
) -> bool:
@@ -623,6 +639,8 @@ def isVarReference(
return False
if re.match(r"^[+-]?\d", s):
return False
if isArithExpr(s):
return False
return bool(re.match(r"^[A-Z_][A-Z0-9_]*$", up))
@@ -57,9 +57,11 @@ class ScriptOrchObserver(ParsingObserver):
if kind == K_SET:
self._current_actions.append((target, value, "set"))
elif kind == K_ADD:
self._current_actions.append((target, f"+{value}", "add"))
prefixed = value if value.startswith("-") else f"+{value}"
self._current_actions.append((target, prefixed, "add"))
else:
self._current_actions.append((target, f"-{value}", "sub"))
prefixed = value if value.startswith("-") else f"-{value}"
self._current_actions.append((target, prefixed, "sub"))
elif kind == K_ENDIF:
self._flushCurrentBlock()
self._current_type = None
+139 -16
View File
@@ -1,6 +1,8 @@
"""
Widget components for the AutoScript orchestration dialog.
"""
import re
from PySide6.QtCore import Slot
from PySide6.QtWidgets import (
QComboBox,
@@ -21,6 +23,7 @@ from gui.ALAutoScriptOrchDialog._helpers import (
VAR_TYPE_ORDER,
encodeValueStr,
getValueFromWidget,
isArithExpr,
isVarReference,
makeComboWidget,
makeLabel,
@@ -46,6 +49,7 @@ class ConditionRowFrame(QFrame):
self._blockIndex = parentBlockIndex
self._isFirst = isFirst
self._isBoolMode = False
self._rawRhsExpr = ""
self.setupUi()
self.connectSignals()
@@ -133,6 +137,7 @@ class ConditionRowFrame(QFrame):
idx
):
self._rawRhsExpr = ""
if idx < 0:
return
data = self.leftVarCombo.itemData(idx)
@@ -157,6 +162,7 @@ class ConditionRowFrame(QFrame):
idx
):
self._rawRhsExpr = ""
isVar = (self._compTypeCombo.currentData() == "variable")
self.rhsStack.setCurrentIndex(1 if isVar else 0)
if isVar:
@@ -179,6 +185,8 @@ class ConditionRowFrame(QFrame):
return ""
name, vartype = data
opSym = self.opCombo.currentData()
if self._rawRhsExpr:
return f"{name} {opSym} {self._rawRhsExpr}"
isVarRef = (self._compTypeCombo.currentData() == "variable")
if isVarRef:
rd = self.rhsVarCombo.currentData()
@@ -204,21 +212,31 @@ class ConditionRowFrame(QFrame):
valueExpr: str
):
for ci in range(self.leftVarCombo.count()):
d = self.leftVarCombo.itemData(ci)
if d and d[0] == operandName:
self.leftVarCombo.setCurrentIndex(ci)
break
if opSym:
for oi in range(self.opCombo.count()):
if self.opCombo.itemData(oi) == opSym:
self.opCombo.setCurrentIndex(oi)
self._rawRhsExpr = ""
self.leftVarCombo.blockSignals(True)
self.opCombo.blockSignals(True)
self._compTypeCombo.blockSignals(True)
try:
for ci in range(self.leftVarCombo.count()):
d = self.leftVarCombo.itemData(ci)
if d and d[0] == operandName:
self.leftVarCombo.setCurrentIndex(ci)
break
if opSym:
for oi in range(self.opCombo.count()):
if self.opCombo.itemData(oi) == opSym:
self.opCombo.setCurrentIndex(oi)
break
finally:
self.leftVarCombo.blockSignals(False)
self.opCombo.blockSignals(False)
self._compTypeCombo.blockSignals(False)
data = self.leftVarCombo.currentData()
vartype = data[1] if data else "String"
self.updateRhsLiteralWidget(vartype)
if not valueExpr:
return
up = valueExpr.strip().upper()
data = self.leftVarCombo.currentData()
vartype = data[1] if data else "String"
if isVarReference(valueExpr) or self._isKnownVar(up):
self._compTypeCombo.setCurrentIndex(1)
self.populateRhsVarCombo()
@@ -228,12 +246,45 @@ class ConditionRowFrame(QFrame):
else:
self.rhsVarCombo.addItem(up, (up, "String"))
self.rhsVarCombo.setCurrentIndex(self.rhsVarCombo.count() - 1)
elif isArithExpr(valueExpr):
self._tryLoadCondArithExpr(valueExpr, vartype)
else:
self._compTypeCombo.setCurrentIndex(0)
w = self.literalWidgets.get(vartype)
if w:
setWidgetValue(w, vartype, valueExpr)
def _tryLoadCondArithExpr(
self,
expr: str,
vartype: str
):
"""Try to decompose a condition RHS arithmetic expression into UI state."""
s = expr.strip()
m = re.match(r'^(.+?)\s+([+-])\s+(.+)$', s)
if not m:
self._rawRhsExpr = s
return
left = m.group(1).strip()
op = m.group(2).strip()
right = m.group(3).strip()
left_up = left.upper()
if vartype == "Date" and left_up == "CURRENT_DATE":
try:
n = int(right)
offset = n if op == "+" else -n
if offset in (-2, -1, 0, 1, 2):
self._compTypeCombo.setCurrentIndex(0)
w = self.literalWidgets.get("Date")
if w and hasattr(w, "setValue"):
w.setValue(s)
return
except ValueError:
pass
self._rawRhsExpr = s
def _isKnownVar(
self,
@@ -426,12 +477,9 @@ class ActionStepFrame(QFrame):
rawVal = self._getValueRaw()
if op == "set":
vartype = self._currentTargetType
if isArithExpr(rawVal):
return f" SET {target} = {rawVal}"
encoded = encodeValueStr(rawVal, vartype)
if vartype == "Time":
if rawVal.startswith("+"):
return f" {target} .ADD. {rawVal[1:]}"
if rawVal.startswith("-"):
return f" {target} .SUB. {rawVal[1:]}"
return f" SET {target} = {encoded}"
elif op == "add":
vartype = self._currentTargetType
@@ -500,6 +548,12 @@ class ActionStepFrame(QFrame):
s = expr.strip()
if not s:
return
op = self.opTypeCombo.currentData()
if op in ("add", "sub") and s.startswith("-"):
s = s[1:]
self.opTypeCombo.setCurrentIndex(
2 if op == "add" else 1
)
up = s.upper()
if isVarReference(s):
self.valueSrcCombo.setCurrentIndex(1)
@@ -510,12 +564,81 @@ class ActionStepFrame(QFrame):
else:
self.existingVarCombo.addItem(up, (up, "String"))
self.existingVarCombo.setCurrentIndex(self.existingVarCombo.count() - 1)
elif isArithExpr(s):
self._tryLoadArithExpr(s)
else:
self.valueSrcCombo.setCurrentIndex(0)
w = self.valueStack.currentWidget()
if w:
setWidgetValue(w, self._currentTargetType, expr)
def _tryLoadArithExpr(
self,
expr: str
):
"""Try to decompose an arithmetic expression into UI state."""
s = expr.strip()
m = re.match(r'^(.+?)\s+([+-])\s+(.+)$', s)
if not m:
self._storeAsCustomExpr(s)
return
left = m.group(1).strip()
op = m.group(2).strip()
right = m.group(3).strip()
left_up = left.upper()
# CURRENT_DATE ± N for Date targets — try relative combo for ±0/1/2,
# otherwise store as custom expression to preserve relative semantics
if self._currentTargetType == "Date" and left_up == "CURRENT_DATE":
try:
n = int(right)
offset = n if op == "+" else -n
if offset in (-2, -1, 0, 1, 2):
w = self._literalWidgets.get("Date")
if w and hasattr(w, "setValue"):
w.setValue(s)
self.valueSrcCombo.setCurrentIndex(0)
return
except ValueError:
pass
self._storeAsCustomExpr(s)
return
# CURRENT_TIME ± N for Time targets — map to add/sub with offset
if self._currentTargetType == "Time" and left_up == "CURRENT_TIME":
try:
hours = int(right)
if op == "-":
hours = -hours
self.opTypeCombo.setCurrentIndex(
1 if hours >= 0 else 2
)
self.valueSrcCombo.setCurrentIndex(0)
w = self._offsetWidgets.get("Time")
if w and hasattr(w, "setValue"):
w.setValue(str(abs(hours)))
return
except ValueError:
pass
self._storeAsCustomExpr(s)
def _storeAsCustomExpr(
self,
expr: str
):
"""Store a raw expression in the variable combo when it can't be decomposed."""
self.valueSrcCombo.setCurrentIndex(1)
self._varMgr.populateCombo(self.existingVarCombo)
found = self._varMgr.findExactNameEntry(self.existingVarCombo, expr)
if found < 0:
self.existingVarCombo.addItem(expr, (expr, self._currentTargetType))
self.existingVarCombo.setCurrentIndex(self.existingVarCombo.count() - 1)
else:
self.existingVarCombo.setCurrentIndex(found)
def refreshVarCombos(
self