/*
 * fb-contrib - Auxiliary detectors for Java programs
 * Copyright (C) 2005-2016 Dave Brosius
 *
 * 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 com.mebigfatguy.fbcontrib.detect;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;

import com.mebigfatguy.fbcontrib.utils.BugType;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.XFactory;

/**
 * looks for simple fields that only store one of several constant values. This usually is an indication that this field should really be an enum type.
 */
public class PoorMansEnum extends BytecodeScanningDetector {

    private BugReporter bugReporter;
    private Map<String, Set<Object>> fieldValues;
    private Map<String, Field> nameToField;
    private Map<String, SourceLineAnnotation> firstFieldUse;
    private OpcodeStack stack;

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

    @Override
    public void visitClassContext(ClassContext classContext) {
        try {
            JavaClass cls = classContext.getJavaClass();
            if (cls.getMajor() >= Constants.MAJOR_1_5) {
                fieldValues = new HashMap<String, Set<Object>>();
                nameToField = new HashMap<String, Field>();
                for (Field f : cls.getFields()) {
                    if (f.isPrivate() && !f.isSynthetic()) {
                        String fieldName = f.getName();
                        fieldValues.put(fieldName, null);
                        nameToField.put(fieldName, f);
                    }
                }
                if (!fieldValues.isEmpty()) {
                    stack = new OpcodeStack();
                    firstFieldUse = new HashMap<String, SourceLineAnnotation>();
                    super.visitClassContext(classContext);

                    for (Map.Entry<String, Set<Object>> fieldInfo : fieldValues.entrySet()) {
                        Set<Object> values = fieldInfo.getValue();
                        if ((values != null) && (values.size() >= 3)) {
                            String fieldName = fieldInfo.getKey();
                            bugReporter.reportBug(new BugInstance(this, BugType.PME_POOR_MANS_ENUM.name(), NORMAL_PRIORITY).addClass(this)
                                    .addField(XFactory.createXField(cls, nameToField.get(fieldName))).addSourceLine(firstFieldUse.get(fieldName)));
                        }
                    }
                }
            }
        } finally {
            fieldValues = null;
            nameToField = null;
            firstFieldUse = null;
            stack = null;
        }
    }

    @Override
    public void visitCode(Code obj) {
        if (!fieldValues.isEmpty()) {
            stack.resetForMethodEntry(this);
            super.visitCode(obj);
        }
    }

    @Override
    public void sawOpcode(int seen) {
        try {
            stack.precomputation(this);
            if (fieldValues.isEmpty()) {
                return;
            }

            if (seen == PUTFIELD) {
                String fieldName = getNameConstantOperand();
                if (fieldValues.containsKey(fieldName) && (stack.getStackDepth() > 0)) {
                    OpcodeStack.Item item = stack.getStackItem(0);
                    Object cons = item.getConstant();
                    if (cons == null) {
                        fieldValues.remove(fieldName);
                        nameToField.remove(fieldName);
                        firstFieldUse.remove(fieldName);
                    } else {
                        Set<Object> values = fieldValues.get(fieldName);
                        if (values == null) {
                            values = new HashSet<Object>();
                            fieldValues.put(fieldName, values);
                            if (firstFieldUse.get(fieldName) == null) {
                                firstFieldUse.put(fieldName, SourceLineAnnotation.fromVisitedInstruction(this));
                            }
                        }
                        values.add(cons);
                    }
                }
            }
        } finally {
            stack.sawOpcode(this, seen);
        }
    }
}

@@ -1178,16 +1178,83 @@
 BugType;
+%0Aimport com.mebigfatguy.fbcontrib.utils.StopOpcodeParsingException;
 %0A%0Aimport
@@ -2345,35 +2345,16 @@
 HashMap%3C
-String, Set%3CObject%3E
 %3E();%0A   
@@ -2392,29 +2392,16 @@
 HashMap%3C
-String, Field
 %3E();%0A   
@@ -2862,42 +2862,40 @@
 Map%3C
-String, SourceLineAnnotation%3E();%0A 
+%3E();%0A%0A                    try %7B%0A
     
@@ -2901,32 +2901,37 @@
                 
+     
 super.visitClass
@@ -2950,24 +2950,28 @@
 sContext);%0A%0A
+    
             
@@ -3068,32 +3068,36 @@
                 
+    
 Set%3CObject%3E valu
@@ -3143,24 +3143,28 @@
             
+ 
+   
 if ((values 
@@ -3219,32 +3219,36 @@
                 
+    
 String fieldName
@@ -3266,24 +3266,28 @@
 o.getKey();%0A
+    
             
@@ -3449,16 +3449,20 @@
         
+  
+  
 .addFiel
@@ -3581,33 +3581,166 @@
                 
-%7D
+    %7D%0A                        %7D%0A                    %7D catch (StopOpcodeParsingException e) %7B%0A                        // no fields left
 %0A               
@@ -4234,87 +4234,8 @@
 is);
-%0A            if (fieldValues.isEmpty()) %7B%0A                return;%0A            %7D
 %0A%0A  
@@ -4737,32 +4737,180 @@
 move(fieldName);
+%0A%0A                        if (fieldValues.isEmpty()) %7B%0A                            throw new StopOpcodeParsingException();%0A                        %7D
 %0A               
@@ -5091,22 +5091,16 @@
 HashSet%3C
-Object
 %3E();%0A   

use StopOpcodeParsingException to skip PME when there are no more fields to process