View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.bcel.generic;
20  
21  /**
22   * Equality of instructions isn't clearly to be defined. You might wish, for example, to compare whether instructions
23   * have the same meaning. E.g., whether two INVOKEVIRTUALs describe the same call.
24   * <p>
25   * The DEFAULT comparator however, considers two instructions to be equal if they have same opcode and point to the same
26   * indexes (if any) in the constant pool or the same local variable index. Branch instructions must have the same
27   * target.
28   * </p>
29   *
30   * @see Instruction
31   */
32  public interface InstructionComparator {
33  
34      /**
35       * Default instruction comparator.
36       */
37      InstructionComparator DEFAULT = (i1, i2) -> {
38          if (i1.getOpcode() == i2.getOpcode()) {
39              if (i1 instanceof BranchInstruction) {
40                  // BIs are never equal to make targeters work correctly (BCEL-195)
41                  return false;
42  //                } else if (i1 == i2) { TODO consider adding this shortcut
43  //                    return true; // this must be AFTER the BI test
44              }
45              if (i1 instanceof ConstantPushInstruction) {
46                  return ((ConstantPushInstruction) i1).getValue().equals(((ConstantPushInstruction) i2).getValue());
47              }
48              if (i1 instanceof IndexedInstruction) {
49                  return ((IndexedInstruction) i1).getIndex() == ((IndexedInstruction) i2).getIndex();
50              }
51              if (i1 instanceof NEWARRAY) {
52                  return ((NEWARRAY) i1).getTypecode() == ((NEWARRAY) i2).getTypecode();
53              }
54              return true;
55          }
56          return false;
57      };
58  
59      /**
60       * Compares two instructions for equality.
61       *
62       * @param i1 the first instruction.
63       * @param i2 the second instruction.
64       * @return true if the instructions are equal, false otherwise.
65       */
66      boolean equals(Instruction i1, Instruction i2);
67  }