Class VariableExtractor
java.lang.Object
cloud.opencode.base.expression.VariableExtractor
Variable Extractor
变量提取器
Utility class to extract variable names referenced in an expression.
Parses the expression into an AST and recursively walks all nodes
to collect IdentifierNode names.
用于提取表达式中引用的变量名的工具类。
将表达式解析为AST并递归遍历所有节点以收集 IdentifierNode 名称。
Features | 主要功能:
- Extract variables from expression string or pre-parsed AST node - 从表达式字符串或预解析的AST节点提取变量
- Recursive traversal with sealed interface pattern matching - 使用密封接口模式匹配的递归遍历
- Excludes special identifiers (#root, #this, root, this) - 排除特殊标识符(#root、#this、root、this)
- Returns insertion-ordered, unmodifiable Set - 返回插入有序的不可修改Set
- Handles all node types including V1.0.3 additions - 处理所有节点类型,包括V1.0.3新增节点
Usage Examples | 使用示例:
// Extract from expression string
Set<String> vars = VariableExtractor.extract("x + y * 2");
// vars = ["x", "y"]
// Extract from complex expression
Set<String> vars = VariableExtractor.extract("user.name == 'John' && age > 18");
// vars = ["user", "age"]
// Extract from pre-parsed AST node
Node ast = Parser.parse("a + b");
Set<String> vars = VariableExtractor.extract(ast);
// vars = ["a", "b"]
// Special identifiers are excluded
Set<String> vars = VariableExtractor.extract("#root.name + #this");
// vars = [] (special identifiers excluded)
Security | 安全性:
- Thread-safe: Yes, stateless utility with no shared mutable state - 线程安全: 是,无共享可变状态的无状态工具
- Null-safe: No, null expressions throw NullPointerException - 空值安全: 否,null表达式抛出NullPointerException
Performance | 性能:
- O(n) traversal where n is the number of AST nodes - O(n)遍历,n为AST节点数
- Uses LinkedHashSet for deterministic insertion order - 使用LinkedHashSet保证确定的插入顺序
- Since:
- JDK 25, opencode-base-expression V1.0.3
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
-
Method Details
-
extract
Extract variable names from an expression string 从表达式字符串中提取变量名Parses the expression and walks the resulting AST to collect all identifier names that represent user-defined variables.
解析表达式并遍历生成的AST,收集所有代表用户定义变量的标识符名称。
- Parameters:
expression- the expression string | 表达式字符串- Returns:
- unmodifiable set of variable names in insertion order | 按插入顺序排列的不可修改变量名集合
- Throws:
NullPointerException- if expression is null | 如果表达式为nullOpenExpressionException- if expression cannot be parsed | 如果表达式无法解析
-
extract
Extract variable names from a pre-parsed AST node 从预解析的AST节点中提取变量名Recursively walks the AST to collect all identifier names that represent user-defined variables (excluding special identifiers such as
#root,#this,true,false,null).递归遍历AST,收集所有代表用户定义变量的标识符名称 (排除特殊标识符如
#root、#this、true、false、null)。- Parameters:
node- the AST node to traverse | 要遍历的AST节点- Returns:
- unmodifiable set of variable names in insertion order | 按插入顺序排列的不可修改变量名集合
- Throws:
NullPointerException- if node is null | 如果节点为null
-