InstructionComparator.java

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

  18. /**
  19.  * Equality of instructions isn't clearly to be defined. You might wish, for example, to compare whether instructions
  20.  * have the same meaning. E.g., whether two INVOKEVIRTUALs describe the same call.
  21.  * <p>
  22.  * The DEFAULT comparator however, considers two instructions to be equal if they have same opcode and point to the same
  23.  * indexes (if any) in the constant pool or the same local variable index. Branch instructions must have the same
  24.  * target.
  25.  * </p>
  26.  *
  27.  * @see Instruction
  28.  */
  29. public interface InstructionComparator {

  30.     InstructionComparator DEFAULT = (i1, i2) -> {
  31.         if (i1.getOpcode() == i2.getOpcode()) {
  32.             if (i1 instanceof BranchInstruction) {
  33.                 // BIs are never equal to make targeters work correctly (BCEL-195)
  34.                 return false;
  35. //                } else if (i1 == i2) { TODO consider adding this shortcut
  36. //                    return true; // this must be AFTER the BI test
  37.             }
  38.             if (i1 instanceof ConstantPushInstruction) {
  39.                 return ((ConstantPushInstruction) i1).getValue().equals(((ConstantPushInstruction) i2).getValue());
  40.             }
  41.             if (i1 instanceof IndexedInstruction) {
  42.                 return ((IndexedInstruction) i1).getIndex() == ((IndexedInstruction) i2).getIndex();
  43.             }
  44.             if (i1 instanceof NEWARRAY) {
  45.                 return ((NEWARRAY) i1).getTypecode() == ((NEWARRAY) i2).getTypecode();
  46.             }
  47.             return true;
  48.         }
  49.         return false;
  50.     };

  51.     boolean equals(Instruction i1, Instruction i2);
  52. }