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

The following examples show how to use javax.lang.model.element.ElementKind#LOCAL_VARIABLE . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@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 2
protected static boolean isVariableValidForVarHint(HintContext ctx) {
    CompilationInfo info = ctx.getInfo();
    TreePath treePath = ctx.getPath();
    // hint will be enable only for JDK-10 or above.
    if (info.getSourceVersion().compareTo(SourceVersion.RELEASE_9) < 1) {
        return false;
    }
     if (treePath.getLeaf().getKind() == Tree.Kind.ENHANCED_FOR_LOOP) {
        EnhancedForLoopTree efl = (EnhancedForLoopTree) treePath.getLeaf();
        TypeMirror expressionType = ctx.getInfo().getTrees().getTypeMirror(new TreePath(treePath, efl.getExpression()));
        if (!Utilities.isValidType(expressionType)) {
            return false;
        }
    } else {
        Element treePathELement = info.getTrees().getElement(treePath);
        // should be local variable
        if (treePathELement != null && (treePathELement.getKind() != ElementKind.LOCAL_VARIABLE && treePathELement.getKind() != ElementKind.RESOURCE_VARIABLE)) {
            return false;
        }
    }
    return true;
}
 
Example 3
Source Project: netbeans   File: IntroduceConstantFix.java    License: Apache License 2.0 6 votes vote down vote up
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 4
@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 5
@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 6
Source Project: netbeans   File: RenameRefactoringUI.java    License: Apache License 2.0 5 votes vote down vote up
@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 7
Source Project: netbeans   File: PreconditionsChecker.java    License: Apache License 2.0 5 votes vote down vote up
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 8
Source Project: netbeans   File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
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
@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
Source Project: netbeans   File: GoToSupport.java    License: Apache License 2.0 5 votes vote down vote up
@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
                && !TreeShims.BINDING_VARIABLE.equals(e.getKind().name())) {
            result.append(" in ");

            //short typename:
            result.append(getTypeName(info, enclosing.asType(), true));
        }
    }
    
    return null;
}
 
Example 11
Source Project: netbeans   File: ELHyperlinkProvider.java    License: Apache License 2.0 5 votes vote down vote up
@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(e.getConstantValue().toString());
        }

        Element enclosing = e.getEnclosingElement();

        if (e.getKind() != ElementKind.PARAMETER && e.getKind() != ElementKind.LOCAL_VARIABLE && e.getKind() != ElementKind.EXCEPTION_PARAMETER) {
            result.append(" in ");

            //short typename:
            result.append(getTypeName(info, enclosing.asType(), true));
        }
    }

    return null;
}
 
Example 12
Source Project: j2cl   File: CompilationUnitBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private Expression convertIdent(JCIdent identifier) {
  if (isThisExpression(identifier)) {
    return new ThisReference(getCurrentType().getTypeDescriptor());
  }
  if (isSuperExpression(identifier)) {
    return new SuperReference(getCurrentType().getTypeDescriptor());
  }
  Symbol symbol = identifier.sym;
  if (symbol instanceof ClassSymbol) {
    return new JavaScriptConstructorReference(
        environment.createDeclarationForType((ClassSymbol) identifier.sym));
  }
  if (symbol instanceof MethodSymbol) {
    return NullLiteral.get().withComment(identifier.toString());
  }

  VarSymbol varSymbol = (VarSymbol) symbol;
  if (symbol.getKind() == ElementKind.LOCAL_VARIABLE
      || symbol.getKind() == ElementKind.RESOURCE_VARIABLE
      || symbol.getKind() == ElementKind.PARAMETER
      || symbol.getKind() == ElementKind.EXCEPTION_PARAMETER) {
    Variable variable = variableByVariableElement.get(symbol);
    return resolveVariableReference(variable);
  }

  FieldDescriptor fieldDescriptor = environment.createFieldDescriptor(varSymbol, identifier.type);
  Expression qualifier =
      fieldDescriptor.isStatic()
          ? null
          : resolveOuterClassReference(fieldDescriptor.getEnclosingTypeDescriptor(), false);
  return FieldAccess.newBuilder()
      .setQualifier(qualifier)
      .setTargetFieldDescriptor(fieldDescriptor)
      .build();
}
 
Example 13
Source Project: netbeans   File: ArithmeticUtilities.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Attempts to resolve Elements value. For JLS-strict mode, values are only resolved for fields. Null value
 * or known-not-null values are ignored. For enhanced mode, null & non-null may be returned for further processing
 * 
 * @param info
 * @param path
 * @param enhanceProcessing
 * @return 
 */
private static Object resolveElementValue(CompilationInfo info, TreePath path, boolean enhanceProcessing) {
    Element el = info.getTrees().getElement(path);
    if (el == null) {
        return null;
    }
    Map<Object, ElementValue> cache = getValueCache(info);
    ElementValue entry = cache.get(el);
    if (entry != null) {
        Object v = enhanceProcessing ? entry.constant : entry.jlsConstant;
        if (v != null) {
            return v != UNKNOWN ? v : null;
        }
    }
    
    if (el == null) {
        return null;
    }
    Object obj = null;
    if (el.getKind() == ElementKind.FIELD) {
        obj = ((VariableElement) el).getConstantValue();
        // if enhanced processing is enabled, give other chance to fields that are static final
        if (obj == null && (!el.getModifiers().contains(Modifier.FINAL) || !enhanceProcessing)) {
            obj = UNKNOWN;
        }
    } else if (el.getKind() == ElementKind.LOCAL_VARIABLE) {
        obj = ((VariableElement) el).getConstantValue();
        if (obj == null && (!el.getModifiers().contains(Modifier.FINAL) || !enhanceProcessing)) {
            obj = UNKNOWN;
        }
    }
    EVAL: if (obj == null) {
        TreePath varPath = info.getTrees().getPath(el);
        if (varPath != null && varPath.getLeaf().getKind() == Tree.Kind.VARIABLE) {
            // #262309: if variable is errnoeously referenced from its own initializer, we must not recurse.
            for (Tree t : path) {
                if (t == varPath.getLeaf()) {
                    break EVAL;
                }
                if (StatementTree.class.isAssignableFrom(t.getKind().asInterface())) {
                    break;
                }
            }
            VariableTree vt = (VariableTree)varPath.getLeaf();
            if (vt.getInitializer() != null) {
                VisitorImpl recurse = new VisitorImpl(info, true, enhanceProcessing);
                try {
                    obj = recurse.scan(new TreePath(varPath, vt.getInitializer()), null);
                } catch (ArithmeticException | IndexOutOfBoundsException | IllegalArgumentException ex) {
                    // no op, obj is already null.
                }
            }
        }
    } else if (entry == null) {
        // obj was resolved as a constant value and entry still does not exist for it -> save memory
        return obj != UNKNOWN ? obj : null;
    }
    
    if (entry == null) {
        entry = new ElementValue();
        cache.put(el, entry);
    }
    if (obj == null) {
        obj = UNKNOWN;
    }
    if (enhanceProcessing) {
        entry.constant = obj;
    } else {
        entry.jlsConstant = obj;
        if (obj == NULL || obj == NOT_NULL) {
            return null;
        }
    }
    return obj != UNKNOWN ? obj : null;
}
 
Example 14
Source Project: netbeans   File: PreconditionsChecker.java    License: Apache License 2.0 4 votes vote down vote up
private boolean isLocalVariable(Element el) {
    return el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.PARAMETER;
}
 
Example 15
Source Project: netbeans   File: Unbalanced.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean isAcceptable(Element el) {
    return el != null && (el.getKind() == ElementKind.LOCAL_VARIABLE || (el.getKind() == ElementKind.FIELD && el.getModifiers().contains(Modifier.PRIVATE)));
}
 
Example 16
Source Project: j2objc   File: ElementUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isVariable(Element element) {
  ElementKind kind = element.getKind();
  return kind == ElementKind.FIELD || kind == ElementKind.LOCAL_VARIABLE
      || kind == ElementKind.PARAMETER || kind == ElementKind.EXCEPTION_PARAMETER
      || kind == ElementKind.RESOURCE_VARIABLE || kind == ElementKind.ENUM_CONSTANT;
}
 
Example 17
Source Project: netbeans   File: DoubleCheck.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 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 18
Source Project: j2objc   File: ElementUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isLocalVariable(Element element) {
  return element.getKind() == ElementKind.LOCAL_VARIABLE;
}
 
Example 19
@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;
}
 
Example 20
Source Project: j2objc   File: GeneratedVariableElement.java    License: Apache License 2.0 4 votes vote down vote up
public static GeneratedVariableElement newLocalVar(
    String name, TypeMirror type, Element enclosingElement) {
  return new GeneratedVariableElement(
      name, type, ElementKind.LOCAL_VARIABLE, enclosingElement, true);
}