Java Code Examples for com.sun.tools.javac.tree.JCTree#JCMethodDecl

The following examples show how to use com.sun.tools.javac.tree.JCTree#JCMethodDecl . 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: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateDeleteTable(JavacTreeMaker maker, JavacNode tableElement, Set<String> allStaticMethodNames, String tableClassName) {
  final String callClassName = CLASS_DELETE_TABLE;
  final String methodName = METHOD_DELETE_TABLE;
  final String invokeKey = getCreateInvokeKey(callClassName, tableClassName);
  if (!allStaticMethodNames.contains(methodName)) {
    final JCTree.JCAnnotation invokesAnnotation = maker.Annotation(chainDotsString(tableElement, Invokes.class.getCanonicalName()),
        List.<JCTree.JCExpression>of(maker.Literal(invokeKey)));
    final JCTree.JCModifiers mods = maker.Modifiers(PUBLIC_STATIC, List.of(invokesAnnotation));
    final Name name = tableElement.toName(methodName);
    final JCTree.JCExpression returnType = getMagicMethodReturnType(tableElement, callClassName, tableClassName);
    final JCTree.JCBlock body = defaultMagicMethodBody(maker, tableElement);
    final JCTree.JCMethodDecl method = maker.MethodDef(mods, name, returnType,
        List.<JCTree.JCTypeParameter>nil(),
        List.<JCTree.JCVariableDecl>nil(),
        List.<JCTree.JCExpression>nil(),
        body,
        null);
    injectMethod(tableElement, recursiveSetGeneratedBy(method, tableElement.get(), tableElement.getContext()));
  }
}
 
Example 2
Source File: TypeAnnotationsPretty.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void runMethod(String code) throws IOException {
    String src = prefix +
            code + "}" +
            postfix;

    try (JavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
                null, Arrays.asList(new MyFileObject(src)));


        for (CompilationUnitTree cut : ct.parse()) {
            JCTree.JCMethodDecl meth =
                    (JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
            checkMatch(code, meth);
        }
    }
}
 
Example 3
Source File: SourceAnalyzerFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
@CheckForNull
public Void visitMethod(@NonNull final MethodTree node, @NonNull final Map<Pair<BinaryName,String>, UsagesData<String>> p) {
    Element old = enclosingElement;
    try {
        enclosingElement = ((JCTree.JCMethodDecl) node).sym;
        if (enclosingElement != null && enclosingElement.getKind() == ElementKind.METHOD) {
            mainMethod |= SourceUtils.isMainMethod((ExecutableElement) enclosingElement);
            // do not add idents for constructors, they always match their class' name, which is added as an ident separately
            addIdent(activeClass.peek(), node.getName(), p, true);
        }
        return super.visitMethod(node, p);
    } finally {
        enclosingElement = old;
    }
}
 
Example 4
Source File: CompleteWord.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private void collectFromMethod(Editor editor, String incomplete, List<SuggestItem> result,
                               JCTree.JCMethodDecl method) {
    //add field from start position of method to the cursor
    List<JCTree.JCStatement> statements
            = method.getBody().getStatements();
    for (JCTree.JCStatement statement : statements) {
        if (statement instanceof JCTree.JCVariableDecl) {
            JCTree.JCVariableDecl field = (JCTree.JCVariableDecl) statement;
            addVariable(field, editor, incomplete, result);
        }
    }
    //add params
    List<JCTree.JCVariableDecl> parameters = method.getParameters();
    for (JCTree.JCVariableDecl parameter : parameters) {
        addVariable(parameter, editor, incomplete, result);
    }

}
 
Example 5
Source File: JavaParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void addMethod(@NonNull JCCompilationUnit unit,
                       @NonNull ClassDescription clazz,
                       @NonNull JCTree.JCMethodDecl member) {


    final String methodName = member.getName().toString();
    final int modifiers = JavaUtil.toJavaModifiers(member.getModifiers().getFlags());

    final List<IClass> methodParameters = new ArrayList<>();
    List<JCTree.JCVariableDecl> parameters = member.getParameters();
    for (JCTree.JCVariableDecl parameter : parameters) {
        JCTree type = parameter.getType();
        IClass paramType = JavaUtil.jcTypeToClass(unit, type);
        methodParameters.add(paramType);
    }

    IClass returnType = JavaUtil.jcTypeToClass(unit, member.getReturnType());

    if (member.getName().toString().equals(CONSTRUCTOR_NAME)) {
        ConstructorDescription constructor = new ConstructorDescription(
                clazz.getFullClassName(),
                methodParameters);
        clazz.addConstructor(constructor);
    } else {
        MethodDescription methodDescription = new MethodDescription(
                methodName,
                modifiers,
                methodParameters,
                returnType);
        clazz.addMethod(methodDescription);
    }
}
 
Example 6
Source File: ManAttr_8.java    From manifold with Apache License 2.0 5 votes vote down vote up
public void visitMethodDef( JCTree.JCMethodDecl tree )
{
  _methodDefs.push( tree );
  try
  {
    super.visitMethodDef( tree );
  }
  finally
  {
    _methodDefs.pop();
  }
}
 
Example 7
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void verifySelfOnThis( JCTree annotated, JCTree.JCAnnotation selfAnno )
{
  String fqn;
  if( annotated instanceof JCTree.JCAnnotatedType )
  {
    fqn = ((JCTree.JCAnnotatedType)annotated).getUnderlyingType().type.tsym.getQualifiedName().toString();
  }
  else if( annotated instanceof JCTree.JCMethodDecl )
  {
    fqn = ((JCTree.JCMethodDecl)annotated).getReturnType().type.tsym.getQualifiedName().toString();
  }
  else
  {
    //## todo: shouldn't happen
    return;
  }

  try
  {
    JCTree.JCClassDecl enclosingClass = _tp.getClassDecl( annotated );
    if( !isDeclaringClassOrExtension( annotated, fqn, enclosingClass ) && !fqn.equals( "Array" ) )
    {
      _tp.report( selfAnno, Diagnostic.Kind.ERROR,
        ExtIssueMsg.MSG_SELF_NOT_ON_CORRECT_TYPE.get( fqn, enclosingClass.sym.getQualifiedName() ) );
    }
  }
  catch( Throwable ignore )
  {
  }
}
 
Example 8
Source File: CompleteWord.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void getPossibleResult(Editor editor, List<SuggestItem> result,
                               JCTree.JCCompilationUnit ast, String incomplete) {
    if (ast == null) {
        return;
    }
    //current file declare
    List<JCTree> typeDecls = ast.getTypeDecls();
    if (typeDecls.isEmpty()) {
        return;
    }
    JCTree jcTree = typeDecls.get(0);
    if (jcTree instanceof JCTree.JCClassDecl) {
        List<JCTree> members =
                ((JCTree.JCClassDecl) jcTree).getMembers();
        for (JCTree member : members) {
            if (member instanceof JCTree.JCVariableDecl) {
                addVariable((JCTree.JCVariableDecl) member, editor, incomplete, result);
            } else if (member instanceof JCTree.JCMethodDecl) {
                JCTree.JCMethodDecl method = (JCTree.JCMethodDecl) member;
                addMethod(method, editor, incomplete, result);

                //if the cursor in method scope
                if (method.getStartPosition() <= editor.getCursor()
                        && method.getBody().getEndPosition(ast.endPositions) >= editor.getCursor()) {
                    collectFromMethod(editor, incomplete, result, method);
                }
            }
        }
    }
}
 
Example 9
Source File: TypeAnnotationsPretty.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void runMethod(String code) throws IOException {
    String src = prefix +
            code + "}" +
            postfix;

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));


    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCMethodDecl meth =
                (JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
        checkMatch(code, meth);
    }
}
 
Example 10
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
private Set<String> findAllMethodNames(JavacNode typeNode) {
  Set<String> methodNames = new LinkedHashSet<>();
  for (JavacNode child : typeNode.down()) {
    if (child.getKind() != AST.Kind.METHOD) continue;
    JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl) child.get();
    long methodFlags = methodDecl.mods.flags;
    //Skip static methods
    if ((methodFlags & Flags.STATIC) != 0) continue;
    methodNames.add(child.getName());
  }
  return methodNames;
}
 
Example 11
Source File: JavaParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private IClass parseClass(JCCompilationUnit unit, JCClassDecl classDecl) {
    final String className = unit.getPackageName() + DOT + classDecl.getSimpleName();
    final int modifiers = JavaUtil.toJavaModifiers(classDecl.getModifiers().getFlags());

    ClassDescription clazz = new ClassDescription(
            className,
            modifiers,
            false,
            classDecl.getKind() == Tree.Kind.ANNOTATION_TYPE,
            classDecl.getKind() == Tree.Kind.ENUM);

    IClass extendsClass = JavaUtil.jcTypeToClass(unit, classDecl.getExtendsClause());
    if (extendsClass != null) {
        clazz.setSuperclass(extendsClass);
    } else {
        clazz.setSuperclass(JavaClassManager.getInstance().getParsedClass(Object.class.getName()));
    }


    List<JCTree> members = classDecl.getMembers();
    for (JCTree member : members) {
        if (member instanceof JCTree.JCMethodDecl) {
            addMethod(unit, clazz, (JCTree.JCMethodDecl) member);
        } else if (member instanceof JCTree.JCVariableDecl) {
            addVariable(unit, clazz, classDecl, (JCTree.JCVariableDecl) member);
        }
    }
    //now add constructor
    //add methods
    return clazz;
}
 
Example 12
Source File: TypeAnnotationsPretty.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private void runMethod(String code) throws IOException {
    String src = prefix +
            code + "}" +
            postfix;

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));


    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCMethodDecl meth =
                (JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
        checkMatch(code, meth);
    }
}
 
Example 13
Source File: JavaPluginUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static boolean isSynthetic(CompilationInfo info, CompilationUnitTree cut, Tree leaf) throws NullPointerException {
    JCTree tree = (JCTree) leaf;
    
    if (tree.pos == (-1))
        return true;
    
    if (leaf.getKind() == Kind.METHOD) {
        //check for synthetic constructor:
        return (((JCTree.JCMethodDecl)leaf).mods.flags & Flags.GENERATEDCONSTR) != 0L;
    }
    
    //check for synthetic superconstructor call:
    if (leaf.getKind() == Kind.EXPRESSION_STATEMENT) {
        ExpressionStatementTree est = (ExpressionStatementTree) leaf;
        
        if (est.getExpression().getKind() == Kind.METHOD_INVOCATION) {
            MethodInvocationTree mit = (MethodInvocationTree) est.getExpression();
            
            if (mit.getMethodSelect().getKind() == Kind.IDENTIFIER) {
                IdentifierTree it = (IdentifierTree) mit.getMethodSelect();
                
                if ("super".equals(it.getName().toString())) {
                    SourcePositions sp = info.getTrees().getSourcePositions();
                    
                    return sp.getEndPosition(cut, leaf) == (-1);
                }
            }
        }
    }
    
    return false;
}
 
Example 14
Source File: VanillaPartialReparser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public BlockTree reattrMethodBody(Context context, Scope scope, MethodTree methodToReparse, BlockTree block) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Attr attr = Attr.instance(context);
//        assert ((JCTree.JCMethodDecl)methodToReparse).localEnv != null;
        JCTree.JCMethodDecl tree = (JCTree.JCMethodDecl) methodToReparse;
        final Names names = Names.instance(context);
        final Symtab syms = Symtab.instance(context);
        final TypeEnter typeEnter = TypeEnter.instance(context);
        final Log log = Log.instance(context);
        final TreeMaker make = TreeMaker.instance(context);
        final Env<AttrContext> env = ((JavacScope) scope).getEnv();//this is a copy anyway...
        final Symbol.ClassSymbol owner = env.enclClass.sym;
        if (tree.name == names.init && !owner.type.isErroneous() && owner.type != syms.objectType) {
            JCTree.JCBlock body = tree.body;
            if (body.stats.isEmpty() || !TreeInfo.isSelfCall(body.stats.head)) {
                body.stats = body.stats.
                prepend(make.at(body.pos).Exec(make.Apply(com.sun.tools.javac.util.List.nil(), make.Ident(names._super), com.sun.tools.javac.util.List.nil())));
            } else if ((env.enclClass.sym.flags() & Flags.ENUM) != 0 &&
                (tree.mods.flags & Flags.GENERATEDCONSTR) == 0 &&
                TreeInfo.isSuperCall(body.stats.head)) {
                // enum constructors are not allowed to call super
                // directly, so make sure there aren't any super calls
                // in enum constructors, except in the compiler
                // generated one.
                log.error(tree.body.stats.head.pos(),
                          new JCDiagnostic.Error("compiler",
                                    "call.to.super.not.allowed.in.enum.ctor",
                                    env.enclClass.sym));
                    }
        }
        attr.attribStat((JCTree.JCBlock)block, env);
        return block;
    }
 
Example 15
Source File: SingletonJavacHandler.java    From tutorials with MIT License 5 votes vote down vote up
private void addPrivateConstructor(JavacNode singletonClass, JavacTreeMaker singletonTM) {
    JCTree.JCModifiers modifiers = singletonTM.Modifiers(Flags.PRIVATE);
    JCTree.JCBlock block = singletonTM.Block(0L, List.nil());
    JCTree.JCMethodDecl constructor = singletonTM.MethodDef(modifiers, singletonClass.toName("<init>"), null, List.nil(), List.nil(), List.nil(), block, null);

    JavacHandlerUtil.injectMethod(singletonClass, constructor);
}
 
Example 16
Source File: TypeAnnotationsPretty.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void runMethod(String code) throws IOException {
    String src = prefix +
            code + "}" +
            postfix;

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));


    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCMethodDecl meth =
                (JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
        checkMatch(code, meth);
    }
}
 
Example 17
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
/**
 * Issue errors/warnings if an extension method violates extension method grammar or conflicts with an existing method
 */
@Override
public void visitMethodDef( JCTree.JCMethodDecl tree )
{
  if( isBridgeMethod( tree ) )
  {
    // we process bridge methods during Generation, since they don't exist prior to Generation
    _bridgeMethod = true;
  }
  try
  {
    super.visitMethodDef( tree );
  }
  finally
  {
    _bridgeMethod = false;
  }

  if( _tp.isGenerate() )
  {
    // Don't process tree during GENERATE, unless the tree was generated e.g., a bridge method
    return;
  }

  if( tree.sym.owner.isAnonymous() )
  {
    // Keep track of anonymous classes so we can process any bridge methods added to them
    JCTree.JCClassDecl anonymousClassDef = (JCTree.JCClassDecl)_tp.getTreeUtil().getTree( tree.sym.owner );
    _tp.preserveInnerClassForGenerationPhase( anonymousClassDef );
  }

  verifyExtensionMethod( tree );
  result = tree;
}
 
Example 18
Source File: ManTypes.java    From manifold with Apache License 2.0 4 votes vote down vote up
private boolean isSameMethodSym( Symbol memberSym, JCTree.JCMethodDecl methodDef )
{
  return methodDef != null && methodDef.sym != null &&
         isSameType( erasure( methodDef.sym.type ), erasure( memberSym.type ) );
}
 
Example 19
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 4 votes vote down vote up
private boolean isBridgeMethod( JCTree.JCMethodDecl tree )
{
  long modifiers = tree.getModifiers().flags;
  return (Flags.BRIDGE & modifiers) != 0;
}
 
Example 20
Source File: ManAttr.java    From manifold with Apache License 2.0 votes vote down vote up
JCTree.JCMethodDecl peekMethodDef();