<commit_before>/*
 * FindBugs - Find bugs in Java programs
 * Copyright (C) 2005 <NAME> <<EMAIL>>
 * Copyright (C) 2005-2006 University of Maryland
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package edu.umd.cs.findbugs.detect;


import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.GotoInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.LOOKUPSWITCH;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.TABLESWITCH;
import org.apache.bcel.util.ByteSequence;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.EdgeTypes;
import edu.umd.cs.findbugs.ba.MethodUnprofitableException;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;

/** @author <NAME>  4/2005  original author
 *  @author <NAME>     7/2006  serious reworking
 */
public class DuplicateBranches extends PreorderVisitor implements Detector
{
	private ClassContext classContext;
	private BugReporter bugReporter;
	private Collection<BugInstance> pendingBugs = new LinkedList<BugInstance>();

	public DuplicateBranches(BugReporter bugReporter) {
		this.bugReporter = bugReporter;
	}


	public void visitClassContext(ClassContext classContext) {
		this.classContext = classContext;
		classContext.getJavaClass().accept(this);
	}

	@Override
		 public void visitMethod(Method method) {
		try {
			if (method.getCode() == null)
				return;

			CFG cfg = classContext.getCFG(method);

			Iterator<BasicBlock> bbi = cfg.blockIterator();
			while (bbi.hasNext()) {
				BasicBlock bb = bbi.next();

				int numOutgoing = cfg.getNumOutgoingEdges(bb);
				if (numOutgoing == 2)
					findIfElseDuplicates(cfg, method, bb);
				else if (numOutgoing > 2)
					findSwitchDuplicates(cfg, method, bb);
			}
		} catch (MethodUnprofitableException mue) {
			if (SystemProperties.getBoolean("unprofitable.debug")) // otherwise don't report
				bugReporter.logError("skipping unprofitable method in " + getClass().getName());
		} catch (Exception e) {
			bugReporter.logError("Failure examining basic blocks in Duplicate Branches detector", e);
		}
		if (pendingBugs.size() <= 2)
		for(BugInstance b : pendingBugs) 
			bugReporter.reportBug(b);
		pendingBugs.clear();
		
	}

	private void findIfElseDuplicates(CFG cfg, Method method, BasicBlock bb) {
		BasicBlock thenBB = null, elseBB = null;

		Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb);
		while (iei.hasNext()) {
			Edge e = iei.next();
			if (e.getType() == EdgeTypes.IFCMP_EDGE) {
				elseBB = e.getTarget();
			}
			else if (e.getType() == EdgeTypes.FALL_THROUGH_EDGE) {
				thenBB = e.getTarget();
			}
		}

		if ((thenBB == null) || (elseBB == null))
			return;
		InstructionHandle thenStartHandle = getDeepFirstInstruction(cfg, thenBB);
		InstructionHandle elseStartHandle = getDeepFirstInstruction(cfg, elseBB);
		if ((thenStartHandle == null) || (elseStartHandle == null))
			return;

		int thenStartPos = thenStartHandle.getPosition();
		int elseStartPos = elseStartHandle.getPosition();

		InstructionHandle thenFinishIns = findThenFinish(cfg, thenBB, elseStartPos);
		int thenFinishPos = thenFinishIns.getPosition();

		if (!(thenFinishIns.getInstruction() instanceof GotoInstruction))
			return;

		InstructionHandle elseFinishHandle =
				((GotoInstruction) thenFinishIns.getInstruction()).getTarget();
		int elseFinishPos = elseFinishHandle.getPosition();

		if (thenFinishPos >= elseStartPos)
			return;

		if ((thenFinishPos - thenStartPos) != (elseFinishPos - elseStartPos))
			return;

		byte[] thenBytes = getCodeBytes(method, thenStartPos, thenFinishPos);
		byte[] elseBytes = getCodeBytes(method, elseStartPos, elseFinishPos);

		if (!Arrays.equals(thenBytes, elseBytes))
			return;

		// adjust elseFinishPos to be inclusive (for source line attribution)
		InstructionHandle elseLastIns = elseFinishHandle.getPrev();
		if (elseLastIns != null) elseFinishPos = elseLastIns.getPosition();

		pendingBugs.add(new BugInstance(this, "DB_DUPLICATE_BRANCHES", NORMAL_PRIORITY)
				.addClass(classContext.getJavaClass())
				.addMethod(classContext.getJavaClass(), method)
				.addSourceLineRange(classContext, this, thenStartPos, thenFinishPos)
				.addSourceLineRange(classContext, this, elseStartPos, elseFinishPos));
	}

	/** Like bb.getFirstInstruction() except that if null is
	 *  returned it will follow the FALL_THROUGH_EDGE (if any) */
	private static InstructionHandle getDeepFirstInstruction(CFG cfg, BasicBlock bb) {
		InstructionHandle ih = bb.getFirstInstruction();
		if (ih != null) return ih;
		Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb);
		while (iei.hasNext()) {
			Edge e = iei.next();
			String edgeString = e.toString();
			if (EdgeTypes.FALL_THROUGH_EDGE == e.getType())<commit_msg>sanity check on ranges<commit_after>/*
 * FindBugs - Find bugs in Java programs
 * Copyright (C) 2005 <NAME> <<EMAIL>>
 * Copyright (C) 2005-2006 University of Maryland
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package edu.umd.cs.findbugs.detect;


import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.GotoInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.LOOKUPSWITCH;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.TABLESWITCH;
import org.apache.bcel.util.ByteSequence;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.EdgeTypes;
import edu.umd.cs.findbugs.ba.MethodUnprofitableException;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;

/** @author <NAME>  4/2005  original author
 *  @author <NAME>     7/2006  serious reworking
 */
public class DuplicateBranches extends PreorderVisitor implements Detector
{
	private ClassContext classContext;
	private BugReporter bugReporter;
	private Collection<BugInstance> pendingBugs = new LinkedList<BugInstance>();

	public DuplicateBranches(BugReporter bugReporter) {
		this.bugReporter = bugReporter;
	}


	public void visitClassContext(ClassContext classContext) {
		this.classContext = classContext;
		classContext.getJavaClass().accept(this);
	}

	@Override
		 public void visitMethod(Method method) {
		try {
			if (method.getCode() == null)
				return;

			CFG cfg = classContext.getCFG(method);

			Iterator<BasicBlock> bbi = cfg.blockIterator();
			while (bbi.hasNext()) {
				BasicBlock bb = bbi.next();

				int numOutgoing = cfg.getNumOutgoingEdges(bb);
				if (numOutgoing == 2)
					findIfElseDuplicates(cfg, method, bb);
				else if (numOutgoing > 2)
					findSwitchDuplicates(cfg, method, bb);
			}
		} catch (MethodUnprofitableException mue) {
			if (SystemProperties.getBoolean("unprofitable.debug")) // otherwise don't report
				bugReporter.logError("skipping unprofitable method in " + getClass().getName());
		} catch (Exception e) {
			bugReporter.logError("Failure examining basic blocks in Duplicate Branches detector", e);
		}
		if (pendingBugs.size() <= 2)
		for(BugInstance b : pendingBugs) 
			bugReporter.reportBug(b);
		pendingBugs.clear();
		
	}

	private void findIfElseDuplicates(CFG cfg, Method method, BasicBlock bb) {
		BasicBlock thenBB = null, elseBB = null;

		Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb);
		while (iei.hasNext()) {
			Edge e = iei.next();
			if (e.getType() == EdgeTypes.IFCMP_EDGE) {
				elseBB = e.getTarget();
			}
			else if (e.getType() == EdgeTypes.FALL_THROUGH_EDGE) {
				thenBB = e.getTarget();
			}
		}

		if ((thenBB == null) || (elseBB == null))
			return;
		InstructionHandle thenStartHandle = getDeepFirstInstruction(cfg, thenBB);
		InstructionHandle elseStartHandle = getDeepFirstInstruction(cfg, elseBB);
		if ((thenStartHandle == null) || (elseStartHandle == null))
			return;

		int thenStartPos = thenStartHandle.getPosition();
		int elseStartPos = elseStartHandle.getPosition();

		InstructionHandle thenFinishIns = findThenFinish(cfg, thenBB, elseStartPos);
		int thenFinishPos = thenFinishIns.getPosition();

		if (!(thenFinishIns.getInstruction() instanceof GotoInstruction))
			return;

		InstructionHandle elseFinishHandle =
				((GotoInstruction) thenFinishIns.getInstruction()).getTarget();
		int elseFinishPos = elseFinishHandle.getPosition();

		if (thenFinishPos >= elseStartPos)
			return;

		if ((thenFinishPos - thenStartPos) != (elseFinishPos - elseStartPos))
			return;

		if (thenFinishPos <= thenStartPos)
			return;

		byte[] thenBytes = getCodeBytes(method, thenStartPos, thenFinishPos);
		byte[] elseBytes = getCodeBytes(method, elseStartPos, elseFinishPos);

		if (!Arrays.equals(thenBytes, elseBytes))
			return;

		// adjust elseFinishPos to be inclusive (for source line attribution)
		InstructionHandle elseLastIns = elseFinishHandle.getPrev();
		if (elseLastIns != null) elseFinishPos = elseLastIns.getPosition();

		pendingBugs.add(new BugInstance(this, "DB_DUPLICATE_BRANCHES", NORMAL_PRIORITY)
				.addClass(classContext.getJavaClass())
				.addMethod(classContext.getJavaClass(), method)
				.addSourceLineRange(classContext, this, thenStartPos, thenFinishPos)
				.addSourceLineRange(classContext, this, elseStartPos, elseFinishPos));
	}

	/** Like bb.getFirstInstruction() except that if null is
	 *  returned it will follow the FALL_THROUGH_EDGE (if any) */
	private static InstructionHandle getDeepFirstInstruction(CFG cfg, BasicBlock bb) {
		InstructionHandle ih = bb.getFirstInstruction();
		if (ih != null) return ih;
		Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb);
		while (iei.hasNext()) {
			Edge e = iei.next();
			String edgeString = e.toString();
			if (EdgeTypes.FALL_THROUGH_EDGE == e.getType())
{'fraction_non_alphanumeric': 0.10698328644712891, 'fraction_numerical': 0.006784709581333774, 'mean_word_length': 4.731152204836415, 'pattern_counts': {'":': 0, '<': 26, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '418496', 'n_tokens_mistral': 4180, 'n_tokens_neox': 3740, 'n_words': 962}