/*
* Copyright 2020 the original author or authors.
*
* Licensed 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
*
* https://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.openrewrite.java.search;
import org.jspecify.annotations.Nullable;
import org.openrewrite.Incubating;
import org.openrewrite.Tree;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Recursively checks the equality of each element of two ASTs to determine if two trees are semantically equal.
*
* Bug fixes related to semantic equality should be applied to `CombineSemanticallyEqualCatchBlocks$CommentVisitor` too.
*/
@Incubating(since = "7.24.0")
public class SemanticallyEqual {
protected SemanticallyEqual() {
}
public static boolean areEqual(J firstElem, J secondElem) {
SemanticallyEqualVisitor semanticallyEqualVisitor = new SemanticallyEqualVisitor(true);
semanticallyEqualVisitor.visit(firstElem, secondElem);
return semanticallyEqualVisitor.isEqual();
}
/**
* Compares method invocations and new class constructors based on the `JavaType.Method` instead of checking
* each types of each parameter.
* I.E. void foo(Object obj) {} invoked with `java.lang.String` or `java.lang.Integer` will return true.
*/
public static boolean areSemanticallyEqual(J firstElem, J secondElem) {
SemanticallyEqualVisitor semanticallyEqualVisitor = new SemanticallyEqualVisitor(false);
semanticallyEqualVisitor.visit(firstElem, secondElem);
return semanticallyEqualVisitor.isEqual.get();
}
@SuppressWarnings("ConstantConditions")
protected static class SemanticallyEqualVisitor extends JavaIsoVisitor {
private final boolean compareMethodArguments;
protected final AtomicBoolean isEqual = new AtomicBoolean(true);
private final Deque