mz_transform/fusion/
negate.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Fuses a sequence of `Negate` operators in to one or zero `Negate` operators.
11
12use mz_expr::MirRelationExpr;
13
14use crate::TransformCtx;
15
16/// Fuses a sequence of `Negate` operators in to one or zero `Negate` operators.
17#[derive(Debug)]
18pub struct Negate;
19
20impl crate::Transform for Negate {
21    fn name(&self) -> &'static str {
22        "NegateFusion"
23    }
24
25    #[mz_ore::instrument(
26        target = "optimizer",
27        level = "debug",
28        fields(path.segment = "negate_fusion")
29    )]
30    fn actually_perform_transform(
31        &self,
32        relation: &mut MirRelationExpr,
33        _: &mut TransformCtx,
34    ) -> Result<(), crate::TransformError> {
35        relation.visit_pre_mut(Self::action);
36        mz_repr::explain::trace_plan(&*relation);
37        Ok(())
38    }
39}
40
41impl Negate {
42    /// Fuses a sequence of `Negate` operators into one or zero `Negate` operators.
43    pub fn action(relation: &mut MirRelationExpr) {
44        if let MirRelationExpr::Negate { input } = relation {
45            let mut require_negate = true;
46            while let MirRelationExpr::Negate { input: inner_input } = &mut **input {
47                **input = inner_input.take_dangerous();
48                require_negate = !require_negate;
49            }
50
51            if !require_negate {
52                *relation = input.take_dangerous();
53            }
54        }
55    }
56}