Java Code Examples for org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair#getFirst()

The following examples show how to use org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair#getFirst() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClassCache.java    From cfr with MIT License 6 votes vote down vote up
public Pair<JavaRefTypeInstance, JavaRefTypeInstance> getRefClassForInnerOuterPair(String rawInnerName, String rawOuterName) {
    String innerName = ClassNameUtils.convertFromPath(rawInnerName);
    String outerName = ClassNameUtils.convertFromPath(rawOuterName);
    JavaRefTypeInstance inner = refClassTypeCache.get(innerName);
    JavaRefTypeInstance outer = refClassTypeCache.get(outerName);
    if (inner != null && outer != null) return Pair.make(inner, outer);
    Pair<JavaRefTypeInstance, JavaRefTypeInstance> pair = JavaRefTypeInstance.createKnownInnerOuter(innerName, outerName, outer, dcCommonState);
    if (inner == null) {
        add(innerName, pair.getFirst());
        inner = pair.getFirst();
    }
    if (outer == null) {
        add(outerName, pair.getSecond());
        outer = pair.getSecond();
    }
    return Pair.make(inner, outer);

}
 
Example 2
Source File: ClassFileDumperEnum.java    From cfr with MIT License 6 votes vote down vote up
private static void dumpEntry(Dumper d, Pair<StaticVariable, AbstractConstructorInvokation> entry, boolean last, JavaTypeInstance classType) {
    StaticVariable staticVariable = entry.getFirst();
    AbstractConstructorInvokation constructorInvokation = entry.getSecond();
    d.fieldName(staticVariable.getFieldName(), classType, false, true, true);

    if (constructorInvokation instanceof ConstructorInvokationSimple) {
        List<Expression> args = constructorInvokation.getArgs();
        if (args.size() > 2) {
            d.separator("(");
            for (int x = 2, len = args.size(); x < len; ++x) {
                if (x > 2) d.print(", ");
                d.dump(args.get(x));
            }
            d.separator(")");
        }
    } else if (constructorInvokation instanceof ConstructorInvokationAnonymousInner) {
        ((ConstructorInvokationAnonymousInner) constructorInvokation).dumpForEnum(d);
    } else {
        MiscUtils.handyBreakPoint();
    }
    if (last) {
        d.endCodeln();
    } else {
        d.print(",").newln();
    }
}
 
Example 3
Source File: AttributeTypeAnnotations.java    From cfr with MIT License 6 votes vote down vote up
AttributeTypeAnnotations(ByteData raw, ConstantPool cp) {
    this.length = raw.getS4At(OFFSET_OF_ATTRIBUTE_LENGTH);
    int numAnnotations = raw.getU2At(OFFSET_OF_NUMBER_OF_ANNOTATIONS);
    long offset = OFFSET_OF_ANNOTATION_TABLE;

    Map<TypeAnnotationEntryValue, List<AnnotationTableTypeEntry>> entryData = MapFactory.newLazyMap(annotationTableEntryData, new UnaryFunction<TypeAnnotationEntryValue, List<AnnotationTableTypeEntry>>() {
        @Override
        public List<AnnotationTableTypeEntry> invoke(TypeAnnotationEntryValue arg) {
            return ListFactory.newList();
        }
    });

    for (int x = 0; x < numAnnotations; ++x) {
        Pair<Long, AnnotationTableTypeEntry> ape = AnnotationHelpers.getTypeAnnotation(raw, offset, cp);
        offset = ape.getFirst();
        AnnotationTableTypeEntry entry = ape.getSecond();
        entryData.get(entry.getValue()).add(entry);
    }
}
 
Example 4
Source File: AnnotationHelpers.java    From cfr with MIT License 5 votes vote down vote up
private static long getElementValuePair(ByteData raw, long offset, ConstantPool cp, Map<String, ElementValue> res) {
    ConstantPoolEntryUTF8 elementName = cp.getUTF8Entry(raw.getU2At(offset));
    offset += 2;
    Pair<Long, ElementValue> elementValueP = getElementValue(raw, offset, cp);
    offset = elementValueP.getFirst();
    res.put(elementName.getValue(), elementValueP.getSecond());
    return offset;
}
 
Example 5
Source File: AssertRewriter.java    From cfr with MIT License 5 votes vote down vote up
private StructuredStatement processSwitchEmbeddedThrow(StructuredStatement ifStm, BlockIdentifier outer, Block swBodyBlock, Op04StructuredStatement switchStm, StructuredSwitch struSwi) {
    // Soooo - if there's only ONE Assertion error that gets thrown, we can be pretty confident that
    // that's the assertion.
    // If there are multiple?
    // If they're identical, then we COULD consider them the same.  If not, give up, go home.
    // Also, don't forget to add a 'yield true' at the end of the last block, if there's not a yield or a throw there already!
    Map<Op04StructuredStatement, StructuredExpressionYield> replacements = MapFactory.newOrderedMap();
    BlockIdentifier swiBlockIdentifier = struSwi.getBlockIdentifier();
    AssertionTrackingControlFlowSwitchExpressionTransformer track = new AssertionTrackingControlFlowSwitchExpressionTransformer(swiBlockIdentifier, outer, replacements);
    switchStm.transform(track, new StructuredScope());
    if (track.failed) return null;
    if (track.throwSS.size() > 1) {
        return null;
    }

    replacements.clear();
    Expression exceptArg = null;
    if (track.throwSS.size() == 1) {
        StructuredStatement throwStm = track.throwSS.get(0);
        Pair<Boolean, Expression> excepTest = getThrowExpression(throwStm);
        if (!excepTest.getFirst()) return null;
        exceptArg = excepTest.getSecond();
        replacements.put(throwStm.getContainer(), new StructuredExpressionYield(Literal.FALSE));
    }

    List<SwitchExpression.Branch> branches = ListFactory.newList();
    if (!getBranches(swiBlockIdentifier, swiBlockIdentifier, swBodyBlock, branches, replacements, true)) return null;
    // And add yield true to the end of every branch that could roll off.

    SwitchExpression sw = new SwitchExpression(boolIjt, struSwi.getSwitchOn(), branches);
    return ((StructuredIf)ifStm).convertToAssertion(StructuredAssert.mkStructuredAssert(new BooleanExpression(sw), exceptArg));

}
 
Example 6
Source File: GetOptParser.java    From cfr with MIT License 5 votes vote down vote up
public <T> Pair<List<String>, T> parse(String[] args, GetOptSinkFactory<T> getOptSinkFactory) {
    Pair<List<String>, Map<String, String>> processed = process(args, getOptSinkFactory);
    final List<String> positional = processed.getFirst();
    Map<String, String> named = processed.getSecond();
    /*
     * A bit of a hack, but if no positional arguments are specified, and 'help' is, then
     * we don't want to blow up, so work around this.
     */
    if (positional.isEmpty() && named.containsKey(OptionsImpl.HELP.getName())) {
        positional.add("ignoreMe.class");
    }
    T res = getOptSinkFactory.create(named);
    return Pair.make(positional, res);
}
 
Example 7
Source File: LambdaCleaner.java    From cfr with MIT License 5 votes vote down vote up
@Override
public Expression rewriteExpression(Expression expression, SSAIdentifiers ssaIdentifiers, StatementContainer statementContainer, ExpressionRewriterFlags flags) {
    if (expression instanceof LambdaExpression) {
        LambdaExpression lambda = (LambdaExpression)expression;
        Expression result = lambda.getResult();
        if (result instanceof StructuredStatementExpression) {
            StructuredStatementExpression structuredStatementExpression = (StructuredStatementExpression)result;
            StructuredStatement content = structuredStatementExpression.getContent();
            if (content instanceof Block) {
                Block block = (Block)content;
                Pair<Boolean, Op04StructuredStatement> singleStatement = block.getOneStatementIfPresent();
                if (singleStatement.getSecond() != null) {
                    StructuredStatement statement = singleStatement.getSecond().getStatement();
                    if (statement instanceof StructuredReturn) {
                        expression = rebuildLambda(lambda, ((StructuredReturn)statement).getValue());
                    } else if (statement instanceof StructuredExpressionStatement) {
                        expression = rebuildLambda(lambda, ((StructuredExpressionStatement) statement).getExpression());
                    }
                } else {
                    if (singleStatement.getFirst()) {
                        Expression empty = new StructuredStatementExpression(expression.getInferredJavaType(), new Block(new LinkedList<Op04StructuredStatement>(), true));
                        expression = rebuildLambda(lambda, empty);
                    }
                }
            }
        }
    }
    return expression.applyExpressionRewriter(this, ssaIdentifiers, statementContainer, flags);
}
 
Example 8
Source File: Op02WithProcessedDataAndRefs.java    From cfr with MIT License 5 votes vote down vote up
private void collectLocallyMutatedVariables(SSAIdentifierFactory<Slot, StackType> ssaIdentifierFactory) {
    Pair<JavaTypeInstance, Integer> storage = getStorageType();
    if (storage != null) {
        ssaIdentifiers = new SSAIdentifiers<Slot>(new Slot(storage.getFirst(), storage.getSecond()), ssaIdentifierFactory);
        return;
    }

    ssaIdentifiers = new SSAIdentifiers<Slot>();
}
 
Example 9
Source File: ConstantPoolUtils.java    From cfr with MIT License 5 votes vote down vote up
public static ClassSignature parseClassSignature(ConstantPoolEntryUTF8 signature, ConstantPool cp) {
    final String sig = signature.getValue();
    int curridx = 0;

    /*
     * Optional formal type parameters
     */
    Pair<Integer, List<FormalTypeParameter>> formalTypeParametersRes = parseFormalTypeParameters(sig, cp, curridx);
    curridx = formalTypeParametersRes.getFirst();
    List<FormalTypeParameter> formalTypeParameters = formalTypeParametersRes.getSecond();

    /*
     * Superclass signature.
     */
    String superClassSignatureTok = getNextTypeTok(sig, curridx);
    curridx += superClassSignatureTok.length();
    JavaTypeInstance superClassSignature = decodeTypeTok(superClassSignatureTok, cp);

    List<JavaTypeInstance> interfaceClassSignatures = ListFactory.newList();
    while (curridx < sig.length()) {
        String interfaceSignatureTok = getNextTypeTok(sig, curridx);
        curridx += interfaceSignatureTok.length();
        interfaceClassSignatures.add(decodeTypeTok(interfaceSignatureTok, cp));
    }

    return new ClassSignature(formalTypeParameters, superClassSignature, interfaceClassSignatures);
}
 
Example 10
Source File: CFRDecompiler.java    From java-disassembler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String decompileClassNode(FileContainer container, ClassNode cn) {
    try {
        byte[] bytes = JDA.getClassBytes(container, cn);
        GetOptParser getOptParser = new GetOptParser();
        Pair processedArgs = getOptParser.parse(generateMainMethod(), OptionsImpl.getFactory());
        List files = (List)processedArgs.getFirst();
        Options options = (Options)processedArgs.getSecond();
        ClassFileSourceImpl classFileSource = new ClassFileSourceImpl(options);
        DCCommonState dcCommonState = new DCCommonState(options, classFileSource);
        return doClass(dcCommonState, bytes);
    } catch (Exception e) {
        return parseException(e);
    }
}
 
Example 11
Source File: ReturnRewriter.java    From cfr with MIT License 5 votes vote down vote up
private static void replaceReturningIf(Op03SimpleStatement ifStatement, boolean aggressive) {
    if (!(ifStatement.getStatement().getClass() == IfStatement.class)) return;
    IfStatement innerIf = (IfStatement) ifStatement.getStatement();
    Op03SimpleStatement tgt = ifStatement.getTargets().get(1);
    final Op03SimpleStatement origtgt = tgt;
    boolean requireJustOneSource = !aggressive;
    do {
        Op03SimpleStatement next = Misc.followNopGoto(tgt, requireJustOneSource, aggressive);
        if (next == tgt) break;
        tgt = next;
    } while (true);
    Statement tgtStatement = tgt.getStatement();
    if (tgtStatement instanceof ReturnStatement) {
        ifStatement.replaceStatement(new IfExitingStatement(innerIf.getCondition(), tgtStatement));
        Op03SimpleStatement origfall = ifStatement.getTargets().get(0);
        origfall.setFirstStatementInThisBlock(null);
        BlockIdentifier ifBlock = innerIf.getKnownIfBlock();
        Pair<Set<Op03SimpleStatement>, Set<Op03SimpleStatement>> blockReachableAndExits = Misc.GraphVisitorBlockReachable.getBlockReachableAndExits(origfall, ifBlock);
        for (Op03SimpleStatement stm : blockReachableAndExits.getFirst()) {
            stm.getBlockIdentifiers().remove(ifBlock);
        }
    } else {
        return;
    }
    origtgt.removeSource(ifStatement);
    ifStatement.removeTarget(origtgt);
}
 
Example 12
Source File: AttributeAnnotations.java    From cfr with MIT License 5 votes vote down vote up
AttributeAnnotations(ByteData raw, ConstantPool cp) {
    this.length = raw.getS4At(OFFSET_OF_ATTRIBUTE_LENGTH);
    int numAnnotations = raw.getU2At(OFFSET_OF_NUMBER_OF_ANNOTATIONS);
    long offset = OFFSET_OF_ANNOTATION_TABLE;
    for (int x = 0; x < numAnnotations; ++x) {
        Pair<Long, AnnotationTableEntry> ape = AnnotationHelpers.getAnnotation(raw, offset, cp);
        offset = ape.getFirst();
        annotationTableEntryList.add(ape.getSecond());
    }
}
 
Example 13
Source File: InternalDumperFactoryImpl.java    From cfr with MIT License 5 votes vote down vote up
public Dumper getNewTopLevelDumper(JavaTypeInstance classType, SummaryDumper summaryDumper, TypeUsageInformation typeUsageInformation, IllegalIdentifierDump illegalIdentifierDump) {
    Pair<String, Boolean> targetInfo = getPathAndClobber();

    if (targetInfo == null) return new StdIODumper(typeUsageInformation, options, illegalIdentifierDump, new MovableDumperContext());

    FileDumper res = new FileDumper(targetInfo.getFirst() + prefix, targetInfo.getSecond(), classType, summaryDumper, typeUsageInformation, options, illegalIdentifierDump);
    if (checkDupes) {
        if (!seen.add(res.getFileName().toLowerCase())) {
            seenCaseDupe = true;
        }
    }
    return res;
}
 
Example 14
Source File: DCCommonState.java    From cfr with MIT License 5 votes vote down vote up
public ClassFile loadClassFileAtPath(final String path) {
    try {
        Pair<byte[], String> content = classFileSource.getClassFileContent(path);
        ByteData data = new BaseByteData(content.getFirst());
        return new ClassFile(data, content.getSecond(), this);
    } catch (Exception e) {
        couldNotLoadClasses.add(path);
        throw new CannotLoadClassException(path, e);
    }
}
 
Example 15
Source File: AnnotationHelpers.java    From cfr with MIT License 4 votes vote down vote up
static Pair<Long, AnnotationTableTypeEntry> getTypeAnnotation(ByteData raw, long offset, ConstantPool cp) {
    short targetType = raw.getU1At(offset++);
    TypeAnnotationEntryValue typeAnnotationEntryValue = TypeAnnotationEntryValue.get(targetType);
    Pair<Long, TypeAnnotationTargetInfo> targetInfoPair = readTypeAnnotationTargetInfo(typeAnnotationEntryValue.getKind(), raw, offset);
    offset = targetInfoPair.getFirst();
    TypeAnnotationTargetInfo targetInfo = targetInfoPair.getSecond();

    short type_path_length = raw.getU1At(offset++);
    List<TypePathPart> pathData = ListFactory.newList();
    for (int x=0;x<type_path_length;++x) {
        short type_path_kind = raw.getU1At(offset++);
        short type_argument_index = raw.getU1At(offset++);
        switch (type_path_kind) {
            case 0:
                pathData.add(TypePathPartArray.INSTANCE);
                break;
            case 1:
                pathData.add(TypePathPartNested.INSTANCE);
                break;
            case 2:
                pathData.add(TypePathPartBound.INSTANCE);
                break;
            case 3:
                pathData.add(new TypePathPartParameterized(type_argument_index));
                break;
        }
    }
    TypePath path = new TypePath(pathData);

    int type_index = raw.getU2At(offset);
    offset+=2;
    ConstantPoolEntryUTF8 type_entry = cp.getUTF8Entry(type_index);
    JavaTypeInstance type = ConstantPoolUtils.decodeTypeTok(type_entry.getValue(), cp);


    int numElementPairs = raw.getU2At(offset);
    offset += 2;
    Map<String, ElementValue> elementValueMap = MapFactory.newOrderedMap();
    for (int x = 0; x < numElementPairs; ++x) {
        offset = getElementValuePair(raw, offset, cp, elementValueMap);
    }

    AnnotationTableTypeEntry res = new AnnotationTableTypeEntry<TypeAnnotationTargetInfo>(typeAnnotationEntryValue, targetInfo, path, type, elementValueMap);

    return new Pair<Long, AnnotationTableTypeEntry>(offset, res);
}
 
Example 16
Source File: ConstantPoolUtils.java    From cfr with MIT License 4 votes vote down vote up
private static JavaTypeInstance parseRefType(String tok, ConstantPool cp, boolean isTemplate) {
    int idxGen = tok.indexOf('<');
    int idxStart = 0;

    if (idxGen != -1) {
        tok = tok.replace(">.", ">$");
        List<JavaTypeInstance> genericTypes;
        StringBuilder already = new StringBuilder();
        while (true) {
            String pre = tok.substring(idxStart, idxGen);
            already.append(pre);
            String gen = tok.substring(idxGen + 1, tok.length() - 1);
            Pair<List<JavaTypeInstance>, Integer> genericTypePair = parseTypeList(gen, cp);
            genericTypes = genericTypePair.getFirst();
            idxStart = idxGen + genericTypePair.getSecond() + 1;
            if (idxStart < idxGen + gen.length()) {
                if (tok.charAt(idxStart) != '>') {
                    throw new IllegalStateException();
                }
                idxStart++;
                idxGen = tok.indexOf('<', idxStart);
                if (idxGen == -1) {
                    // At this point we're parsing an inner class.
                    // Append rest, treat as if no generics.
                    already.append(tok.substring(idxStart));
                    return cp.getClassCache().getRefClassFor(already.toString());
                }
                /*
                 * At this point we're discarding the outer generics info - that's not good....
                 */
            } else {
                break;
            }
        }
        JavaRefTypeInstance clazzType = cp.getClassCache().getRefClassFor(already.toString());
        return new JavaGenericRefTypeInstance(clazzType, genericTypes);
    } else if (isTemplate) {
        return new JavaGenericPlaceholderTypeInstance(tok, cp);
    } else {
        return cp.getClassCache().getRefClassFor(tok);
    }
}
 
Example 17
Source File: UnreachableStaticRewriter.java    From cfr with MIT License 4 votes vote down vote up
public static void rewrite(ClassFile classFile, TypeUsageCollectingDumper typeUsage) {
    // It is worth considering this, if we have made use of a class that also exists
    // as an inner class, AND as a 'synthetic full package' class.
    // (see https://github.com/leibnitz27/cfr/issues/102 )
    TypeUsageInformation info = typeUsage.getRealTypeUsageInformation();
    final JavaRefTypeInstance thisType = classFile.getRefClassType();
    if (thisType == null) return;

    Pair<List<JavaRefTypeInstance>, List<JavaRefTypeInstance>> split = Functional.partition(info.getUsedClassTypes(), new Predicate<JavaRefTypeInstance>() {
        @Override
        public boolean test(JavaRefTypeInstance in) {
            return in.getInnerClassHereInfo().isTransitiveInnerClassOf(thisType);
        }
    });
    List<JavaRefTypeInstance> inners = split.getFirst();
    /*
     * We are interested in inner classes where we clash with the fqn.
     * (What monster would do that? See test).
     */
    Map<String, JavaRefTypeInstance> potentialClashes = MapFactory.newMap();
    for (JavaRefTypeInstance inner : inners) {
        StringBuilder sb = new StringBuilder();
        inner.getInnerClassHereInfo().getFullInnerPath(sb);
        sb.append(inner.getRawShortName());
        String name = sb.toString();
        potentialClashes.put(name, inner);
    }

    List<JavaRefTypeInstance> others = split.getSecond();

    Map<JavaTypeInstance, Inaccessible> inaccessibles = MapFactory.newMap();
    for (JavaRefTypeInstance type : others) {
        JavaRefTypeInstance clashFqn = potentialClashes.get(type.getRawName());
        JavaRefTypeInstance clashShort = potentialClashes.get(type.getRawShortName());
        // Strictly speaking, if EITHER of these is true we have a problem,
        // that's a todo.
        if (clashFqn == null || clashShort == null) continue;
        // Ok, we can't import this guy.  We could import static if it's just used as a method,
        // but even then, only if we don't collide with any *LOCAL* methods.
        inaccessibles.put(type, new Inaccessible(type, clashShort, clashFqn));
    }

    if (inaccessibles.isEmpty()) return;

    Rewriter usr = new Rewriter(thisType, typeUsage, inaccessibles);
    ExpressionRewriterTransformer trans = new ExpressionRewriterTransformer(usr);

    for (Method method : classFile.getMethods()) {
        if (method.hasCodeAttribute()) {
            Op04StructuredStatement code = method.getAnalysis();
            trans.transform(code);
        }
    }
}
 
Example 18
Source File: ConstantPoolUtils.java    From cfr with MIT License 4 votes vote down vote up
public static MethodPrototype parseJavaMethodPrototype(DCCommonState state, ClassFile classFile, JavaTypeInstance classType, String name, boolean instanceMethod, Method.MethodConstructor constructorFlag, ConstantPoolEntryUTF8 prototype, ConstantPool cp, boolean varargs, boolean synthetic, VariableNamer variableNamer) {
    String proto = prototype.getValue();
    try {
        int curridx = 0;
        /*
         * Method is itself generic...
         */
        Pair<Integer, List<FormalTypeParameter>> formalTypeParametersRes = parseFormalTypeParameters(proto, cp, curridx);
        curridx = formalTypeParametersRes.getFirst();
        List<FormalTypeParameter> formalTypeParameters = formalTypeParametersRes.getSecond();
        Map<String, JavaTypeInstance> ftpMap;
        if (formalTypeParameters == null) {
            ftpMap = Collections.emptyMap();
        } else {
            ftpMap = MapFactory.newMap();
            for (FormalTypeParameter ftp : formalTypeParameters) {
                ftpMap.put(ftp.getName(), ftp.getBound());
            }
        }

        if (proto.charAt(curridx) != '(') throw new ConfusedCFRException("Prototype " + proto + " is invalid");
        curridx++;
        List<JavaTypeInstance> args = ListFactory.newList();
        // could use parseTypeList below.
        while (proto.charAt(curridx) != ')') {
            curridx = processTypeEntry(cp, proto, curridx, ftpMap, args);
        }
        curridx++;
        JavaTypeInstance resultType = RawJavaType.VOID;
        if (proto.charAt(curridx) == 'V') {
            curridx++;
        } else {
            String resTypeTok = getNextTypeTok(proto, curridx);
            curridx += resTypeTok.length();
            resultType = decodeTypeTok(resTypeTok, cp);
        }
        // And process any exceptions....
        List<JavaTypeInstance> exceptions = Collections.emptyList();
        if (curridx < proto.length()) {
            exceptions = ListFactory.newList();
            while (curridx < proto.length() && proto.charAt(curridx) == '^') {
                curridx++;
                curridx = processTypeEntry(cp, proto, curridx, ftpMap, exceptions);
            }
        }
        return new MethodPrototype(state, classFile, classType, name, instanceMethod, constructorFlag, formalTypeParameters, args, resultType, exceptions, varargs, variableNamer, synthetic);
    } catch (StringIndexOutOfBoundsException e) {
        throw new MalformedPrototypeException(proto, e);
    }
}
 
Example 19
Source File: AssertRewriter.java    From cfr with MIT License 4 votes vote down vote up
@Override
public void collectStatement(String name, StructuredStatement statement) {
    /* We expect this statement to be a block, containing our test, and starting a switch.
     * We don't know if the switch is the only statement in the block (exception has been rolled up)
     * or if there's ONE throw after it.
     *
     * If neither, bail!
     */
    if (!(statement instanceof BeginBlock)) return;

    Block block = ((BeginBlock)statement).getBlock();
    Pair<Boolean, Op04StructuredStatement> content = block.getOneStatementIfPresent();
    if (content.getFirst()) return;

    StructuredStatement ifStm = content.getSecond().getStatement();
    if (!(ifStm instanceof StructuredIf)) return;

    Op04StructuredStatement taken = ((StructuredIf) ifStm).getIfTaken();
    StructuredStatement takenBody = taken.getStatement();
    if (takenBody.getClass() != Block.class) return;
    Block takenBlock = (Block)takenBody;
    // This will either have a switch ONLY, or a switch and a throw.
    List<Op04StructuredStatement> switchAndThrow = takenBlock.getFilteredBlockStatements();
    if (switchAndThrow.isEmpty()) return;

    BlockIdentifier outerBlock = block.getBreakableBlockOrNull();

    StructuredStatement switchS = switchAndThrow.get(0).getStatement();
    if (!(switchS instanceof StructuredSwitch)) return;
    StructuredSwitch struSwi = (StructuredSwitch)switchS;
    BlockIdentifier switchBlock = struSwi.getBlockIdentifier();
    Op04StructuredStatement swBody = struSwi.getBody();
    if (!(swBody.getStatement() instanceof Block)) {
        return;
    }
    Block swBodyBlock = (Block)(swBody.getStatement());

    if (switchAndThrow.size() > 2) {
        // It's possible that this is a switch with no content, because we've extracted all the content
        // after the default.
        // if so, we could aggressively roll it up, and try that.
        // (test SwitchExpressionAssert1d)
        switchAndThrow = tryCombineSwitch(switchAndThrow, outerBlock, switchBlock, swBodyBlock);
        if (switchAndThrow.size() != 1) return;
        takenBlock.replaceBlockStatements(switchAndThrow);
    }
    StructuredStatement newAssert = null;


    switch (switchAndThrow.size()) {
        case 1:
            // switch, with throw rolled up into last case.
            newAssert = processSwitchEmbeddedThrow(ifStm, outerBlock, swBodyBlock, swBody, struSwi);
            break;
        case 2:
            // switch, followed by throw.
            // In this version, if it ends up leaving the if, it's true.
            // if it ends up leaving the switch (so into the throw), it's false.
            newAssert = processSwitchAndThrow(ifStm, outerBlock, switchBlock, swBodyBlock, struSwi, switchAndThrow.get(1));
            break;
        default:
            // switch, with logic dropping off the last case.
            break;
    }
    if (newAssert != null) {
        content.getSecond().replaceStatement(newAssert);
    }
}
 
Example 20
Source File: InternalDumperFactoryImpl.java    From cfr with MIT License 3 votes vote down vote up
public SummaryDumper getSummaryDumper() {
    Pair<String, Boolean> targetInfo = getPathAndClobber();

    if (targetInfo == null) return new NopSummaryDumper();

    return new FileSummaryDumper(targetInfo.getFirst(), options, new AdditionalComments());
}