Java Code Examples for com.sun.source.tree.CaseTree#getExpression()

The following examples show how to use com.sun.source.tree.CaseTree#getExpression() . 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 visitCase(CaseTree node, Void unused) {
    sync(node);
    markForPartialFormat();
    builder.forcedBreak();
    if (node.getExpression() == null) {
        token("default", plusTwo);
        token(":");
    } else {
        token("case", plusTwo);
        builder.space();
        scan(node.getExpression(), null);
        token(":");
    }
    builder.open(plusTwo);
    try {
        // don't partially format within case groups
        inExpression.addLast(true);
        visitStatements(node.getStatements());
    } finally {
        inExpression.removeLast();
    }
    builder.close();
    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 visitCase(CaseTree node, Void unused) {
    sync(node);
    markForPartialFormat();
    builder.forcedBreak();
    if (node.getExpression() == null) {
        token("default", plusTwo);
        token(":");
    } else {
        token("case", plusTwo);
        builder.space();
        scan(node.getExpression(), null);
        token(":");
    }
    builder.open(plusTwo);
    try {
        // don't partially format within case groups
        inExpression.addLast(true);
        visitStatements(node.getStatements());
    } finally {
        inExpression.removeLast();
    }
    builder.close();
    return null;
}
 
Example 3
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitCase(CaseTree node, Void unused) {
  sync(node);
  markForPartialFormat();
  builder.forcedBreak();
  if (node.getExpression() == null) {
    token("default", plusTwo);
    token(":");
  } else {
    token("case", plusTwo);
    builder.space();
    scan(node.getExpression(), null);
    token(":");
  }
  builder.open(plusTwo);
  visitStatements(node.getStatements());
  builder.close();
  return null;
}
 
Example 4
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 5
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 6
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 7
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 8
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertCase(CaseTree node, TreePath parent) {
  // Case statements are converted in convertSwitch().
  SwitchCase newNode = new SwitchCase();
  ExpressionTree expressionTree = node.getExpression();
  if (expressionTree != null) {
    newNode.setExpression((Expression) convert(expressionTree, getTreePath(parent, node)));
  } else {
    newNode.setIsDefault(true);
  }
  return newNode;
}
 
Example 9
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 10
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 11
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 12
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 13
Source File: DependencyCollector.java    From netbeans with Apache License 2.0 3 votes vote down vote up
/**Method
 * Method invocation adds a dependency on the method's declaring class
@Override
public Object visitMethodInvocation(MethodInvocationTree node, Object p) {
// possibly redundant, member select could handle the same
Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getMethodSelect()));
if (e.getKind() == ElementKind.METHOD) {
Element encl = e.getEnclosingElement();
if (encl.getKind() == ElementKind.CLASS || encl.getKind() == ElementKind.INTERFACE || encl.getKind() == ElementKind.ENUM) {
TypeElement te = (TypeElement) encl;
addDependency(te.asType());
}
}
return super.visitMethodInvocation(node, p);
}
 */
@Override
public Object visitCase(CaseTree node, Object p) {
    if (node.getExpression() != null && node.getExpression().getKind() == Tree.Kind.IDENTIFIER) {
        Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getExpression()));
        
        addDependency(node.getExpression());
    }
    return super.visitCase(node, p); //To change body of generated methods, choose Tools | Templates.
}