Java Code Examples for com.sun.source.tree.ClassTree#getImplementsClause()

The following examples show how to use com.sun.source.tree.ClassTree#getImplementsClause() . 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: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeClass(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ClassTree ct = (ClassTree) parent.getLeaf();
    
    if (ct.getExtendsClause() == error) {
        types.add(ElementKind.CLASS);
        return null;
    }
    
    for (Tree t : ct.getImplementsClause()) {
        if (t == error) {
            types.add(ElementKind.INTERFACE);
            return null;
        }
    }
    
    //XXX: annotation types...
    
    return null;
}
 
Example 2
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeClass(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ClassTree ct = (ClassTree) parent.getLeaf();
    
    if (ct.getExtendsClause() == error) {
        types.add(ElementKind.CLASS);
        return null;
    }
    
    for (Tree t : ct.getImplementsClause()) {
        if (t == error) {
            types.add(ElementKind.INTERFACE);
            return null;
        }
    }
    
    //XXX: annotation types...
    
    return null;
}
 
Example 3
Source File: ComputeImports.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitClass(ClassTree node, Map<String, Object> p) {
    if (getCurrentPath().getParentPath().getLeaf().getKind() != Kind.NEW_CLASS) {
        filterByAcceptedKind(node.getExtendsClause(), ElementKind.CLASS);
        for (Tree intf : node.getImplementsClause()) {
            filterByAcceptedKind(intf, ElementKind.INTERFACE, ElementKind.ANNOTATION_TYPE);
        }
    }

    scan(node.getModifiers(), p);
    scan(node.getTypeParameters(), p, true);
    scan(node.getExtendsClause(), p, true);
    scan(node.getImplementsClause(), p, true);
    scan(node.getMembers(), p);

    return null;
}
 
Example 4
Source File: JavadocUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isInHeader(CompilationInfo info, ClassTree tree, int offset) {
    CompilationUnitTree cut = info.getCompilationUnit();
    SourcePositions sp = info.getTrees().getSourcePositions();
    long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
    
    List<? extends Tree> impls = tree.getImplementsClause();
    List<? extends TypeParameterTree> typeparams;
    if (impls != null && !impls.isEmpty()) {
        lastKnownOffsetInHeader= sp.getEndPosition(cut, impls.get(impls.size() - 1));
    } else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
        lastKnownOffsetInHeader= sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
    } else if (tree.getExtendsClause() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getExtendsClause());
    } else if (tree.getModifiers() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
    }
    
    TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
    
    ts.move((int) lastKnownOffsetInHeader);
    
    while (ts.moveNext()) {
        if (ts.token().id() == JavaTokenId.LBRACE) {
            return offset < ts.offset();
        }
    }
    
    return false;
}
 
Example 5
Source File: InterfaceValidator.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void onTypeDeclared(TypeElement type, TreePath path) {
  if (type.getKind() == ElementKind.ANNOTATION_TYPE
      && !ruleInfo.ruleIsRequiredForSourceOnlyAbi()) {
    trees.printMessage(
        messageKind,
        String.format(
            "Annotation definitions must be in rules with required_for_source_only_abi = True.\n"
                + "For a quick fix, add required_for_source_only_abi = True to %s.\n"
                + "A better fix is to move %s to a new rule that contains only\n"
                + "annotations, and mark that rule required_for_source_only_abi.\n",
            ruleInfo.getRuleName(), type.getSimpleName()),
        path.getLeaf(),
        path.getCompilationUnit());
  }

  ClassTree classTree = (ClassTree) path.getLeaf();

  // The compiler can handle superclasses and interfaces that are outright missing
  // (because it is possible for those to be generated by annotation processors).
  // However, if a superclass or interface is present, the compiler expects
  // the entire class hierarchy of that class/interface to also be present, and
  // gives a sketchy error if they are missing.
  Tree extendsClause = classTree.getExtendsClause();
  if (extendsClause != null) {
    ensureAbsentOrComplete(type.getSuperclass(), new TreePath(path, extendsClause));
  }

  List<? extends Tree> implementsClause = classTree.getImplementsClause();
  if (implementsClause != null) {
    List<? extends TypeMirror> interfaces = type.getInterfaces();
    for (int i = 0; i < implementsClause.size(); i++) {
      ensureAbsentOrComplete(interfaces.get(i), new TreePath(path, implementsClause.get(i)));
    }
  }
}
 
Example 6
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
public void visitClassDeclaration(ClassTree node) {
    sync(node);
    List<Op> breaks =
            visitModifiers(node.getModifiers(), Direction.VERTICAL, Optional.<BreakTag>absent());
    boolean hasSuperclassType = node.getExtendsClause() != null;
    boolean hasSuperInterfaceTypes = !node.getImplementsClause().isEmpty();
    builder.addAll(breaks);
    token(node.getKind() == Tree.Kind.INTERFACE ? "interface" : "class");
    builder.space();
    visit(node.getSimpleName());
    if (!node.getTypeParameters().isEmpty()) {
        token("<");
    }
    builder.open(plusFour);
    {
        if (!node.getTypeParameters().isEmpty()) {
            typeParametersRest(
                    node.getTypeParameters(),
                    hasSuperclassType || hasSuperInterfaceTypes ? plusFour : ZERO);
        }
        if (hasSuperclassType) {
            builder.breakToFill(" ");
            token("extends");
            builder.space();
            scan(node.getExtendsClause(), null);
        }
        if (hasSuperInterfaceTypes) {
            builder.breakToFill(" ");
            builder.open(node.getImplementsClause().size() > 1 ? plusFour : ZERO);
            token(node.getKind() == Tree.Kind.INTERFACE ? "extends" : "implements");
            builder.space();
            boolean first = true;
            for (Tree superInterfaceType : node.getImplementsClause()) {
                if (!first) {
                    token(",");
                    builder.breakOp(" ");
                }
                scan(superInterfaceType, null);
                first = false;
            }
            builder.close();
        }
    }
    builder.close();
    if (node.getMembers() == null) {
        token(";");
    } else {
        addBodyDeclarations(node.getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
    dropEmptyDeclarations();
}
 
Example 7
Source File: ImplementMethods.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
@Messages({
    "# {0} - the FQN of the type whose methods will be implemented",
    "ERR_ImplementMethods=Implement unimplemented abstract methods of {0}"
})
public static ErrorDescription implementMethods(HintContext ctx) {
    ClassTree clazz = (ClassTree) ctx.getPath().getLeaf();
    Element typeEl = ctx.getInfo().getTrees().getElement(ctx.getPath());
    
    if (typeEl == null || !typeEl.getKind().isClass())
        return null;
    
    List<Tree> candidate = new ArrayList<Tree>(clazz.getImplementsClause());
    
    candidate.add(clazz.getExtendsClause());
    
    Tree found = null;
    
    for (Tree cand : candidate) {
        if (   ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getInfo().getCompilationUnit(), cand) <= ctx.getCaretLocation()
            && ctx.getCaretLocation() <= ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getInfo().getCompilationUnit(), cand)) {
            found = cand;
            break;
        }
    }
    
    if (found == null) return null;
    
    TreePath foundPath = new TreePath(ctx.getPath(), found);
    Element supertype = ctx.getInfo().getTrees().getElement(foundPath);
    
    if (supertype == null || (!supertype.getKind().isClass() && !supertype.getKind().isInterface()))
        return null;
    
    List<ExecutableElement> unimplemented = computeUnimplemented(ctx.getInfo(), typeEl, supertype);
    
    if (!unimplemented.isEmpty()) {
        return ErrorDescriptionFactory.forName(ctx, foundPath, Bundle.ERR_ImplementMethods(((TypeElement) supertype).getQualifiedName().toString()), new ImplementFix(ctx.getInfo(), ctx.getPath(), (TypeElement) typeEl, (TypeElement) supertype).toEditorFix());
    }
    
    return null;
}
 
Example 8
Source File: MethodGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
public static void deleteMethod(final FileObject implClass, final String operationName) throws IOException{
    JavaSource targetSource = JavaSource.forFileObject(implClass);
    CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>() {
        @Override
        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.ELEMENTS_RESOLVED);
            //workingCopy.toPhase(Phase.ELEMENTS_RESOLVED);
            ClassTree javaClass = SourceUtils.getPublicTopLevelTree(workingCopy);
            if (javaClass!=null) {
                ExecutableElement method = new MethodVisitor(workingCopy).
                    getMethod( operationName);
                TreeMaker make  = workingCopy.getTreeMaker();
                if(method != null){
                    MethodTree methodTree = workingCopy.getTrees().getTree(
                            method);
                    ClassTree modifiedJavaClass = make.removeClassMember(
                            javaClass, methodTree);
                    workingCopy.rewrite(javaClass, modifiedJavaClass);
                    boolean removeImplementsClause = false;
                    //find out if there are no more exposed operations, if so remove the implements clause
                    if(! new MethodVisitor(workingCopy).hasPublicMethod()){
                        removeImplementsClause = true;
                    }
                
                    if(removeImplementsClause){
                        //TODO: need to remove implements clause on the SEI
                        //for now all implements are being remove
                        List<? extends Tree> implementeds = javaClass.
                            getImplementsClause();
                        for(Tree implemented : implementeds) {
                            modifiedJavaClass = make.
                                removeClassImplementsClause(modifiedJavaClass, 
                                        implemented);
                        }
                        workingCopy.rewrite(javaClass, modifiedJavaClass);
                    }
                }
            }
        }
        //}
        public void cancel() {
        }
    };
    targetSource.runModificationTask(task).commit();
    DataObject dobj = DataObject.find(implClass);
    if (dobj!=null) {
        SaveCookie cookie = dobj.getCookie(SaveCookie.class);
        if (cookie!=null) cookie.save();
    }
}
 
Example 9
Source File: EntityResourcesGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void generateResourceMethods( FileObject fileObject , 
        final String entityFQN, final String idClass) throws IOException 
{
    JavaSource javaSource = JavaSource.forFileObject( fileObject );
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        
        @Override
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree tree = workingCopy.getCompilationUnit();
            
            ClassTree classTree = (ClassTree)tree.getTypeDecls().get(0);
            TypeElement classElement = (TypeElement)workingCopy.getTrees().
                getElement(TreePath.getPath( tree, classTree));
            
            List<String> imports = getResourceImports( entityFQN );
            JavaSourceHelper.addImports(workingCopy, imports.toArray(
                    new String[ imports.size()]));
            
            GenerationUtils genUtils = GenerationUtils.newInstance(workingCopy);
            TreeMaker maker = workingCopy.getTreeMaker();
            
            List<Tree> members = new ArrayList<Tree>(classTree.getMembers());
            // make empty CTOR
            MethodTree constructor = maker.Constructor(
                    genUtils.createModifiers(Modifier.PUBLIC),
                    Collections.<TypeParameterTree>emptyList(),
                    Collections.<VariableTree>emptyList(),
                    Collections.<ExpressionTree>emptyList(),
                    "{}");                                      //NOI18N
            members.add(constructor);
            
            List<RestGenerationOptions> restGenerationOptions = 
                getRestFacadeMethodOptions(entityFQN, idClass);
            
            for(RestGenerationOptions option: restGenerationOptions) {
                generateRestMethod(classElement, genUtils, maker, members,
                        option);
            }
            
            ModifiersTree modifiersTree = addResourceAnnotation(entityFQN,
                    classTree, genUtils, maker);
            
            // final step : generate new class tree
            List<Tree> implementsClause = new ArrayList<Tree>(
                    classTree.getImplementsClause());
            ClassTree newClassTree = maker.Class(
                    modifiersTree,
                    classTree.getSimpleName(),
                    classTree.getTypeParameters(),
                    classTree.getExtendsClause(),
                    implementsClause,
                    members);

            workingCopy.rewrite(classTree, newClassTree);
        }

    };
    javaSource.runModificationTask(task).commit();
}
 
Example 10
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
public void visitClassDeclaration(ClassTree node) {
    sync(node);
    List<Op> breaks =
            visitModifiers(node.getModifiers(), Direction.VERTICAL, Optional.<BreakTag>absent());
    boolean hasSuperclassType = node.getExtendsClause() != null;
    boolean hasSuperInterfaceTypes = !node.getImplementsClause().isEmpty();
    builder.addAll(breaks);
    token(node.getKind() == Tree.Kind.INTERFACE ? "interface" : "class");
    builder.space();
    visit(node.getSimpleName());
    if (!node.getTypeParameters().isEmpty()) {
        token("<");
    }
    builder.open(plusFour);
    {
        if (!node.getTypeParameters().isEmpty()) {
            typeParametersRest(
                    node.getTypeParameters(),
                    hasSuperclassType || hasSuperInterfaceTypes ? plusFour : ZERO);
        }
        if (hasSuperclassType) {
            builder.breakToFill(" ");
            token("extends");
            builder.space();
            scan(node.getExtendsClause(), null);
        }
        if (hasSuperInterfaceTypes) {
            builder.breakToFill(" ");
            builder.open(node.getImplementsClause().size() > 1 ? plusFour : ZERO);
            token(node.getKind() == Tree.Kind.INTERFACE ? "extends" : "implements");
            builder.space();
            boolean first = true;
            for (Tree superInterfaceType : node.getImplementsClause()) {
                if (!first) {
                    token(",");
                    builder.breakOp(" ");
                }
                scan(superInterfaceType, null);
                first = false;
            }
            builder.close();
        }
    }
    builder.close();
    if (node.getMembers() == null) {
        token(";");
    } else {
        addBodyDeclarations(node.getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
    dropEmptyDeclarations();
}
 
Example 11
Source File: ExtImplsLocationCriterion.java    From annotation-tools with MIT License 4 votes vote down vote up
@Override
public boolean isSatisfiedBy(TreePath path) {
  if (path == null) {
    return false;
  }

  Tree leaf = path.getLeaf();

  // System.out.printf("ExtImplsLocationCriterion.isSatisfiedBy(%s):%n  leaf=%s (%s)%n", path, leaf, leaf.getClass());

  TreePath parentPath = path.getParentPath();
  if (parentPath == null) {
    return false;
  }

  Tree parent = parentPath.getLeaf();
  if (parent == null) {
    return false;
  }

  // System.out.printf("ExtImplsLocationCriterion.isSatisfiedBy(%s):%n  leaf=%s (%s)%n  parent=%s (%s)%n", path, leaf, leaf.getClass(), parent, parent.getClass());

  boolean returnValue = false;

  if (index == -1 && leaf.getKind() == Tree.Kind.CLASS) {
      return ((JCTree.JCClassDecl) leaf).getExtendsClause() == null;
  }
  if (CommonScanner.hasClassKind(parent)) {
      ClassTree ct = (ClassTree) parent;

      if (index==-1) {
          Tree ext = ct.getExtendsClause();
          if (ext == leaf) {
              returnValue = true;
          }
      } else {
          List<? extends Tree> impls = ct.getImplementsClause();
          if (index < impls.size() && impls.get(index) == leaf) {
              returnValue = true;
          }
      }
  }

  if (!returnValue) {
      return this.isSatisfiedBy(parentPath);
  } else {
      return true;
  }
}
 
Example 12
Source File: Java14InputAstVisitor.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
public void visitRecordDeclaration(ClassTree node) {
  sync(node);
  List<Op> breaks =
      visitModifiers(
          node.getModifiers(),
          Direction.VERTICAL,
          /* declarationAnnotationBreak= */ Optional.empty());
  Verify.verify(node.getExtendsClause() == null);
  boolean hasSuperInterfaceTypes = !node.getImplementsClause().isEmpty();
  builder.addAll(breaks);
  token("record");
  builder.space();
  visit(node.getSimpleName());
  if (!node.getTypeParameters().isEmpty()) {
    token("<");
  }
  builder.open(plusFour);
  {
    if (!node.getTypeParameters().isEmpty()) {
      typeParametersRest(node.getTypeParameters(), hasSuperInterfaceTypes ? plusFour : ZERO);
    }
    ImmutableList<JCVariableDecl> parameters =
        compactRecordConstructor(node)
            .map(m -> ImmutableList.copyOf(m.getParameters()))
            .orElseGet(() -> recordVariables(node));
    token("(");
    if (!parameters.isEmpty()) {
      // Break before args.
      builder.breakToFill("");
    }
    // record headers can't declare receiver parameters
    visitFormals(/* receiver= */ Optional.empty(), parameters);
    token(")");
    if (hasSuperInterfaceTypes) {
      builder.breakToFill(" ");
      builder.open(node.getImplementsClause().size() > 1 ? plusFour : ZERO);
      token("implements");
      builder.space();
      boolean first = true;
      for (Tree superInterfaceType : node.getImplementsClause()) {
        if (!first) {
          token(",");
          builder.breakOp(" ");
        }
        scan(superInterfaceType, null);
        first = false;
      }
      builder.close();
    }
  }
  builder.close();
  if (node.getMembers() == null) {
    token(";");
  } else {
    List<Tree> members =
        node.getMembers().stream()
            .filter(t -> (TreeInfo.flags((JCTree) t) & Flags.GENERATED_MEMBER) == 0)
            .collect(toImmutableList());
    addBodyDeclarations(members, BracesOrNot.YES, FirstDeclarationsOrNot.YES);
  }
  dropEmptyDeclarations();
}
 
Example 13
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
public void visitClassDeclaration(ClassTree node) {
  sync(node);
  List<Op> breaks =
      visitModifiers(
          node.getModifiers(),
          Direction.VERTICAL,
          /* declarationAnnotationBreak= */ Optional.empty());
  boolean hasSuperclassType = node.getExtendsClause() != null;
  boolean hasSuperInterfaceTypes = !node.getImplementsClause().isEmpty();
  builder.addAll(breaks);
  token(node.getKind() == Tree.Kind.INTERFACE ? "interface" : "class");
  builder.space();
  visit(node.getSimpleName());
  if (!node.getTypeParameters().isEmpty()) {
    token("<");
  }
  builder.open(plusFour);
  {
    if (!node.getTypeParameters().isEmpty()) {
      typeParametersRest(
          node.getTypeParameters(),
          hasSuperclassType || hasSuperInterfaceTypes ? plusFour : ZERO);
    }
    if (hasSuperclassType) {
      builder.breakToFill(" ");
      token("extends");
      builder.space();
      scan(node.getExtendsClause(), null);
    }
    if (hasSuperInterfaceTypes) {
      builder.breakToFill(" ");
      builder.open(node.getImplementsClause().size() > 1 ? plusFour : ZERO);
      token(node.getKind() == Tree.Kind.INTERFACE ? "extends" : "implements");
      builder.space();
      boolean first = true;
      for (Tree superInterfaceType : node.getImplementsClause()) {
        if (!first) {
          token(",");
          builder.breakOp(" ");
        }
        scan(superInterfaceType, null);
        first = false;
      }
      builder.close();
    }
  }
  builder.close();
  if (node.getMembers() == null) {
    token(";");
  } else {
    addBodyDeclarations(node.getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
  }
  dropEmptyDeclarations();
}