Java Code Examples for javax.lang.model.element.ElementKind.LOCAL_VARIABLE

The following are Jave code examples for showing how to use LOCAL_VARIABLE of the javax.lang.model.element.ElementKind class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-netbeans   File: IntroduceConstantFix.java   Source Code and License Vote up 6 votes
static boolean checkConstantExpression(final CompilationInfo info, TreePath path) {
    InstanceRefFinder finder = new InstanceRefFinder(info, path) {
        @Override
        public Object visitIdentifier(IdentifierTree node, Object p) {
            Element el = info.getTrees().getElement(getCurrentPath());
            if (el == null || el.asType() == null || el.asType().getKind() == TypeKind.ERROR) {
                return null;
            }
            if (el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.PARAMETER) {
                throw new StopProcessing();
            } else if (el.getKind() == ElementKind.FIELD) {
                if (!el.getModifiers().contains(Modifier.FINAL)) {
                    throw new StopProcessing();
                }
            }
            return super.visitIdentifier(node, p);
        }
    };
    try {
        finder.process();
        return  !(finder.containsInstanceReferences() || finder.containsLocalReferences() || finder.containsReferencesToSuper());
    } catch (StopProcessing e) {
        return false;
    }
}
 
Example 2
Project: incubator-netbeans   File: AssignmentIssues.java   Source Code and License Vote up 6 votes
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToForLoopParam", description = "#DESC_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToForLoopParam", category = "assignment_issues", enabled = false, suppressWarnings = "AssignmentToForLoopParameter", options=Options.QUERY) //NOI18N
@TriggerPatterns({
    @TriggerPattern(value = "for ($paramType $param = $init; $expr; $update) $statement;"), //NOI18N
    @TriggerPattern(value = "for ($paramType $param : $expr) $statement;") //NOI18N
})
public static List<ErrorDescription> assignmentToForLoopParam(HintContext context) {
    final Trees trees = context.getInfo().getTrees();
    final TreePath paramPath = context.getVariables().get("$param"); //NOI18N
    final Element param = trees.getElement(paramPath);
    if (param == null || param.getKind() != ElementKind.LOCAL_VARIABLE) {
        return null;
    }
    final TreePath stat = context.getVariables().get("$statement"); //NOI18N
    final List<TreePath> paths = new LinkedList<TreePath>();
    new AssignmentFinder(trees, param).scan(stat, paths);
    final List<ErrorDescription> ret = new ArrayList<ErrorDescription>(paths.size());
    for (TreePath path : paths) {
        ret.add(ErrorDescriptionFactory.forTree(context, path, NbBundle.getMessage(AssignmentIssues.class, "MSG_AssignmentToForLoopParam", param.getSimpleName()))); //NOI18N
    }
    return ret;
}
 
Example 3
Project: incubator-netbeans   File: ResourceStringFoldProvider.java   Source Code and License Vote up 6 votes
@Override
public Void visitVariable(VariableTree node, Void p) {
    scan(node.getInitializer(), null);
    if (exprBundleName == null) {
        return null;
    }
    TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath());
    if (resourceBundleType == null || !info.getTypes().isAssignable(tm, resourceBundleType)) {
        return null;
    }
    Element dest = info.getTrees().getElement(getCurrentPath());
    if (dest != null && (dest.getKind() == ElementKind.LOCAL_VARIABLE || dest.getKind() == ElementKind.FIELD)) {
        variableBundles.put(dest, exprBundleName);
    }
    return null;
}
 
Example 4
Project: openjdk-jdk10   File: Symbol.java   Source Code and License Vote up 6 votes
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    long flags = flags();
    if ((flags & PARAMETER) != 0) {
        if (isExceptionParameter())
            return ElementKind.EXCEPTION_PARAMETER;
        else
            return ElementKind.PARAMETER;
    } else if ((flags & ENUM) != 0) {
        return ElementKind.ENUM_CONSTANT;
    } else if (owner.kind == TYP || owner.kind == ERR) {
        return ElementKind.FIELD;
    } else if (isResourceVariable()) {
        return ElementKind.RESOURCE_VARIABLE;
    } else {
        return ElementKind.LOCAL_VARIABLE;
    }
}
 
Example 5
Project: incubator-netbeans   File: RenameRefactoringUI.java   Source Code and License Vote up 5 votes
@Override
public CustomRefactoringPanel getPanel(ChangeListener parent) {
    if (panel == null) {
        String suffix = "";
        if(handle != null && handle.getKind() == Tree.Kind.LABELED_STATEMENT) {
            suffix = getString("LBL_Label");
        } else if (handle != null && handle.getElementHandle() !=null) {
            ElementKind kind = handle.getElementHandle().getKind();
            if (kind!=null && (kind.isClass() || kind.isInterface())) {
                suffix  = kind.isInterface() ? getString("LBL_Interface") : getString("LBL_Class");
            } else if (kind == ElementKind.METHOD) {
                suffix = getString("LBL_Method");
            } else if (kind == ElementKind.FIELD) {
                suffix = getString("LBL_Field");
            } else if (kind == ElementKind.LOCAL_VARIABLE) {
                suffix = getString("LBL_LocalVar");
            } else if (kind == ElementKind.PACKAGE || (handle == null && fromListener)) {
                suffix = pkgRename ? getString("LBL_Package") : getString("LBL_Folder");
            } else if (kind == ElementKind.PARAMETER) {
                suffix = getString("LBL_Parameter");
            }
        }
        suffix = suffix + " " + this.oldName; // NOI18N
        panel = new RenamePanel(handle, newName, parent, NbBundle.getMessage(RenamePanel.class, "LBL_Rename") + " " + suffix, !fromListener, fromListener && !byPassPakageRename);
    }
    return panel;
}
 
Example 6
Project: incubator-netbeans   File: PreconditionsChecker.java   Source Code and License Vote up 5 votes
private boolean isLocalVariable(IdentifierTree id, Trees trees) {
    Element el = trees.getElement(TreePath.getPath(treePath, id));
    if (el != null) {
        return el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.PARAMETER;
    }
    return false;
}
 
Example 7
Project: incubator-netbeans   File: ReplaceBufferByString.java   Source Code and License Vote up 5 votes
@TriggerPatterns({
    @TriggerPattern(value = "java.lang.StringBuffer $x = $expr;"),
    @TriggerPattern(value = "java.lang.StringBuilder $x = $expr;"),
})
public static ErrorDescription checkReplace(HintContext ctx) {
    CompilationInfo ci = ctx.getInfo();
    TreePath vp = ctx.getVariables().get("$x"); // NOI18N
    TreePath initP = ctx.getVariables().get("$expr"); // NOI18N
    Element el = ci.getTrees().getElement(vp);
    if (el == null || el.getKind() != ElementKind.LOCAL_VARIABLE) {
        return null;
    }
    
    StringBufferUsageScanner scanner = new StringBufferUsageScanner(ci, ((VariableElement)el));
    TreePath declRoot = ctx.getPath().getParentPath();
    scanner.scan(declRoot, null);
    if (scanner.isIncompatible()) {
        return null;
    }
    NewAppendScanner newScan = new NewAppendScanner(ci);
    if (newScan.scan(initP, null) != Boolean.TRUE || !newScan.hasContents) {
        return null;
    }
    
    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), Bundle.TEXT_ReplaceStringBufferByString(), 
            new RewriteToStringFix(
                TreePathHandle.create(vp, ci),
                TreePathHandle.create(declRoot, ci)
            ).toEditorFix());
}
 
Example 8
Project: incubator-netbeans   File: Utilities.java   Source Code and License Vote up 5 votes
public static boolean isConstantString(CompilationInfo info, TreePath tp, boolean acceptsChars) {
    if (tp.getLeaf().getKind() == Kind.STRING_LITERAL) return true;
    if (acceptsChars && tp.getLeaf().getKind() == Kind.CHAR_LITERAL) return true;

    Element el = info.getTrees().getElement(tp);

    if (el != null && (el.getKind() == ElementKind.FIELD || el.getKind() == ElementKind.LOCAL_VARIABLE)
            && ((VariableElement) el).getConstantValue() instanceof String) {
        return true;
    }

    if (tp.getLeaf().getKind() != Kind.PLUS) {
        return false;
    }

    List<List<TreePath>> sorted = splitStringConcatenationToElements(info, tp);

    if (sorted.size() != 1) {
        return false;
    }

    List<TreePath> part = sorted.get(0);

    for (TreePath c : part) {
        if (isConstantString(info, c, acceptsChars))
            return true;
    }

    return false;
}
 
Example 9
Project: incubator-netbeans   File: ResourceStringFoldProvider.java   Source Code and License Vote up 5 votes
@Override
public Void visitAssignment(AssignmentTree node, Void p) {
    exprBundleName = null;
    Void d = super.visitAssignment(node, p);
    if (exprBundleName != null) {
        Element dest = info.getTrees().getElement(getCurrentPath());
        if (dest != null && (dest.getKind() == ElementKind.LOCAL_VARIABLE || dest.getKind() == ElementKind.FIELD)) {
            variableBundles.put(dest, exprBundleName);
        }
    }
    return d;
}
 
Example 10
Project: incubator-netbeans   File: GoToSupport.java   Source Code and License Vote up 5 votes
@Override
public Void visitVariable(VariableElement e, Boolean highlightName) {
    modifier(e.getModifiers());
    
    result.append(getTypeName(info, e.asType(), true));
    
    result.append(' ');
    
    boldStartCheck(highlightName);

    result.append(e.getSimpleName());
    
    boldStopCheck(highlightName);
    
    if (highlightName) {
        if (e.getConstantValue() != null) {
            result.append(" = ");
            result.append(StringEscapeUtils.escapeHtml(e.getConstantValue().toString()));
        }
        
        Element enclosing = e.getEnclosingElement();
        
        if (e.getKind() != ElementKind.PARAMETER && e.getKind() != ElementKind.LOCAL_VARIABLE
                && e.getKind() != ElementKind.RESOURCE_VARIABLE && e.getKind() != ElementKind.EXCEPTION_PARAMETER) {
            result.append(" in ");

            //short typename:
            result.append(getTypeName(info, enclosing.asType(), true));
        }
    }
    
    return null;
}
 
Example 11
Project: incubator-netbeans   File: SemanticHighlighterBase.java   Source Code and License Vote up 4 votes
private static boolean isLocalVariableClosure(Element el) {
    return el.getKind() == ElementKind.PARAMETER || el.getKind() == ElementKind.LOCAL_VARIABLE
            || el.getKind() == ElementKind.RESOURCE_VARIABLE || el.getKind() == ElementKind.EXCEPTION_PARAMETER;
}
 
Example 12
Project: incubator-netbeans   File: PreconditionsChecker.java   Source Code and License Vote up 4 votes
private boolean isLocalVariable(Element el) {
    return el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.PARAMETER;
}
 
Example 13
Project: incubator-netbeans   File: Unbalanced.java   Source Code and License Vote up 4 votes
private static boolean isAcceptable(Element el) {
    return el != null && (el.getKind() == ElementKind.LOCAL_VARIABLE || (el.getKind() == ElementKind.FIELD && el.getModifiers().contains(Modifier.PRIVATE)));
}
 
Example 14
Project: incubator-netbeans   File: DoubleCheck.java   Source Code and License Vote up 4 votes
/**
 * Checks, that the two if statements test the same variable. Returns the tree that references
 * the guard variable if the two ifs are the same, or {@code null} if the ifs do not match.
 * @param info
 * @param statementTP
 * @param secondTP
 * @return 
 */
private static TreePath sameIfAndValidate(CompilationInfo info, TreePath statementTP, TreePath secondTP, TreePath[] fieldRef) {
    StatementTree statement = (StatementTree) statementTP.getLeaf();
    
    if (statement.getKind() != Kind.IF) {
        return null;
    }
    
    IfTree first = (IfTree)statement;
    IfTree second = (IfTree) secondTP.getLeaf();
    
    if (first.getElseStatement() != null) {
        return null;
    }
    if (second.getElseStatement() != null) {
        return null;
    }
    
    TreePath varFirst = equalToNull(new TreePath(statementTP, first.getCondition()));
    TreePath varSecond = equalToNull(new TreePath(secondTP, second.getCondition()));
    
    if (varFirst == null || varSecond == null) {
        return null;
    }

    Element firstVariable = info.getTrees().getElement(varFirst);
    Element secondVariable = info.getTrees().getElement(varSecond);
    Element target = firstVariable;
    if (firstVariable != null && firstVariable.equals(secondVariable)) {
        TreePath var = info.getTrees().getPath(firstVariable);
        if (info.getSourceVersion().compareTo(SourceVersion.RELEASE_5) < 0) {
            fieldRef[0] = var;
            return varFirst;
        }
        if (firstVariable.getKind() == ElementKind.LOCAL_VARIABLE) {
            // check how the variable was assigned:
            TreePath methodPath = Utilities.findTopLevelBlock(varFirst);
            FlowResult fr = Flow.assignmentsForUse(info, methodPath, new AtomicBoolean(false));
            Iterable<? extends TreePath> itp = fr.getAssignmentsForUse().get(varFirst.getLeaf());
            
            if (itp != null) {
                Iterator<? extends TreePath> i = itp.iterator();
                if (i.hasNext()) {
                    TreePath v = i.next();
                    if (!i.hasNext()) {
                        // if the local variable has exactly one possible value,
                        // use it as the field 
                        target = info.getTrees().getElement(v);
                        if (target != null && target.getKind() == ElementKind.FIELD) {
                            var = info.getTrees().getPath(target);
                            if (!sameCompilationUnit(var, varFirst)) {
                                // the variable is somewhere ... 
                                var = info.getTrees().getPath(firstVariable);
                            }
                        }
                    }
                }
            }
        }
        fieldRef[0] = var;
        return varFirst;
    }
    
    return null;
}
 
Example 15
Project: incubator-netbeans   File: ResourceStringFoldProvider.java   Source Code and License Vote up 4 votes
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void p) {
    messageMethod = null;
    exprBundleName = null;

    Void d = scan(node.getMethodSelect(), p);
    
    try {
        if (messageMethod == null) {
            return d;
        }
        String bundleFile = null;
        if (messageMethod.getKeyParam() == MessagePattern.GET_BUNDLE_CALL) {
            processGetBundleCall(node);
        } else {
            int bp = messageMethod.getBundleParam();
            if (bp == MessagePattern.BUNDLE_FROM_CLASS) {
                TypeMirror tm = info.getTrees().getTypeMirror(methodOwnerPath);
                if (tm != null && tm.getKind() == TypeKind.DECLARED) {
                    bundleFile = bundleFileFromClass(methodOwnerPath, messageMethod.getBundleFile());
                }
            } else if (bp == MessagePattern.BUNDLE_FROM_INSTANCE) {
                // simplification: assume the selector expression is a variable
                Element el = info.getTrees().getElement(methodOwnerPath);
                if (el != null && (el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.FIELD)) {
                    bundleFile = variableBundles.get(el);
                } else {
                    bundleFile = exprBundleName;
                }
            } else if (bp >= 0 && bp < node.getArguments().size()) {
                bundleFile = getBundleName(node, bp, messageMethod.getBundleFile());
            }
        }

        if (bundleFile == null) {
            return d;
        }

        int keyIndex = messageMethod.getKeyParam();
        if (node.getArguments().size() <= keyIndex) {
            return d;
        }

        String keyVal;
        if (keyIndex == MessagePattern.KEY_FROM_METHODNAME) {
            keyVal = this.methodName;
        } else {
            ExpressionTree keyArg = node.getArguments().get(keyIndex);
            if (keyArg.getKind() != Tree.Kind.STRING_LITERAL) {
                return d;
            }
            Object o = ((LiteralTree)keyArg).getValue();
            if (o == null) {
                return d;
            }
            keyVal = o.toString();
        }

        defineFold(bundleFile, keyVal, node);
    } finally {
    
        String expr = exprBundleName;

        scan(node.getArguments(), p);

        this.exprBundleName = expr;
    }
    
    // simplification, accept only String literals
    return d;
}