001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 *
017 */
018package org.apache.bcel.generic;
019
020/**
021 * Equality of instructions isn't clearly to be defined. You might wish, for example, to compare whether instructions
022 * have the same meaning. E.g., whether two INVOKEVIRTUALs describe the same call.
023 * <p>
024 * The DEFAULT comparator however, considers two instructions to be equal if they have same opcode and point to the same
025 * indexes (if any) in the constant pool or the same local variable index. Branch instructions must have the same
026 * target.
027 * </p>
028 *
029 * @see Instruction
030 */
031public interface InstructionComparator {
032
033    InstructionComparator DEFAULT = (i1, i2) -> {
034        if (i1.getOpcode() == i2.getOpcode()) {
035            if (i1 instanceof BranchInstruction) {
036                // BIs are never equal to make targeters work correctly (BCEL-195)
037                return false;
038//                } else if (i1 == i2) { TODO consider adding this shortcut
039//                    return true; // this must be AFTER the BI test
040            }
041            if (i1 instanceof ConstantPushInstruction) {
042                return ((ConstantPushInstruction) i1).getValue().equals(((ConstantPushInstruction) i2).getValue());
043            }
044            if (i1 instanceof IndexedInstruction) {
045                return ((IndexedInstruction) i1).getIndex() == ((IndexedInstruction) i2).getIndex();
046            }
047            if (i1 instanceof NEWARRAY) {
048                return ((NEWARRAY) i1).getTypecode() == ((NEWARRAY) i2).getTypecode();
049            }
050            return true;
051        }
052        return false;
053    };
054
055    boolean equals(Instruction i1, Instruction i2);
056}