Class Parser

java.lang.Object
cloud.opencode.base.expression.parser.Parser

public class Parser extends Object
Expression Parser 表达式解析器

Parses token lists into abstract syntax trees.

将词法单元列表解析为抽象语法树。

Features | 主要功能:

  • Recursive descent parsing with operator precedence - 带运算符优先级的递归下降解析
  • Support for ternary, elvis, logical, comparison, arithmetic, power operators - 支持三元、Elvis、逻辑、比较、算术、幂运算符
  • Bitwise operators: &, |, ^, ~, <<, >> - 位运算符
  • In and between operators for membership and range tests - in和between运算符用于成员和范围测试
  • Lambda expressions: x -> expr - Lambda表达式
  • Map literals: #{key: value} - Map字面量
  • String interpolation: "text ${expr}" - 字符串插值
  • Property access, method calls, index access - 属性访问、方法调用、索引访问
  • Collection filter (.?[]) and projection (.![]) - 集合过滤和投影
  • Null-safe navigation (?.) - 空安全导航
  • Maximum nesting depth limit (200) - 最大嵌套深度限制(200)

Operator Precedence (low to high) | 运算符优先级(低到高):

  1. Ternary: ? :
  2. Elvis: ?:
  3. Logical OR: ||, or
  4. Logical AND: &&, and
  5. Bitwise OR: |
  6. Bitwise XOR: ^
  7. Bitwise AND: &
  8. Equality: ==, !=, matches
  9. Relational: <, <=, >, >=, in, between, instanceof
  10. Shift: <<, >>
  11. Additive: +, -
  12. Multiplicative: *, /, %
  13. Power: **
  14. Unary: !, -, +, ~
  15. Postfix: ., ?., [], .?[], .![]
  16. Primary: literals, identifiers, functions, lambdas, map literals

Usage Examples | 使用示例:

Node ast = Parser.parse("price * (1 - discount)");
Object result = ast.evaluate(ctx);

// Elvis operator
Node elvis = Parser.parse("name ?: 'default'");

// In operator
Node in = Parser.parse("x in {1, 2, 3}");

// Between operator
Node between = Parser.parse("age between 18 and 65");

// Lambda
Node lambda = Parser.parse("filter(list, x -> x > 3)");

// Map literal
Node map = Parser.parse("#{name: 'Jon', age: 30}");

Security | 安全性:

  • Thread-safe: No, stateful parser instance - 线程安全: 否,有状态的解析器实例
  • Null-safe: No, null expression not supported - 空值安全: 否,不支持null表达式
  • Depth-limited to prevent stack overflow attacks - 深度限制以防止栈溢出攻击

Performance | 性能特性:

  • Time complexity: O(n) for parse where n is the number of tokens - 时间复杂度: parse 为 O(n),n为词法单元数量
  • Space complexity: O(n) for the resulting AST - 空间复杂度: O(n),存储生成的 AST
Since:
JDK 25, opencode-base-expression V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Details

    • Parser

      public Parser(List<Token> tokens)
      Create parser with tokens 使用词法单元创建解析器
      Parameters:
      tokens - the token list | 词法单元列表
  • Method Details

    • parse

      public Node parse()
      Parse tokens into AST 将词法单元解析为AST
      Returns:
      the AST root node | AST根节点
    • parse

      public static Node parse(String expression)
      Parse expression string 解析表达式字符串
      Parameters:
      expression - the expression | 表达式
      Returns:
      the AST root node | AST根节点