com.sun.source.tree.SwitchTree Java Examples

The following examples show how to use com.sun.source.tree.SwitchTree. 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: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }

  ExpressionTree switchExpression = tree.getExpression();
  if (switchExpression instanceof ParenthesizedTree) {
    switchExpression = ((ParenthesizedTree) switchExpression).getExpression();
  }

  if (mayBeNullExpr(state, switchExpression)) {
    final String message =
        "switch expression " + state.getSourceForNode(switchExpression) + " is @Nullable";
    ErrorMessage errorMessage =
        new ErrorMessage(MessageTypes.SWITCH_EXPRESSION_NULLABLE, message);

    return errorBuilder.createErrorDescription(
        errorMessage, switchExpression, buildDescription(switchExpression), state);
  }

  return Description.NO_MATCH;
}
 
Example #4
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitSwitch(SwitchTree tree, Void p) {
    SwitchTree n = make.Switch(tree.getExpression(), tree.getCases());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #5
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitSwitch(SwitchTree expected, Tree actual) {
  Optional<SwitchTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getExpression(), other.get().getExpression());
  parallelScan(expected.getCases(), other.get().getCases());
  return null;
}
 
Example #6
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 #7
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 #8
Source File: ExpressionScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Tree> visitSwitch(SwitchTree node, ExpressionScanner.ExpressionsInfo p) {
    List<Tree> result = null;
    if (acceptsTree(node)) {
        result = scan(node.getExpression(), p);
    }
    return reduce(result, scan(node.getCases(), p));
}
 
Example #9
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 #10
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 #11
Source File: DifferentCaseKindsFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    if (Utilities.isJDKVersionLower(SWITCH_RULE_PREVIEW_JDK_VERSION) && !CompilerOptionsQuery.getOptions(info.getFileObject()).getArguments().contains("--enable-preview")) {
        return null;
    }
    TreePath parentPath = treePath.getParentPath();
    List<? extends CaseTree> caseTrees = null;
    boolean flag = false;
    if(parentPath.getLeaf().getKind().toString().equals(TreeShims.SWITCH_EXPRESSION)){
        caseTrees = TreeShims.getCases(parentPath.getLeaf());            
    } else {
        flag = true;
        caseTrees = ((SwitchTree) treePath.getParentPath().getLeaf()).getCases();
    }
        boolean completesNormally = false;
        boolean wasDefault = false;
        boolean wasEmpty = false;
        for (CaseTree ct : caseTrees) {
            if (ct.getStatements() == null && TreeShims.getBody(ct) == null) {
                return null;
            } else if (flag && ct.getStatements() != 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(info, new TreePath(treePath.getParentPath(), ct));
                wasDefault = ct.getExpression() == null;
                wasEmpty = ct.getStatements().isEmpty();
            }
        }      

    return Collections.<Fix>singletonList(new DifferentCaseKindsFix.FixImpl(info, treePath).toEditorFix());
}
 
Example #12
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Boolean visitSwitch(SwitchTree node, TreePath p) {
    if (p == null) {
        super.visitSwitch(node, p);
        return false;
    }

    SwitchTree st = (SwitchTree) p.getLeaf();

    if (!scan(node.getExpression(), st.getExpression(), p)) {
        return false;
    }

    return checkLists(node.getCases(), st.getCases(), p);
}
 
Example #13
Source File: VarCompoundDeclarationTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Fix compound variable declaration in switch-case statement.
 * array type.
 * @throws IOException
 */
private void rewriteCaseStatement() throws IOException {

    JavaSource js = getJavaSource();
    assertNotNull(js);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            SwitchTree st = (SwitchTree) method.getBody().getStatements().get(1);
            
            CaseTree ct = st.getCases().get(0);
            List<? extends StatementTree> statements = ct.getStatements();
                    
            for (int current = 0; current < statements.size(); current++) {
                StatementTree t = (StatementTree) statements.get(current);
                if (t instanceof VariableTree) {
                    VariableTree oldVariableTree = (VariableTree) t;
                    VariableTree newVariableTree = make.Variable(
                            oldVariableTree.getModifiers(),
                            oldVariableTree.getName(),
                            make.Type("var"), // NOI18N
                            oldVariableTree.getInitializer()
                    );
                    workingCopy.rewrite(oldVariableTree, newVariableTree);

                }

            }
        }
    };

    js.runModificationTask(task).commit();
}
 
Example #14
Source File: TreeNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitSwitch(SwitchTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();
    
    addCorrespondingType(below);
    addCorrespondingComments(below);
    super.visitSwitch(tree, below);
    
    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
 
Example #15
Source File: DepthVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object visitSwitch(SwitchTree node, Object p) {
    depth++;
    Object o = super.visitSwitch(node, p); 
    depth--;
    return o;
}
 
Example #16
Source File: JavaFixUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Number visitSwitch(SwitchTree node, Void p) {
    List<? extends CaseTree> cases = (List<? extends CaseTree>) resolveMultiParameters(node.getCases());
    SwitchTree nue = make.Switch(node.getExpression(), cases);

    rewrite(node, nue);
    return super.visitSwitch(node, p);
}
 
Example #17
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 #18
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.suggestions.Tiny.fillSwitch", description = "#DESC_org.netbeans.modules.java.hints.suggestions.Tiny.fillSwitch", category="suggestions", hintKind=Kind.ACTION, severity=Severity.HINT, customizerProvider=CustomizerProviderImpl.class)
@TriggerPattern(value="switch ($expression) { case $cases$; }",
                constraints=@ConstraintVariableType(variable="$expression", type="java.lang.Enum"))
public static ErrorDescription fillSwitch(HintContext ctx) {
    int caret = ctx.getCaretLocation();
    SwitchTree st = (SwitchTree) ctx.getPath().getLeaf();
    int switchStart = (int) ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getPath().getCompilationUnit(), st);
    LineMap lm = ctx.getPath().getCompilationUnit().getLineMap();

    if (lm.getLineNumber(caret) != lm.getLineNumber(switchStart)) return null;
    
    TreePath expression = ctx.getVariables().get("$expression");
    Element possibleEnumElement = ctx.getInfo().getTypes().asElement(ctx.getInfo().getTrees().getTypeMirror(expression));
    
    if (possibleEnumElement == null || !possibleEnumElement.getKind().isClass()) return null;
    
    TypeElement enumType = (TypeElement) possibleEnumElement;
    List<VariableElement> enumConstants = new ArrayList<VariableElement>(enumType.getEnclosedElements().size());
    for (Element e : enumType.getEnclosedElements()) {
        if (e.getKind() == ElementKind.ENUM_CONSTANT) {
            enumConstants.add((VariableElement) e);
        }
    }
    boolean hasDefault = false;
    for (TreePath casePath : ctx.getMultiVariables().get("$cases$")) {
        CaseTree ct = (CaseTree) casePath.getLeaf();

        if (ct.getExpression() == null) {
            hasDefault = true;
        } else {
            enumConstants.remove(ctx.getInfo().getTrees().getElement(new TreePath(casePath, ct.getExpression())));
        }
    }
    boolean generateDefault = ctx.getPreferences().getBoolean(KEY_DEFAULT_ENABLED, DEF_DEFAULT_ENABLED);
    if (enumConstants.isEmpty() && (hasDefault || !generateDefault)) return null;
    List<String> names = new ArrayList<String>(enumConstants.size());
    for (VariableElement constant : enumConstants) {
        names.add(constant.getSimpleName().toString());
    }
    String defaultTemplate = generateDefault ? ctx.getPreferences().get(KEY_DEFAULT_SNIPPET, DEF_DEFAULT_SNIPPET) : null;
    String errMessage = enumConstants.isEmpty() ? "ERR_Tiny.fillSwitchDefault" : !hasDefault && generateDefault ? "ERR_Tiny.fillSwitchCasesAndDefault" : "ERR_Tiny.fillSwitchCases";
    String fixMessage = enumConstants.isEmpty() ? "FIX_Tiny.fillSwitchDefault" : !hasDefault && generateDefault ? "FIX_Tiny.fillSwitchCasesAndDefault" : "FIX_Tiny.fillSwitchCases";
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), NbBundle.getMessage(Tiny.class, errMessage), new AddSwitchCasesImpl(ctx.getInfo(), ctx.getPath(), fixMessage, names, defaultTemplate).toEditorFix());
}
 
Example #19
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
@Override
public Void visitSwitch(SwitchTree node, Void unused) {
  sync(node);
  visitSwitch(node.getExpression(), node.getCases());
  return null;
}
 
Example #20
Source File: SwitchExpressionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Rewrite Switch Expression cases.
 *
 * @throws IOException
 */
private void rewriteSwitchExpression() throws IOException {

    JavaSource js = getJavaSource();
    assertNotNull(js);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            List<CaseTree> newCases = new ArrayList<>();
            VariableTree switcExpression = (VariableTree) ((BlockTree) method.getBody()).getStatements().get(0);
            Tree switchBlock = switcExpression.getInitializer();
            List<? extends CaseTree> cases;
            List<ExpressionTree> patterns = new ArrayList<>();
            boolean switchExpressionFlag = switchBlock.getKind().toString().equals(TreeShims.SWITCH_EXPRESSION);
            if (switchExpressionFlag) {
                cases = TreeShims.getCases(switchBlock);
            } else {
                cases = ((SwitchTree) switchBlock).getCases();
            }
            for (Iterator<? extends CaseTree> it = cases.iterator(); it.hasNext();) {
                CaseTree ct = it.next();
                patterns.addAll(TreeShims.getExpressions(ct));
                List<StatementTree> statements;
                if (ct.getStatements() == null) {
                    statements = new ArrayList<>(((JCTree.JCCase) ct).stats);
                } else {
                    statements = new ArrayList<>(ct.getStatements());
                }
                if (statements.isEmpty()) {
                    if (it.hasNext()) {
                        continue;
                    }
                }
                Set<Element> seenVariables = new HashSet<>();
                int idx = 0;
                for (StatementTree statement : new ArrayList<>(statements)) {
                    Tree body = make.Block(statements, false);
                    if (statements.size() == 1) {
                        if (statements.get(0).getKind() == Tree.Kind.EXPRESSION_STATEMENT
                                || statements.get(0).getKind() == Tree.Kind.THROW
                                || statements.get(0).getKind() == Tree.Kind.BLOCK) {
                            body = statements.get(0);
                        }
                    }
                    newCases.add(make.Case(patterns, body));
                    patterns = new ArrayList<>();
                }
            }
            workingCopy.rewrite(switchBlock, make.SwitchExpression(TreeShims.getExpressions(switchBlock).get(0), newCases));
        }

    };

    js.runModificationTask(task).commit();
}
 
Example #21
Source File: SwitchTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddCase1() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    String test = "public class Test {\n" +
                  "    void m(int p) {\n" +
                  "        switch (p) {\n" +
                  "            case 0:\n" +
                  "                System.err.println(1);\n" +
                  "                break;\n" +
                  "            ca|se 2:\n" +
                  "                System.err.println(2);\n" +
                  "                break;\n" +
                  "        }\n" +
                  "    }\n" +
                  "}\n";
    String golden = "public class Test {\n" +
                    "    void m(int p) {\n" +
                    "        switch (p) {\n" +
                    "            case 0:\n" +
                    "                System.err.println(1);\n" +
                    "                break;\n" +
                    "            case 1:\n" +
                    "            case 2:\n" +
                    "            case 3:\n" +
                    "                System.err.println(2);\n" +
                    "                break;\n" +
                    "        }\n" +
                    "    }\n" +
                    "}\n";
    final int index = test.indexOf("|");
    assertTrue(index != -1);
    TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy copy) throws IOException {
            if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
                return;
            }
            TreeMaker make = copy.getTreeMaker();
            TreePath node = copy.getTreeUtilities().pathFor(index);
            assertTrue(node.getLeaf().getKind() == Kind.CASE);
            SwitchTree st = (SwitchTree) node.getParentPath().getLeaf();
            List<CaseTree> newCases = new LinkedList<CaseTree>();
            newCases.add(st.getCases().get(0));
            newCases.add(make.Case(make.Literal(1), Collections.<StatementTree>emptyList()));
            newCases.add(make.Case(make.Literal(2), Collections.<StatementTree>emptyList()));
            newCases.add(make.Case(make.Literal(3), st.getCases().get(1).getStatements()));
            copy.rewrite(st, make.Switch(st.getExpression(), newCases));
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #22
Source File: LocalVarScanner.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean visitSwitch(SwitchTree node, Element p) {
    return null;
}
 
Example #23
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);
}
 
Example #24
Source File: NCLOCVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Object visitSwitch(SwitchTree node, Object p) {
    statements++;
    return super.visitSwitch(node, p);
}
 
Example #25
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 #26
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 #27
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 #28
Source File: ConvertSwitchToRuleSwitch.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void performRewrite(JavaFix.TransformationContext ctx) {
    TreePath tp = ctx.getPath();
    SwitchTree st = (SwitchTree) tp.getLeaf();
    Utilities.performRewriteRuleSwitch(ctx, tp, st, true);
}
 
Example #29
Source File: ConvertSwitchToRuleSwitch.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    TreePath tp = ctx.getPath();
    SwitchTree st = (SwitchTree) tp.getLeaf();
    Utilities.performRewriteRuleSwitch(ctx, tp, st, false);
}