Java Code Examples for com.sun.source.tree.SwitchTree#getCases()

The following examples show how to use com.sun.source.tree.SwitchTree#getCases() . 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: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitSwitch(SwitchTree node, Void unused) {
    sync(node);
    token("switch");
    builder.space();
    token("(");
    scan(skipParen(node.getExpression()), null);
    token(")");
    builder.space();
    tokenBreakTrailingComment("{", plusTwo);
    builder.blankLineWanted(BlankLineWanted.NO);
    builder.open(plusTwo);
    boolean first = true;
    for (CaseTree caseTree : node.getCases()) {
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.PRESERVE);
        }
        scan(caseTree, null);
        first = false;
    }
    builder.close();
    builder.forcedBreak();
    builder.blankLineWanted(BlankLineWanted.NO);
    token("}", plusFour);
    return null;
}
 
Example 2
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Void visitSwitch(SwitchTree node, Void unused) {
    sync(node);
    token("switch");
    builder.space();
    token("(");
    scan(skipParen(node.getExpression()), null);
    token(")");
    builder.space();
    tokenBreakTrailingComment("{", plusTwo);
    builder.blankLineWanted(BlankLineWanted.NO);
    builder.open(plusTwo);
    boolean first = true;
    for (CaseTree caseTree : node.getCases()) {
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.PRESERVE);
        }
        scan(caseTree, null);
        first = false;
    }
    builder.close();
    builder.forcedBreak();
    builder.blankLineWanted(BlankLineWanted.NO);
    token("}", plusFour);
    return null;
}
 
Example 3
Source File: ConvertSwitchToRuleSwitch.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Tree.Kind.SWITCH)
@Messages({"ERR_ConvertSwitchToRuleSwitch=Convert switch to rule switch", "ERR_ConvertSwitchToSwitchExpression=Convert to switch expression"})
public static ErrorDescription switch2RuleSwitch(HintContext ctx) {
    if (Utilities.isJDKVersionLower(SWITCH_RULE_PREVIEW_JDK_VERSION) && !CompilerOptionsQuery.getOptions(ctx.getInfo().getFileObject()).getArguments().contains("--enable-preview"))
        return null;
    SwitchTree st = (SwitchTree) ctx.getPath().getLeaf();
    boolean completesNormally = false;
    boolean wasDefault = false;
    boolean wasEmpty = false;
    for (CaseTree ct : st.getCases()) {
        if (ct.getStatements() == null) //TODO: test
            return null;
        if (completesNormally) {
            if (!wasEmpty) //fall-through from a non-empty case
                return null;
            if (wasDefault) //fall-through from default to a case
                return null;
            if (!wasDefault && ct.getExpression() == null) //fall-through from a case to default
                return null;
        }
        completesNormally = Utilities.completesNormally(ctx.getInfo(), new TreePath(ctx.getPath(), ct));
        wasDefault = ct.getExpression() == null;
        wasEmpty = ct.getStatements().isEmpty();
    }
    if (wasDefault && Utilities.isCompatibleWithSwitchExpression(st)) {
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ConvertSwitchToSwitchExpression(), new FixImpl1(ctx.getInfo(), ctx.getPath()).toEditorFix());
    } else {
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ConvertSwitchToRuleSwitch(), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix());
    }
}
 
Example 4
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean visitSwitch(SwitchTree node, Void p) {
    boolean lastCaseExit = false;
    boolean defaultSeen = false;
    Set<Element> enumValues = null;
    
    if (node.getExpression() != null) {
        TypeMirror exprType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
        if (isValidType(exprType) && exprType.getKind() == TypeKind.DECLARED) {
            Element el = ((DeclaredType)exprType).asElement();
            enumValues = new HashSet<>();
            for (Element f : el.getEnclosedElements()) {
                if (f.getKind() == ElementKind.ENUM_CONSTANT) {
                    enumValues.add(f);
                }
            }
        }
    }
    for (CaseTree ct : node.getCases()) {
        Boolean res = scan(ct, null);
        if (res == Boolean.FALSE) {
            return res;
        }
        lastCaseExit = res == Boolean.TRUE;
        if (ct.getExpression() == null) {
            defaultSeen = true;
        } else if (enumValues != null ) {
            TreePath casePath = new TreePath(getCurrentPath(), ct);
            Element v = info.getTrees().getElement(new TreePath(
                    casePath, ct.getExpression()));
            if (v != null) {
                enumValues.remove(v);
            }
        }
    }
    if (enumValues != null && enumValues.isEmpty()) {
        defaultSeen = true;
    }
    return lastCaseExit == Boolean.TRUE && defaultSeen;
}
 
Example 5
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends TypeMirror> visitSwitch(SwitchTree node, Object p) {
    if (theExpression == null) {
        initExpression(node.getExpression());
    }
    for (CaseTree cs : node.getCases()) {
        if (cs.getExpression() != null) {
            TreePath casePath = new TreePath(getCurrentPath(), cs);
            TypeMirror caseType = info.getTrees().getTypeMirror(new TreePath(casePath, cs.getExpression()));
            return Collections.singletonList(caseType);
        }
    }
    // cannot determine
    return null;
}
 
Example 6
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private boolean testBlock(StringWriter writer, SourcePositions sp, String text, CompilationUnitTree cut, BlockTree blockTree) {
    boolean success = true;
    for (StatementTree st : blockTree.getStatements()) {
        if (isLegal(st)) {
            success &= testStatement(writer, sp, text, cut, st);
        }
        if (st instanceof IfTree) {
            IfTree ifTree = (IfTree) st;
            success &= testBranch(writer, sp, text, cut, ifTree.getThenStatement());
            success &= testBranch(writer, sp, text, cut, ifTree.getElseStatement());
        } else if (st instanceof WhileLoopTree) {
            WhileLoopTree whileLoopTree = (WhileLoopTree) st;
            success &= testBranch(writer, sp, text, cut, whileLoopTree.getStatement());
        } else if (st instanceof DoWhileLoopTree) {
            DoWhileLoopTree doWhileLoopTree = (DoWhileLoopTree) st;
            success &= testBranch(writer, sp, text, cut, doWhileLoopTree.getStatement());
        } else if (st instanceof ForLoopTree) {
            ForLoopTree forLoopTree = (ForLoopTree) st;
            success &= testBranch(writer, sp, text, cut, forLoopTree.getStatement());
        } else if (st instanceof LabeledStatementTree) {
            LabeledStatementTree labelTree = (LabeledStatementTree) st;
            success &= testBranch(writer, sp, text, cut, labelTree.getStatement());
        } else if (st instanceof SwitchTree) {
            SwitchTree switchTree = (SwitchTree) st;
            for (CaseTree caseTree : switchTree.getCases()) {
                for (StatementTree statementTree : caseTree.getStatements()) {
                    success &= testBranch(writer, sp, text, cut, statementTree);
                }
            }
        }
    }
    return success;
}
 
Example 7
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertSwitch(SwitchTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  SwitchStatement newNode =
      new SwitchStatement().setExpression(convertWithoutParens(node.getExpression(), path));
  for (CaseTree switchCase : node.getCases()) {
    newNode.addStatement((SwitchCase) convert(switchCase, path));
    TreePath switchCasePath = getTreePath(path, switchCase);
    for (StatementTree s : switchCase.getStatements()) {
      newNode.addStatement((Statement) convert(s, switchCasePath));
    }
  }
  return newNode;
}
 
Example 8
Source File: InfiniteRecursion.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public State visitSwitch(SwitchTree node, Void p) {
    registerBreakTarget(node);
    State s;
    if (returnIfRecurse(s= scan(node.getExpression(), p))) {
        return s;
    }
    // look for the default case, but cannot return immediately as some return / break inside could
    // slip unnoticed.
    boolean defaultFound = false;
    
    Set<Tree> saveBreaks = breakContinueJumps;
    Set<Tree> collectBreaks = Collections.emptySet();
    
    State lastState = State.NO;
    
    boolean saveDefinite = definitePath;
    definitePath = false;
    for (CaseTree ct : node.getCases()) {
        if (ct.getExpression() == null) {
            defaultFound = true;
        }
        knownResult = null;
        breakContinueJumps = new HashSet<Tree>();
    
        s = scan(ct, p);
        if (s == State.RETURN) {
            // possible return reachable from the branch, bail out
            definitePath = saveDefinite;
            return knownResult = s;
            // the branch just jumped off
        } else {
            // the branch recurses. But if the branch also contains breaks out of the switch, or out of outer
            // cycles, those breaks must have been found before the recursion instruction. Any jumps to
            // nested statements should have been cleared by scan().
            boolean self = breakContinueJumps.remove(node);
            if (self || !breakContinueJumps.isEmpty()) {
                // at least one way out
                saveBreaks.addAll(breakContinueJumps);
                saveBreaks.addAll(collectBreaks);
                breakContinueJumps = saveBreaks;
                definitePath = saveDefinite;
                recursionPoints.clear();
                return State.NO;
            }
            lastState = s;
        }
    }
    definitePath = saveDefinite;
    if (defaultFound) {
        return lastState;
    } else {
        recursionPoints.clear();
        return State.NO;
    }
}
 
Example 9
Source File: Flow.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public Boolean visitSwitch(SwitchTree node, ConstructorData p) {
    scan(node.getExpression(), null);

    Map< Element, State> origVariable2State = new HashMap< Element, State>(variable2State);

    variable2State = new HashMap< Element, State>();

    boolean exhaustive = false;

    for (CaseTree ct : node.getCases()) {
        variable2State = mergeOr(variable2State, origVariable2State);

        if (ct.getExpression() == null) {
            exhaustive = true;
        }

        scan(ct, null);
    }

    if (!exhaustive) {
        variable2State = mergeOr(variable2State, origVariable2State);
    }
    
    return null;
}
 
Example 10
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static boolean isCompatibleWithSwitchExpression(SwitchTree st) {
    boolean firstCase = true;
    Name leftTreeName = null;
    int caseCount = 0;
    List<? extends CaseTree> cases = st.getCases();

    for (CaseTree ct : cases) {
        caseCount++;
        List<StatementTree> statements = new ArrayList<>(ct.getStatements());
        switch (statements.size()) {
            case 0:
                break;
            case 1:
                if (firstCase && leftTreeName == null && statements.get(0).getKind() == Tree.Kind.RETURN) {
                    break;
                } else if (caseCount == cases.size() && statements.get(0).getKind() == Tree.Kind.EXPRESSION_STATEMENT) {
                    if (firstCase) {
                        leftTreeName = getLeftTreeName(statements.get(0));
                        if (leftTreeName == null) {
                            return false;
                        }
                        break;
                    } else {
                        if (leftTreeName != null && leftTreeName.contentEquals(getLeftTreeName(statements.get(0)))) {
                            break;
                        } else {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            case 2:
                if (statements.get(0).getKind() == Tree.Kind.EXPRESSION_STATEMENT && statements.get(1).getKind() == Tree.Kind.BREAK) {
                    if (firstCase) {
                        leftTreeName = getLeftTreeName(statements.get(0));
                        if (leftTreeName == null) {
                            return false;
                        }
                        firstCase = false;
                    }
                    if (leftTreeName != null && leftTreeName.contentEquals(getLeftTreeName(statements.get(0)))) {
                        break;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            default:
                return false;
        }
    }
    return true;
}
 
Example 11
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void performRewrite(final TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    final TreeMaker make = wc.getTreeMaker();
    final TreePath tp = ctx.getPath();
    SwitchTree st = (SwitchTree) tp.getLeaf();
    int insertIndex = 0;
    boolean hadDefault = false;

    for (CaseTree ct : st.getCases()) {
        if (ct.getExpression() == null) {
            hadDefault = true;
            break;
        }
        insertIndex++;
    }

    for (String name : names) {
        st = make.insertSwitchCase(st, insertIndex++, make.Case(make.Identifier(name), Collections.singletonList(make.Break(null))));
    }

    if (!hadDefault && defaultTemplate != null) {
        StatementTree stmt = ctx.getWorkingCopy().getTreeUtilities().parseStatement(defaultTemplate, new SourcePositions[1]);
        Scope s = ctx.getWorkingCopy().getTrees().getScope(tp);
        ctx.getWorkingCopy().getTreeUtilities().attributeTree(stmt, s);
        st = GeneratorUtilities.get(ctx.getWorkingCopy()).importFQNs(make.addSwitchCase(st, make.Case(null, Collections.singletonList(stmt))));
        new ErrorAwareTreePathScanner<Void, Void>() {
            @Override public Void visitIdentifier(IdentifierTree node, Void p) {
                if (node.getName().contentEquals("$expression")) {
                    ExpressionTree expression = ((SwitchTree) tp.getLeaf()).getExpression();
                    if (expression.getKind() == Tree.Kind.PARENTHESIZED) {
                        expression = ((ParenthesizedTree) expression).getExpression();
                    }
                    if (JavaFixUtilities.requiresParenthesis(expression, node, getCurrentPath().getParentPath().getLeaf())) {
                        expression = make.Parenthesized(expression);
                    }
                    ctx.getWorkingCopy().rewrite(node, expression);
                }
                return super.visitIdentifier(node, p);
            }
        }.scan(new TreePath(ctx.getPath(), st), null);
    }

    wc.rewrite(tp.getLeaf(), st);
}