Crate rust_cel_parser

Crate rust_cel_parser 

Source
Expand description

A parser for Google’s Common Expression Language (CEL).

This crate provides a parser that transforms CEL expression strings into a Abstract Syntax Tree (AST).

§Key Features

  • CEL Spec Compliance: Parses a wide range of the CEL specification, including all literals, operators, and standard macros.
  • Detailed AST: A comprehensive and precise ast::Expr enum represents the structure of the parsed code.
  • Ergonomic Traversal: A built-in visitor::Visitor pattern allows you to inspect and analyze the AST without writing recursive boilerplate.
  • Fluent AST Construction: A builder module provides a clean, fluent API for programmatically creating AST nodes, perfect for testing or code generation.
  • Rich Error Reporting: On failure, returns a CelParserError with precise line and column information.

§Getting Started: Parsing an Expression

The main entry point to the library is the parse_cel_program function.

use rust_cel_parser::{parse_cel_program, Expr, BinaryOperator, Literal};

let expression = "request.auth.claims['group'] == 'admin'";
let ast = parse_cel_program(expression).unwrap();

// You can inspect the AST using helper methods
if let Some((op, left, right)) = ast.as_binary_op() {
    assert_eq!(op, BinaryOperator::Eq);
    assert_eq!(right.as_literal(), Some(&Literal::String("admin".to_string())));
} else {
    panic!("Expected a binary operation");
}

§Building an AST Programmatically

The builder module is ideal for creating expected ASTs in tests.

use rust_cel_parser::{Expr, BinaryOperator, builder::*};

// Represents the expression: `a.b + 1`
let expected_ast = add(
    field_access(ident("a"), "b"),
    1 // .into() is called implicitly!
);

assert_eq!(
    expected_ast,
    Expr::BinaryOp {
        op: BinaryOperator::Add,
        left: Box::new(Expr::FieldAccess {
            base: Box::new(Expr::Identifier("a".to_string())),
            field: "b".to_string(),
        }),
        right: Box::new(Expr::from(1i64)),
    }
);

Modules§

builder
Fluent functions for constructing AST nodes program by programmatically.

Structs§

CelParser

Enums§

BinaryOperator
An operator that takes two operands.
CelParserError
CelType
A way to represent the type of a value in an expression.
ComprehensionOp
A comprehension operation is a way to iterate over a collection and apply a filter or transformation.
Expr
Literal
A literal is a primitive value that can be used in an expression.
Rule
UnaryOperator
A unary operator is an operator that takes a single operand.

Traits§

Visitor
A trait for visiting nodes in the AST in an immutable fashion.

Functions§

parse_cel_program
Parses a full CEL program string into an AST.
walk_binary_op
walk_call
walk_comprehension
walk_conditional
walk_expr
walk_field_access
walk_has
walk_index
walk_list
walk_map
walk_map_literal
walk_message_literal
walk_unary_op