-
-
Notifications
You must be signed in to change notification settings - Fork 362
fix: expression evaluation #1005
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import expression from 'angular-expressions'; | ||
| import { stageStateManager } from '@/Core/Modules/stage/stageStateManager'; | ||
| import { webgalStore } from '@/store/store'; | ||
| import { logger } from '@/Core/util/logger'; | ||
| import random from 'lodash/random'; | ||
|
|
||
| /** | ||
| * 提取变量名和表达式 | ||
| * @param expressionString 表达式字符串,例如 "x = a + 5" | ||
| * @returns 包含变量名和表达式,如果无效则返回 undefined | ||
| */ | ||
| export function extractVariableNameAndExpression( | ||
| expressionString: string, | ||
| ): { variableName: string; expression: string } | undefined { | ||
| const equalIndex = expressionString.indexOf('='); | ||
| if (equalIndex === -1) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const variableName = expressionString.substring(0, equalIndex).trim(); | ||
| if (variableName.length === 0) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const expression = expressionString.substring(equalIndex + 1).trim(); | ||
| if (expression.length === 0) { | ||
| return undefined; | ||
| } | ||
|
|
||
| return { variableName, expression }; | ||
| } | ||
|
|
||
| // 内置函数 | ||
| const builtinFunctions = { | ||
| random: (...args: any[]) => { | ||
| return args.length ? random(...args) : Math.random(); | ||
| }, | ||
| }; | ||
|
|
||
| /** | ||
| * 评估表达式字符串 | ||
| * @param expressionString 表达式字符串 | ||
| * @returns 评估结果,可能是 string、number、boolean 或 undefined | ||
| * 但也有可能返回其他类型,取决于表达式的内容和上下文 | ||
| */ | ||
| export function evaluateExpression(expressionString: string): string | number | boolean | undefined { | ||
| try { | ||
| const evaluate = expression.compile(expressionString); | ||
|
|
||
| const stageState = stageStateManager.getCalculationStageState(); | ||
| const stageVar = stageState.GameVar; | ||
| const userData = webgalStore.getState().userData; | ||
| const globalVar = userData.globalGameVar; | ||
|
|
||
| const scope: any = {}; | ||
| // 先加入内置函数(最低优先级) | ||
| Object.assign(scope, builtinFunctions); | ||
| // 然后加入全局变量 | ||
| Object.assign(scope, globalVar); | ||
| // 最后加入舞台变量以保证最高优先级 | ||
| Object.assign(scope, stageVar); | ||
| // 支持 $ 前缀的特殊值 | ||
| scope['$stage'] = stageState; | ||
| scope['$userData'] = userData; | ||
|
|
||
| const result = evaluate(scope); | ||
| switch (typeof result) { | ||
| case 'string': | ||
| case 'number': | ||
| case 'boolean': | ||
| return result; | ||
| default: | ||
| logger.warn(`不支持的表达式求值类型: ${typeof result},表达式: ${expressionString}`); | ||
| return undefined; | ||
| } | ||
| } catch (error) { | ||
| logger.warn(`表达式求值失败: ${expressionString}`, error); | ||
| return undefined; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,6 +11,8 @@ import get from 'lodash/get'; | |
| import random from 'lodash/random'; | ||
| import { getBooleanArgByKey } from '../util/getSentenceArg'; | ||
| import { stageStateManager } from '@/Core/Modules/stage/stageStateManager'; | ||
| import { WebGAL } from '@/Core/WebGAL'; | ||
| import { evaluateExpression, extractVariableNameAndExpression } from '@/Core/controller/gamePlay/expressionEvaluation'; | ||
|
|
||
| interface ISetGameVarFromExpressionPayload { | ||
| key: string; | ||
|
|
@@ -40,7 +42,13 @@ export const setGameVarFromExpression = ({ | |
| if (!normalizedKey) { | ||
| return; | ||
| } | ||
| setGameVar({ key: normalizedKey, value: resolveSetVarValue(value) }); | ||
|
|
||
| const resolvedValue = resolveSetVarValue(value); | ||
| if (resolvedValue === undefined) { | ||
| return; | ||
| } | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 此处应有 log |
||
| setGameVar({ key: normalizedKey, value: resolvedValue }); | ||
|
|
||
| if (isGlobal) { | ||
| logger.debug('设置全局变量:', { key: normalizedKey, value: webgalStore.getState().userData.globalGameVar[normalizedKey] }); | ||
| if (persistGlobal) { | ||
|
|
@@ -57,27 +65,41 @@ export const setGameVarFromExpression = ({ | |
| */ | ||
| export const setVar = (sentence: ISentence): IPerform => { | ||
| const setGlobal = getBooleanArgByKey(sentence, 'global') ?? false; | ||
| if (sentence.content.match(/\s*=\s*/)) { | ||
| const key = sentence.content.split(/\s*=\s*/)[0]; | ||
| const valExp = sentence.content.split(/\s*=\s*/)[1]; | ||
| setGameVarFromExpression({ key, value: valExp, isGlobal: setGlobal }); | ||
| if (WebGAL.legacyExpressionParser) { | ||
| if (sentence.content.match(/\s*=\s*/)) { | ||
| const key = sentence.content.split(/\s*=\s*/)[0]; | ||
| const valExp = sentence.content.split(/\s*=\s*/)[1]; | ||
| setGameVarFromExpression({ key, value: valExp, isGlobal: setGlobal }); | ||
| } | ||
| } else { | ||
| const extracted = extractVariableNameAndExpression(sentence.content); | ||
| if (extracted) { | ||
| const { variableName, expression } = extracted; | ||
| setGameVarFromExpression({ key: variableName, value: expression, isGlobal: setGlobal }); | ||
| } else { | ||
| logger.error(`setVar 语句格式错误,无法提取变量名和表达式: ${sentence.content}`); | ||
| } | ||
| } | ||
| return createNonePerform(); | ||
| }; | ||
|
|
||
| type BaseVal = string | number | boolean | undefined; | ||
|
|
||
| export function resolveSetVarValue(valExp: string): string | boolean | number { | ||
| export function resolveSetVarValue(valExp: string): string | boolean | number | undefined { | ||
| if (!WebGAL.legacyExpressionParser) { | ||
| return evaluateExpression(valExp); | ||
| } | ||
|
|
||
| if (/^\s*[a-zA-Z_$][\w$]*\s*\(.*\)\s*$/.test(valExp)) { | ||
| return EvaluateExpression(valExp); | ||
| return LegacyEvaluateExpression(valExp); | ||
| } else if (valExp.match(/[+\-*\/()]/)) { | ||
| const valExpArr = valExp.split(/([+\-*\/()])/g); | ||
| const valExp2 = valExpArr | ||
| .map((e) => { | ||
| if (!e.trim().match(/^[a-zA-Z_$][a-zA-Z0-9_.]*$/)) { | ||
| return e; | ||
| } | ||
| const _r = getValueFromStateElseKey(e.trim(), true); | ||
| const _r = legacyGetValueFromStateElseKey(e.trim(), true); | ||
| return typeof _r === 'string' ? `'${_r}'` : _r; | ||
| }) | ||
| .reduce((pre, curr) => pre + curr, ''); | ||
|
|
@@ -102,7 +124,7 @@ export function resolveSetVarValue(valExp: string): string | boolean | number { | |
| if (!isNaN(Number(valExp))) { | ||
| return Number(valExp); | ||
| } else { | ||
| return getValueFromStateElseKey(valExp, true) ?? ''; | ||
| return legacyGetValueFromStateElseKey(valExp, true) ?? ''; | ||
| } | ||
| } | ||
| return ''; | ||
|
|
@@ -111,7 +133,7 @@ export function resolveSetVarValue(valExp: string): string | boolean | number { | |
| /** | ||
| * 执行函数 | ||
| */ | ||
| function EvaluateExpression(val: string) { | ||
| function LegacyEvaluateExpression(val: string) { | ||
| const instance = expression.compile(val); | ||
| return instance({ | ||
| random: (...args: any[]) => { | ||
|
|
@@ -123,7 +145,7 @@ function EvaluateExpression(val: string) { | |
| /** | ||
| * 取不到时返回 undefined | ||
| */ | ||
| export function getValueFromState(key: string) { | ||
| export function legacyGetValueFromState(key: string) { | ||
| let ret: any; | ||
| const stage = stageStateManager.getCalculationStageState(); | ||
| const userData = webgalStore.getState().userData; | ||
|
|
@@ -142,8 +164,8 @@ export function getValueFromState(key: string) { | |
| /** | ||
| * 取不到时返回 {key} | ||
| */ | ||
| export function getValueFromStateElseKey(key: string, useKeyNameAsReturn = false, quoteString = false) { | ||
| const valueFromState = getValueFromState(key); | ||
| export function legacyGetValueFromStateElseKey(key: string, useKeyNameAsReturn = false, quoteString = false) { | ||
| const valueFromState = legacyGetValueFromState(key); | ||
| if (valueFromState === null || valueFromState === undefined) { | ||
| logger.warn('valueFromState result null, key = ' + key); | ||
| if (useKeyNameAsReturn) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,4 +25,5 @@ export class WebgalCore { | |
| public steam = new SteamIntegration(); | ||
| public template: WebgalTemplate | null = null; | ||
| public styleObjects: Map<string, IWebGALStyleObj> = new Map(); | ||
| public legacyExpressionParser = false; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a game omits Useful? React with 👍 / 👎. |
||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
性能优化建议:缓存编译结果与避免对象拷贝
在当前实现中,每次调用
evaluateExpression都会执行以下操作:expression.compile(expressionString)重新编译表达式。编译是一个涉及词法分析、语法分析和生成 AST 的 CPU 密集型操作。Object.assign浅拷贝builtinFunctions、globalVar和stageVar。在大型游戏中,变量(尤其是全局变量和舞台变量)的数量可能非常多,频繁的对象创建和属性拷贝会带来显著的 CPU 开销和垃圾回收(GC)压力。解决方案:
Map缓存已编译的表达式函数。由于angular-expressions编译出的函数是无状态的,因此可以安全地复用。Proxy代理作用域查找:通过Proxy动态拦截属性读取,避免每次求值时都进行对象拷贝,从而实现零拷贝(Zero-copy)查找。以下是优化后的代码建议: