com.sun.source.tree.InstanceOfTree Java Examples

The following examples show how to use com.sun.source.tree.InstanceOfTree. 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: Java14InputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitInstanceOf(InstanceOfTree node, Void unused) {
  sync(node);
  builder.open(plusFour);
  scan(node.getExpression(), null);
  builder.breakOp(" ");
  builder.open(ZERO);
  token("instanceof");
  builder.breakOp(" ");
  if (node.getPattern() != null) {
    scan(node.getPattern(), null);
  } else {
    scan(node.getType(), null);
  }
  builder.close();
  builder.close();
  return null;
}
 
Example #2
Source File: ConvertToPatternInstanceOf.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
        protected void performRewrite(JavaFix.TransformationContext ctx) {
            WorkingCopy wc = ctx.getWorkingCopy();
            TreePath main = ctx.getPath();
            IfTree it = (IfTree) main.getLeaf();
            InstanceOfTree iot = (InstanceOfTree) ((ParenthesizedTree) it.getCondition()).getExpression();
            StatementTree bt = it.getThenStatement();
//            wc.rewrite(iot.getType(), wc.getTreeMaker().BindingPattern(var.getName(), iot.getType()));
//            wc.rewrite(bt, wc.getTreeMaker().removeBlockStatement(bt, 0));
            InstanceOfTree cond = wc.getTreeMaker().InstanceOf(iot.getExpression(), wc.getTreeMaker().BindingPattern(varName, iot.getType()));
            StatementTree thenBlock = removeFirst ? wc.getTreeMaker().removeBlockStatement((BlockTree) bt, 0) : bt;
            wc.rewrite(it, wc.getTreeMaker().If(wc.getTreeMaker().Parenthesized(cond), thenBlock, it.getElseStatement()));
            replaceOccurrences.stream().map(tph -> tph.resolve(wc)).forEach(tp -> {
                if (!removeFirst && tp.getParentPath().getLeaf().getKind() == Kind.PARENTHESIZED) {
                    tp = tp.getParentPath();
                }
                wc.rewrite(tp.getLeaf(), wc.getTreeMaker().Identifier(varName));
            });
        }
 
Example #3
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitInstanceOf(InstanceOfTree tree, Void p) {
    InstanceOfTree n = make.InstanceOf(tree.getExpression(), tree.getType());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #4
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitInstanceOf(InstanceOfTree expected, Tree actual) {
  Optional<InstanceOfTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getExpression(), other.get().getExpression());
  scan(expected.getType(), other.get().getType());
  return null;
}
 
Example #5
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertInstanceOf(InstanceOfTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  TypeMirror clazz = getTypeMirror(getTreePath(path, node.getType()));
  return new InstanceofExpression()
      .setLeftOperand((Expression) convert(node.getExpression(), path))
      .setRightOperand(Type.newType(clazz))
      .setTypeMirror(getTypeMirror(path));
}
 
Example #6
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitInstanceOf(InstanceOfTree node, Void unused) {
  sync(node);
  builder.open(plusFour);
  scan(node.getExpression(), null);
  builder.breakOp(" ");
  builder.open(ZERO);
  token("instanceof");
  builder.breakOp(" ");
  scan(node.getType(), null);
  builder.close();
  builder.close();
  return null;
}
 
Example #7
Source File: InstanceOfScanner.java    From annotation-tools with MIT License 5 votes vote down vote up
@Override
public Void visitInstanceOf(InstanceOfTree node, Void p) {
  if (!done) {
    index++;
  }
  if (tree == node) {
    done = true;
  }
  return super.visitInstanceOf(node, p);
}
 
Example #8
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Void visitInstanceOf(InstanceOfTree node, Void unused) {
    sync(node);
    builder.open(plusFour);
    scan(node.getExpression(), null);
    builder.breakOp(" ");
    builder.open(ZERO);
    token("instanceof");
    builder.breakOp(" ");
    scan(node.getType(), null);
    builder.close();
    builder.close();
    return null;
}
 
Example #9
Source File: GoToSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isCaretInsideDeclarationName(CompilationInfo info, Tree t, TreePath path, int caret) {
    try {
        switch (t.getKind()) {
            case INSTANCE_OF:
                Tree pattern = TreeShims.getPattern((InstanceOfTree) t);
                if (pattern == null || !"BINDING_PATTERN".equals(pattern.getKind().name())) {
                    return false;
                }
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
            case METHOD:
            case VARIABLE:
                int[] span = org.netbeans.modules.java.editor.base.semantic.Utilities.findIdentifierSpan(path, info, info.getDocument());

                if (span == null || span[0] == (-1) || span[1] == (-1)) {
                    return false;
                }

                return span[0] <= caret && caret <= span[1];
            default:
                return false;
        }

    } catch (IOException iOException) {
        Exceptions.printStackTrace(iOException);
        return false;
    }
}
 
Example #10
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Anything object-typed could be in the instance-of
 * 
 * @param node
 * @param p
 * @return 
 */
@Override
public List<? extends TypeMirror> visitInstanceOf(InstanceOfTree node, Object p) {
    if (theExpression == null) {
        initExpression(new TreePath(getCurrentPath(), node.getExpression()));
    }
    TypeElement tel = info.getElements().getTypeElement("java.lang.Object");
    if (tel == null) {
        return null;
    }
    return Collections.singletonList(tel.asType()); // NOI18N
}
 
Example #11
Source File: EqualsMethodHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitInstanceOf(InstanceOfTree node, Void p) {
    Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getExpression()));
    
    if (parameter.equals(e)) {
        throw new Found();
    }
    
    return super.visitInstanceOf(node, p);
}
 
Example #12
Source File: TreeNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitInstanceOf(InstanceOfTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();
    
    addCorrespondingType(below);
    addCorrespondingComments(below);
    super.visitInstanceOf(tree, below);
    
    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
 
Example #13
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Boolean visitInstanceOf(InstanceOfTree node, TreePath p) {
    if (p == null)
        return super.visitInstanceOf(node, p);

    InstanceOfTree t = (InstanceOfTree) p.getLeaf();

    if (!scan(node.getExpression(), t.getExpression(), p))
        return false;

    return scan(node.getType(), t.getType(), p);
}
 
Example #14
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitInstanceOf(InstanceOfTree node, Void unused) {
    sync(node);
    builder.open(plusFour);
    scan(node.getExpression(), null);
    builder.breakOp(" ");
    builder.open(ZERO);
    token("instanceof");
    builder.breakOp(" ");
    scan(node.getType(), null);
    builder.close();
    builder.close();
    return null;
}
 
Example #15
Source File: Flow.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public Boolean visitInstanceOf(InstanceOfTree node, ConstructorData p) {
    super.visitInstanceOf(node, p);
    return null;
}
 
Example #16
Source File: RemoveUnnecessary.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Object visitInstanceOf(InstanceOfTree node, Object p) {
    return null;
}
 
Example #17
Source File: IllegalInstanceOf.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public List<ErrorDescription> run(CompilationInfo info, TreePath treePath) {
    if (treePath.getLeaf().getKind() != Kind.INSTANCE_OF) {
        return null;
    }
    
    InstanceOfTree iot = (InstanceOfTree) treePath.getLeaf();
    TypeMirror     leftTypeMirror = info.getTrees().getTypeMirror(new TreePath(treePath, iot.getExpression()));
    Element        rightType = info.getTrees().getElement(new TreePath(treePath, iot.getType()));
    
    if (leftTypeMirror == null || leftTypeMirror.getKind() != TypeKind.DECLARED) {
        return null;
    }
    
    Element leftType = ((DeclaredType) leftTypeMirror).asElement();
    
    if (leftType == null || rightType == null || !leftType.getKind().isInterface() || !rightType.getKind().isInterface()) {
        //no problem:
        return null;
    }
    
    TypeElement left = (TypeElement) leftType;
    TypeElement right = (TypeElement) rightType;
    
    if (   left.getEnclosingElement().getKind() != ElementKind.PACKAGE
        || right.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        return null;
    }
    
    PackageElement leftPackage = (PackageElement) left.getEnclosingElement();
    PackageElement rightPackage = (PackageElement) right.getEnclosingElement();
    
    String leftPackageFQN = leftPackage.getQualifiedName().toString();
    String rightPackageFQN = rightPackage.getQualifiedName().toString();
    
    if (packagesToCheck.containsKey(leftPackageFQN) && leftPackageFQN.equals(rightPackageFQN)) {
        String verifyClass = packagesToCheck.get(leftPackageFQN);
        TypeElement loadedVerify = info.getElements().getTypeElement(verifyClass);
        
        if (loadedVerify == null || !info.getTypes().isSubtype(left.asType(), loadedVerify.asType()))
            return null;
        
        if (!info.getTypes().isSubtype(right.asType(), loadedVerify.asType()))
            return null;
        
        int start = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), iot);
        int end   = (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), iot);
        return Collections.<ErrorDescription>singletonList(
                   ErrorDescriptionFactory.createErrorDescription(getSeverity().toEditorSeverity(),
                                                                  NbBundle.getMessage(IllegalInstanceOf.class, "MSG_IllegalInstanceOf"),
                                                                  info.getFileObject(),
                                                                  start,
                                                                  end
                                                                 )
               );
    }
    
    return null;
}
 
Example #18
Source File: DeclarationForInstanceOf.java    From netbeans with Apache License 2.0 4 votes vote down vote up
List<ErrorDescription> run(CompilationInfo info, TreePath treePath, int offset) {
    TreePath ifPath = treePath;
    
    while (ifPath != null) {
        Kind lk = ifPath.getLeaf().getKind();
        
        if (lk == Kind.IF) {
            break;
        }
        
        if (lk == Kind.METHOD || TreeUtilities.CLASS_TREE_KINDS.contains(lk)) {
            return null;
        }
        
        ifPath = ifPath.getParentPath();
    }
    
    if (ifPath == null) {
        return null;
    }
    
    InstanceOfTree leaf = (InstanceOfTree) treePath.getLeaf();
    
    if (leaf.getType() == null || leaf.getType().getKind() == Kind.ERRONEOUS) {
        return null;
    }
    
    TypeMirror castTo = info.getTrees().getTypeMirror(new TreePath(treePath, leaf.getType()));
    TreePath expression = new TreePath(treePath, leaf.getExpression());
    TypeMirror expressionType = info.getTrees().getTypeMirror(expression);
    
    if (!(Utilities.isValidType(castTo) && Utilities.isValidType(expressionType)) || !info.getTypeUtilities().isCastable(expressionType, castTo)) {
        return null;
    }
    
    List<Fix> fix = Collections.<Fix>singletonList(new FixImpl(info.getJavaSource(), TreePathHandle.create(ifPath, info), TreePathHandle.create(expression, info), TypeMirrorHandle.create(castTo), Utilities.getName(castTo)));
    String displayName = NbBundle.getMessage(DeclarationForInstanceOf.class, "ERR_DeclarationForInstanceof");
    ErrorDescription err = ErrorDescriptionFactory.createErrorDescription(Severity.HINT, displayName, fix, info.getFileObject(), offset, offset);

    return Collections.singletonList(err);
}
 
Example #19
Source File: DependencyCollector.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * instanceof adds dependency on the literal type
 */
@Override
public Object visitInstanceOf(InstanceOfTree node, Object p) {
    addDependency(node.getType());
    return super.visitInstanceOf(node, p);
}
 
Example #20
Source File: ExpressionScanner.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<Tree> visitInstanceOf(InstanceOfTree node, ExpressionScanner.ExpressionsInfo p) {
    return scan(node.getExpression(), node.getType(), p);
}
 
Example #21
Source File: InstanceOfTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddInstanceOf() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (true) {\n" + 
        "        }\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String) {\n" +
        "        }\n" +
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            IfTree ift = (IfTree) method.getBody().getStatements().get(0);
            ExpressionTree condition = ((ParenthesizedTree) ift.getCondition()).getExpression();
            InstanceOfTree nue = make.InstanceOf(make.Identifier("o"), make.QualIdent("java.lang.String"));
            workingCopy.rewrite(condition, nue);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example #22
Source File: InstanceOfTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testRemoveVariableName() throws Exception {
    if (!typeTestPatternAvailable())
        return ;

    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String t) {\n" + 
        "        }\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String) {\n" +
        "        }\n" +
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            IfTree ift = (IfTree) method.getBody().getStatements().get(0);
            InstanceOfTree it = (InstanceOfTree) ((ParenthesizedTree) ift.getCondition()).getExpression();
            InstanceOfTree nue = make.InstanceOf(it.getExpression(), it.getType());
            workingCopy.rewrite(it, nue);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example #23
Source File: InstanceOfTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddVariableName() throws Exception {
    if (!typeTestPatternAvailable())
        return ;

    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String) {\n" + 
        "        }\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String t) {\n" +
        "        }\n" +
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            IfTree ift = (IfTree) method.getBody().getStatements().get(0);
            InstanceOfTree it = (InstanceOfTree) ((ParenthesizedTree) ift.getCondition()).getExpression();
            InstanceOfTree nue = make.InstanceOf(it.getExpression(), make.BindingPattern("t", it.getType()));
            workingCopy.rewrite(it, nue);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example #24
Source File: UTemplater.java    From Refaster with Apache License 2.0 4 votes vote down vote up
@Override
public UInstanceOf visitInstanceOf(InstanceOfTree tree, Void v) {
  return UInstanceOf.create(template(tree.getExpression()), template(tree.getType()));
}
 
Example #25
Source File: UInstanceOf.java    From Refaster with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public Unifier visitInstanceOf(InstanceOfTree instanceOf, @Nullable Unifier unifier) {
  unifier = getExpression().unify(instanceOf.getExpression(), unifier);
  return getType().unify(instanceOf.getType(), unifier);
}
 
Example #26
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 4 votes vote down vote up
@Override
public CodeModel visitInstanceOf(InstanceOfTree node, VisitContext p) {
  ExpressionModel classModel = scan(node.getExpression(), p);
  TypeElement type = (TypeElement) ((JCTree.JCIdent) node.getType()).sym;
  return classModel.onInstanceOf(type);
}
 
Example #27
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 votes vote down vote up
@Override public Object visitInstanceOf(InstanceOfTree node, Object p) { return null; }