com.sun.source.tree.EnhancedForLoopTree Java Examples
The following examples show how to use
com.sun.source.tree.EnhancedForLoopTree.
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: CopyFinder.java From netbeans with Apache License 2.0 | 6 votes |
public Boolean visitEnhancedForLoop(EnhancedForLoopTree node, TreePath p) { if (p == null) { super.visitEnhancedForLoop(node, p); return false; } EnhancedForLoopTree ef = (EnhancedForLoopTree) p.getLeaf(); if (!scan(node.getVariable(), ef.getVariable(), p)) return false; if (!scan(node.getExpression(), ef.getExpression(), p)) return false; return scan(node.getStatement(), ef.getStatement(), p); }
Example #2
Source File: JavaInputAstVisitor.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
@Override public Void visitEnhancedForLoop(EnhancedForLoopTree node, Void unused) { sync(node); builder.open(ZERO); token("for"); builder.space(); token("("); builder.open(ZERO); visitToDeclare( DeclarationKind.NONE, Direction.HORIZONTAL, node.getVariable(), Optional.of(node.getExpression()), ":", Optional.<String>absent()); builder.close(); token(")"); builder.close(); visitStatement( node.getStatement(), CollapseEmptyOrNot.YES, AllowLeadingBlankLine.YES, AllowTrailingBlankLine.NO); return null; }
Example #3
Source File: JavaInputAstVisitor.java From google-java-format with Apache License 2.0 | 6 votes |
@Override public Void visitEnhancedForLoop(EnhancedForLoopTree node, Void unused) { sync(node); builder.open(ZERO); token("for"); builder.space(); token("("); builder.open(ZERO); visitToDeclare( DeclarationKind.NONE, Direction.HORIZONTAL, node.getVariable(), Optional.of(node.getExpression()), ":", /* trailing= */ Optional.empty()); builder.close(); token(")"); builder.close(); visitStatement( node.getStatement(), CollapseEmptyOrNot.YES, AllowLeadingBlankLine.YES, AllowTrailingBlankLine.NO); return null; }
Example #4
Source File: NCLOCVisitor.java From netbeans with Apache License 2.0 | 6 votes |
@Override public Object visitVariable(VariableTree node, Object p) { TreePath path = getCurrentPath(); Tree parent = path.getParentPath().getLeaf(); if (parent instanceof StatementTree) { boolean count = true; if (parent instanceof ForLoopTree) { count = !((ForLoopTree)parent).getInitializer().contains(node); } else if (parent instanceof EnhancedForLoopTree) { count = ((EnhancedForLoopTree)parent).getVariable() != node; } if (count) { statements++; } } return super.visitVariable(node, p); }
Example #5
Source File: JavaInputAstVisitor.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public Void visitEnhancedForLoop(EnhancedForLoopTree node, Void unused) { sync(node); builder.open(ZERO); token("for"); builder.space(); token("("); builder.open(ZERO); visitToDeclare( DeclarationKind.NONE, Direction.HORIZONTAL, node.getVariable(), Optional.of(node.getExpression()), ":", Optional.<String>absent()); builder.close(); token(")"); builder.close(); visitStatement( node.getStatement(), CollapseEmptyOrNot.YES, AllowLeadingBlankLine.YES, AllowTrailingBlankLine.NO); return null; }
Example #6
Source File: ExpectedTypeResolver.java From netbeans with Apache License 2.0 | 6 votes |
@Override public List<? extends TypeMirror> visitEnhancedForLoop(EnhancedForLoopTree node, Object p) { TypeMirror varType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getVariable())); if (!Utilities.isValidType(varType)) { return null; } else { TypeMirror arrayType = info.getTypes().getArrayType(varType); TypeElement iterableEl = info.getElements().getTypeElement("java.lang.Iterable"); // NOI18N if (iterableEl == null || iterableEl.getKind() != ElementKind.INTERFACE) { return null; } TypeMirror iterableForVar = isPrimitiveType(varType.getKind()) ? info.getTypes().getDeclaredType(iterableEl, info.getTypes().getWildcardType( info.getTypes().boxedClass((PrimitiveType)varType).asType(), null)) : info.getTypes().getDeclaredType(iterableEl, info.getTypes().getWildcardType(varType, null) ); List<TypeMirror> result = new ArrayList<TypeMirror>(2); result.add(arrayType); result.add(iterableForVar); return result; } }
Example #7
Source File: ForLoopToFunctionalHint.java From netbeans with Apache License 2.0 | 6 votes |
@TriggerTreeKind(Tree.Kind.ENHANCED_FOR_LOOP) @Messages("ERR_ForLoopToFunctionalHint=Can use functional operations") public static ErrorDescription computeWarning(HintContext ctx) { if (ctx.getInfo().getElements().getTypeElement("java.util.stream.Streams") == null && !DISABLE_CHECK_FOR_STREAM) return null; PreconditionsChecker pc = new PreconditionsChecker(ctx.getPath().getLeaf(), ctx.getInfo()); if (pc.isSafeToRefactor()) { EnhancedForLoopTree eflt = (EnhancedForLoopTree)ctx.getPath().getLeaf(); StatementTree stmt = eflt.getStatement(); if (stmt == null) { return null; } if (stmt.getKind() == Tree.Kind.BLOCK) { BlockTree bt = (BlockTree)stmt; if (bt.getStatements() == null || bt.getStatements().isEmpty()) { return null; } } Fix fix = new FixImpl(ctx.getInfo(), ctx.getPath(), null).toEditorFix(); return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ForLoopToFunctionalHint(), fix); } return null; }
Example #8
Source File: ConvertVarToExplicitType.java From netbeans with Apache License 2.0 | 6 votes |
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 #9
Source File: ExpressionScanner.java From netbeans with Apache License 2.0 | 5 votes |
@Override public List<Tree> visitEnhancedForLoop(EnhancedForLoopTree node, ExpressionScanner.ExpressionsInfo p) { List<Tree> expr = null; if (acceptsTree(node.getExpression())) { expr = scan(node.getExpression(), p); } List<Tree> bodyr = scan(node.getStatement(), p); if (expr != null && expr.size() > 0 && bodyr != null && bodyr.size() > 0) { p.addNextExpression(expr.get(expr.size() - 1), bodyr.get(0)); p.addNextExpression(bodyr.get(bodyr.size() - 1), expr.get(0)); } return reduce(expr, bodyr); }
Example #10
Source File: Unbalanced.java From netbeans with Apache License 2.0 | 5 votes |
@TriggerPattern(value="$mods$ $type $name = $init$;") public static ErrorDescription after(HintContext ctx) { if (testElement(ctx) == null) return null; TreePath init = ctx.getVariables().get("$init$"); if (init != null) { if (init.getLeaf().getKind() != Kind.NEW_CLASS) return null; NewClassTree nct = (NewClassTree) init.getLeaf(); if (nct.getClassBody() != null || nct.getArguments().size() > 1) return null; if (nct.getArguments().size() == 1) { TypeMirror tm = ctx.getInfo().getTrees().getTypeMirror(new TreePath(init, nct.getArguments().get(0))); if (tm == null || tm.getKind() != TypeKind.INT) return null; } } if ( ctx.getPath().getParentPath().getLeaf().getKind() == Kind.ENHANCED_FOR_LOOP && ((EnhancedForLoopTree) ctx.getPath().getParentPath().getLeaf()).getVariable() == ctx.getPath().getLeaf()) { return null; } return produceWarning(ctx, "ERR_UnbalancedCollection"); }
Example #11
Source File: CreateElementUtilities.java From netbeans with Apache License 2.0 | 5 votes |
private static List<? extends TypeMirror> computeEnhancedForLoop(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { EnhancedForLoopTree efl = (EnhancedForLoopTree) parent.getLeaf(); if (efl.getExpression() != error) { return null; } TypeMirror argument = info.getTrees().getTypeMirror(new TreePath(new TreePath(parent, efl.getVariable()), efl.getVariable().getType())); if (argument == null) return null; if (argument.getKind().isPrimitive()) { types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return Collections.singletonList(info.getTypes().getArrayType(argument)); } TypeElement iterable = info.getElements().getTypeElement("java.lang.Iterable"); //NOI18N if (iterable == null) { return null; } types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return Collections.singletonList(info.getTypes().getDeclaredType(iterable, argument)); }
Example #12
Source File: CreateElementUtilities.java From netbeans with Apache License 2.0 | 5 votes |
private static List<? extends TypeMirror> computeVariableDeclaration(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { VariableTree vt = (VariableTree) parent.getLeaf(); if (vt.getInitializer() == error) { types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return Collections.singletonList(info.getTrees().getTypeMirror(new TreePath(parent, vt.getType()))); } TreePath context = parent.getParentPath(); if (vt.getType() != error || context == null) { return null; } switch (context.getLeaf().getKind()) { case ENHANCED_FOR_LOOP: ExpressionTree iterableTree = ((EnhancedForLoopTree) context.getLeaf()).getExpression(); TreePath iterablePath = new TreePath(context, iterableTree); TypeMirror type = getIterableGenericType(info, iterablePath); types.add(ElementKind.LOCAL_VARIABLE); return Collections.singletonList(type); default: types.add(ElementKind.CLASS); return Collections.<TypeMirror>emptyList(); } }
Example #13
Source File: ExpandEnhancedForLoop.java From netbeans with Apache License 2.0 | 5 votes |
@TriggerPattern("for ($type $varName : $expression) { $stmts$; }") public static ErrorDescription run(HintContext ctx) { TreePath tp = ctx.getPath(); EnhancedForLoopTree efl = (EnhancedForLoopTree) tp.getLeaf(); long statementStart = ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getInfo().getCompilationUnit(), efl.getStatement()); int caret = ctx.getCaretLocation(); if (caret >= statementStart) { return null; } TypeMirror expressionType = ctx.getInfo().getTrees().getTypeMirror(new TreePath(tp, efl.getExpression())); if (expressionType == null || expressionType.getKind() != TypeKind.DECLARED) { return null; } ExecutableElement iterator = findIterable(ctx.getInfo()); Types t = ctx.getInfo().getTypes(); if (iterator == null || !t.isSubtype(((DeclaredType) expressionType), t.erasure(iterator.getEnclosingElement().asType()))) { return null; } FixImpl fix = new FixImpl(TreePathHandle.create(tp, ctx.getInfo())); List<Fix> fixes = Collections.<Fix>singletonList(fix.toEditorFix()); return ErrorDescriptionFactory.createErrorDescription(ctx.getSeverity(), NbBundle.getMessage(ExpandEnhancedForLoop.class, "ERR_ExpandEhancedForLoop"), fixes, ctx.getInfo().getFileObject(), caret, caret); }
Example #14
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
public static Collection<? extends Element> getForwardReferences(TreePath path, int pos, SourcePositions sourcePositions, Trees trees) { HashSet<Element> refs = new HashSet<Element>(); while(path != null) { switch(path.getLeaf().getKind()) { case BLOCK: if (path.getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) break; case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: return refs; case VARIABLE: refs.add(trees.getElement(path)); TreePath parent = path.getParentPath(); if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getLeaf().getKind())) { boolean isStatic = ((VariableTree)path.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC); for(Tree member : ((ClassTree)parent.getLeaf()).getMembers()) { if (member.getKind() == Tree.Kind.VARIABLE && sourcePositions.getStartPosition(path.getCompilationUnit(), member) >= pos && (isStatic || !((VariableTree)member).getModifiers().getFlags().contains(Modifier.STATIC))) refs.add(trees.getElement(new TreePath(parent, member))); } } return refs; case ENHANCED_FOR_LOOP: EnhancedForLoopTree efl = (EnhancedForLoopTree)path.getLeaf(); if (sourcePositions.getEndPosition(path.getCompilationUnit(), efl.getExpression()) >= pos) refs.add(trees.getElement(new TreePath(path, efl.getVariable()))); } path = path.getParentPath(); } return refs; }
Example #15
Source File: InfiniteRecursion.java From netbeans with Apache License 2.0 | 5 votes |
@Override public State visitEnhancedForLoop(EnhancedForLoopTree node, Void p) { State s; registerBreakTarget((node)); returnIfRecurse(s = scan(node.getExpression(), p)); // if the expression does not recurse, it might evaluate to an empty Iterable, and skip the entire body. // PENDING: speculatively report recursions, if unconditionally reachable from cycles ? return s; }
Example #16
Source File: NullAway.java From NullAway with MIT License | 5 votes |
@Override public Description matchEnhancedForLoop(EnhancedForLoopTree tree, VisitorState state) { if (!matchWithinClass) { return Description.NO_MATCH; } ExpressionTree expr = tree.getExpression(); final ErrorMessage errorMessage = new ErrorMessage( MessageTypes.DEREFERENCE_NULLABLE, "enhanced-for expression " + state.getSourceForNode(expr) + " is @Nullable"); if (mayBeNullExpr(state, expr)) { return errorBuilder.createErrorDescription(errorMessage, buildDescription(expr), state); } return Description.NO_MATCH; }
Example #17
Source File: TreeConverter.java From j2objc with Apache License 2.0 | 5 votes |
private TreeNode convertEnhancedForStatement(EnhancedForLoopTree node, TreePath parent) { TreePath path = getTreePath(parent, node); return new EnhancedForStatement() .setParameter( (SingleVariableDeclaration) convertSingleVariable(node.getVariable(), path).setPosition(getPosition(node))) .setExpression((Expression) convert(node.getExpression(), path)) .setBody((Statement) convert(node.getStatement(), path)); }
Example #18
Source File: UTemplater.java From Refaster with Apache License 2.0 | 5 votes |
@Override public UEnhancedForLoop visitEnhancedForLoop(EnhancedForLoopTree tree, Void v) { return UEnhancedForLoop.create( visitVariable(tree.getVariable(), null), template(tree.getExpression()), template(tree.getStatement())); }
Example #19
Source File: UEnhancedForLoop.java From Refaster with Apache License 2.0 | 5 votes |
@Override @Nullable public Unifier visitEnhancedForLoop(EnhancedForLoopTree loop, @Nullable Unifier unifier) { unifier = getVariable().unify(loop.getVariable(), unifier); unifier = getExpression().unify(loop.getExpression(), unifier); return getStatement().unify(loop.getStatement(), unifier); }
Example #20
Source File: TreeDiffer.java From compile-testing with Apache License 2.0 | 5 votes |
@Override public Void visitEnhancedForLoop(EnhancedForLoopTree expected, Tree actual) { Optional<EnhancedForLoopTree> other = checkTypeAndCast(expected, actual); if (!other.isPresent()) { addTypeMismatch(expected, actual); return null; } scan(expected.getVariable(), other.get().getVariable()); scan(expected.getExpression(), other.get().getExpression()); scan(expected.getStatement(), other.get().getStatement()); return null; }
Example #21
Source File: DepthVisitor.java From netbeans with Apache License 2.0 | 5 votes |
@Override public Object visitEnhancedForLoop(EnhancedForLoopTree node, Object p) { depth++; Object o = super.visitEnhancedForLoop(node, p); depth--; return o; }
Example #22
Source File: TreeDuplicator.java From netbeans with Apache License 2.0 | 5 votes |
@Override public Tree visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { EnhancedForLoopTree n = make.EnhancedForLoop(tree.getVariable(), tree.getExpression(), tree.getStatement()); model.setType(n, model.getType(tree)); comments.copyComments(tree, n); model.setPos(n, model.getPos(tree)); return n; }
Example #23
Source File: CreateElementUtilities.java From netbeans with Apache License 2.0 | 5 votes |
private static List<? extends TypeMirror> computeEnhancedForLoop(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { EnhancedForLoopTree efl = (EnhancedForLoopTree) parent.getLeaf(); if (efl.getExpression() != error) { return null; } TypeMirror argument = info.getTrees().getTypeMirror(new TreePath(new TreePath(parent, efl.getVariable()), efl.getVariable().getType())); if (argument == null) return null; if (argument.getKind().isPrimitive()) { types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return Collections.singletonList(info.getTypes().getArrayType(argument)); } TypeElement iterable = info.getElements().getTypeElement("java.lang.Iterable"); //NOI18N if (iterable == null) { return null; } types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return Collections.singletonList(info.getTypes().getDeclaredType(iterable, argument)); }
Example #24
Source File: CreateElementUtilities.java From netbeans with Apache License 2.0 | 5 votes |
private static List<? extends TypeMirror> computeVariableDeclaration(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { VariableTree vt = (VariableTree) parent.getLeaf(); if (vt.getInitializer() == error) { types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return Collections.singletonList(info.getTrees().getTypeMirror(new TreePath(parent, vt.getType()))); } TreePath context = parent.getParentPath(); if (vt.getType() != error || context == null) { return null; } switch (context.getLeaf().getKind()) { case ENHANCED_FOR_LOOP: ExpressionTree iterableTree = ((EnhancedForLoopTree) context.getLeaf()).getExpression(); TreePath iterablePath = new TreePath(context, iterableTree); TypeMirror type = getIterableGenericType(info, iterablePath); types.add(ElementKind.LOCAL_VARIABLE); return Collections.singletonList(type); default: types.add(ElementKind.CLASS); return Collections.<TypeMirror>emptyList(); } }
Example #25
Source File: CyclomaticComplexityVisitor.java From netbeans with Apache License 2.0 | 5 votes |
@Override public Object visitEnhancedForLoop(EnhancedForLoopTree node, Object p) { boolean saveFlag = switchCase; switchCase = false; complexity++; Object o = super.visitEnhancedForLoop(node, p); this.switchCase = saveFlag; return o; }
Example #26
Source File: Unbalanced.java From netbeans with Apache License 2.0 | 5 votes |
@TriggerPattern(value="$mods$ $type[] $name = $init$;") public static ErrorDescription after(HintContext ctx) { VariableElement var = testElement(ctx); if (var == null) return null; Tree parent = ctx.getPath().getParentPath().getLeaf(); if (parent.getKind() == Kind.ENHANCED_FOR_LOOP && ((EnhancedForLoopTree) parent).getVariable() == ctx.getPath().getLeaf()) { return null; } TreePath init = ctx.getVariables().get("$init$"); if (init != null) { boolean asWrite = true; if (init.getLeaf().getKind() == Kind.NEW_ARRAY) { NewArrayTree nat = (NewArrayTree) init.getLeaf(); if (nat.getInitializers() == null || nat.getInitializers().isEmpty()) { asWrite = false; } } if (asWrite) { record(ctx.getInfo(), var, State.WRITE); } } return produceWarning(ctx, "ERR_UnbalancedArray"); }
Example #27
Source File: TreeNode.java From netbeans with Apache License 2.0 | 5 votes |
@Override public Void visitEnhancedForLoop(EnhancedForLoopTree tree, List<Node> d) { List<Node> below = new ArrayList<Node>(); addCorrespondingType(below); addCorrespondingComments(below); super.visitEnhancedForLoop(tree, below); d.add(new TreeNode(info, getCurrentPath(), below)); return null; }
Example #28
Source File: ForLoopToFunctionalHint.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected void performRewrite(TransformationContext ctx) { EnhancedForLoopTree loop = (EnhancedForLoopTree) ctx.getPath().getLeaf(); pc = new PreconditionsChecker(loop, ctx.getWorkingCopy()); refactorer = new Refactorer(loop, ctx.getWorkingCopy(), pc); if (pc.isSafeToRefactor() && refactorer.isRefactorable()) { ctx.getWorkingCopy().rewrite(ctx.getPath().getLeaf(), refactorer.refactor(ctx.getWorkingCopy().getTreeMaker())); } }
Example #29
Source File: PreconditionsChecker.java From netbeans with Apache License 2.0 | 5 votes |
public PreconditionsChecker(Tree forLoop, CompilationInfo workingCopy) { if (forLoop.getKind() == Tree.Kind.ENHANCED_FOR_LOOP) { this.isForLoop = true; this.workingCopy = workingCopy; this.hasUncaughtException = workingCopy.getTreeUtilities() .getUncaughtExceptions(TreePath.getPath(workingCopy.getCompilationUnit(), forLoop)).stream().anyMatch(this::filterCheckedExceptions); this.innerVariables = this.getInnerVariables(forLoop, workingCopy.getTrees()); this.visitor = new ForLoopTreeVisitor(this.innerVariables, workingCopy, new TreePath(workingCopy.getCompilationUnit()), (EnhancedForLoopTree) forLoop); this.isIterable = this.isIterbale(((EnhancedForLoopTree) forLoop).getExpression()); visitor.scan(TreePath.getPath(workingCopy.getCompilationUnit(), forLoop), workingCopy.getTrees()); } else { this.isForLoop = false; } }
Example #30
Source File: Braces.java From netbeans with Apache License 2.0 | 5 votes |
@Hint(displayName="#LBL_Braces_For", description="#DSC_Braces_For", category="braces", id=BRACES_ID + "FOR_LOOP", enabled=false, suppressWarnings={"", "ControlFlowStatementWithoutBraces"}) @TriggerTreeKind({Tree.Kind.FOR_LOOP, Tree.Kind.ENHANCED_FOR_LOOP}) public static ErrorDescription checkFor(HintContext ctx) { StatementTree st; switch (ctx.getPath().getLeaf().getKind()){ case FOR_LOOP: st = ((ForLoopTree) ctx.getPath().getLeaf()).getStatement(); break; case ENHANCED_FOR_LOOP: st = ((EnhancedForLoopTree) ctx.getPath().getLeaf()).getStatement(); break; default: throw new IllegalStateException(); } return checkStatement(ctx, "LBL_Braces_For", st, ctx.getPath()); }