cqlib_core/compile/knowledge/rule_dsl/ast.rs
1// This code is part of Cqlib.
2//
3// (C) Copyright China Telecom Quantum Group 2025-2026
4//
5// This code is licensed under the Apache License, Version 2.0. You may
6// obtain a copy of this license in the LICENSE.txt file in the root directory
7// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8//
9// Any modifications or derivative works of this code must retain this
10// copyright notice, and modified files need to carry a notice indicating
11// that they have been altered from the originals.
12
13//! AST definitions for the rule DSL.
14//!
15//! This module defines the surface syntax tree ([`RuleDef`], [`GatePattern`])
16//! produced by the parser. Lowering to runtime structures is handled by the
17//! [`lower`](crate::compile::knowledge::rule_dsl::lower) module.
18
19use crate::circuit::Parameter;
20use crate::compile::knowledge::rule::Condition;
21
22/// Surface AST for a single optimization rule.
23#[derive(Debug, Clone)]
24pub struct RuleDef {
25 /// Name of the rule, e.g. `merge_rz`.
26 pub name: String,
27 /// Gate patterns that must be matched in order.
28 pub match_ops: Vec<GatePattern>,
29 /// Algebraic conditions on the matched variables.
30 pub conditions: Vec<Condition>,
31 /// Replacement gate patterns (may be empty for deletion rules).
32 pub rewrite_ops: Vec<GatePattern>,
33}
34
35/// Gate identifier used by one surface pattern.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum GateSpec {
38 /// Standard gate identifier, e.g. `H`, `RX`, `CX`.
39 Standard { gate_name: String },
40 /// Multi-controlled gate identifier, e.g. `MCX[3]`.
41 MultiControlled {
42 /// Base standard gate to control.
43 base_gate_name: String,
44 /// Number of controls added by the `MC` wrapper.
45 added_controls: u8,
46 },
47}
48
49impl GateSpec {
50 /// Returns the canonical DSL spelling of this gate spec.
51 pub fn display_name(&self) -> String {
52 match self {
53 Self::Standard { gate_name } => gate_name.clone(),
54 Self::MultiControlled {
55 base_gate_name,
56 added_controls,
57 } => format!("MC{base_gate_name}[{added_controls}]"),
58 }
59 }
60}
61
62/// Surface AST for a single gate pattern.
63///
64/// A pattern looks like `RZ(a + b) 0` or `MCX[3] 0 1 2 3`:
65/// - `gate` = gate identifier
66/// - `params` = `[Parameter("a + b")]`
67/// - `qubits` = `[0]`
68#[derive(Debug, Clone)]
69pub struct GatePattern {
70 /// Gate identifier.
71 pub gate: GateSpec,
72 /// Parameter expressions appearing inside the parentheses.
73 pub params: Vec<Parameter>,
74 /// Qubit indices appearing after the parentheses.
75 pub qubits: Vec<u32>,
76}