SlotReplacementMapping.java

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.nereids;

import org.apache.doris.nereids.trees.expressions.ExprId;

import java.util.HashMap;
import java.util.Map;

/**
 * Records the expression ids that a rewrite has replaced and resolves them transitively.
 *
 * <p>A rewrite may give a slot a new expression id while it keeps the same meaning, so a reference
 * that was recorded earlier, e.g. the slot of a CTE producer that a consumer copies, can become
 * stale and then no longer matches any slot of the rewritten plan. A slot can be replaced more than
 * once during one statement, so resolving has to follow the whole chain: when {@code #1} is replaced
 * by {@code #2} and later {@code #2} by {@code #3}, the recorded {@code #1} resolves to {@code #3}
 * and never to the outdated {@code #2}.
 */
public class SlotReplacementMapping {
    private final Map<ExprId, ExprId> replacements = new HashMap<>();

    /**
     * Records that the expression id {@code replacedId} has been replaced by {@code replacementId}.
     * Recording an identity replacement or the same replacement twice is a no-op.
     */
    public void record(ExprId replacedId, ExprId replacementId) {
        if (replacedId.equals(replacementId)) {
            return;
        }
        ExprId previous = replacements.put(replacedId, replacementId);
        if (previous == null || previous.equals(replacementId)) {
            return;
        }
        // keep the chain short: everything that pointed to the previous replacement now points to
        // the new one as well
        for (Map.Entry<ExprId, ExprId> entry : replacements.entrySet()) {
            if (entry.getValue().equals(previous)) {
                entry.setValue(replacementId);
            }
        }
    }

    /**
     * Returns the expression id that currently stands for the recorded {@code id}, following the
     * replacements until the last one. An id that was never replaced resolves to itself.
     */
    public ExprId resolve(ExprId id) {
        ExprId current = replacements.get(id);
        if (current == null) {
            return id;
        }
        // path compression: remember that the whole prefix now resolves to the final id
        int remaining = replacements.size();
        while (remaining-- > 0) {
            ExprId next = replacements.get(current);
            if (next == null || next.equals(current)) {
                break;
            }
            current = next;
        }
        replacements.put(id, current);
        return current;
    }

    /**
     * Returns the current expression id as the int that {@code RoaringBitmap} based derivation
     * contexts use.
     */
    public int resolveToInt(ExprId id) {
        return resolve(id).asInt();
    }

    public boolean isEmpty() {
        return replacements.isEmpty();
    }

    /** Returns a copy of the recorded replacements, e.g. to restore them later. */
    public Map<ExprId, ExprId> snapshot() {
        return new HashMap<>(replacements);
    }

    /** Replaces the recorded replacements by a snapshot taken earlier. */
    public void restoreFrom(Map<ExprId, ExprId> snapshot) {
        replacements.clear();
        replacements.putAll(snapshot);
    }

    /** Forgets every recorded replacement, e.g. when the plan tree is rebuilt from scratch. */
    public void clear() {
        replacements.clear();
    }
}