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

The following examples show how to use com.sun.tools.javac.tree.JCTree#JCBlock . 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: VanillaPartialReparser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public JCTree.JCBlock reparseMethodBody(Context ctx, CompilationUnitTree topLevel, MethodTree methodToReparse, String newBodyText,
        final Map<JCTree, Object> docComments) throws IllegalArgumentException, IllegalAccessException {
    int startPos = ((JCTree.JCBlock)methodToReparse.getBody()).pos;
    char[] body = new char[startPos + newBodyText.length() + 1];
    Arrays.fill(body, 0, startPos, ' ');
    for (int i = 0; i < newBodyText.length(); i++) {
        body[startPos + i] = newBodyText.charAt(i);
    }
    body[startPos + newBodyText.length()] = '\u0000';
    CharBuffer buf = CharBuffer.wrap(body, 0, body.length - 1);
    com.sun.tools.javac.parser.JavacParser parser = newParser(ctx, buf, ((JCTree.JCBlock)methodToReparse.getBody()).pos, ((JCTree.JCCompilationUnit)topLevel).endPositions);
    final JCTree.JCStatement statement = parser.parseStatement();
    if (statement.getKind() == Tree.Kind.BLOCK) {
        if (docComments != null) {
            docComments.putAll((Map<JCTree, Object>) lazyDocCommentsTable.get(parserDocComments.get(parser)));
        }
        return (JCTree.JCBlock) statement;
    }
    return null;
}
 
Example 2
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateMethod(JavacTreeMaker maker, JavacNode tableElement, Set<String> allMethodNames, String methodName, String callClassName, String tableClassName) {
  final String invokeKey = getCreateInvokeKey(callClassName, tableClassName);
  if (!allMethodNames.contains(methodName)) {
    final JCTree.JCAssign value = maker.Assign(maker.Ident(tableElement.toName("value")),
        maker.Literal(invokeKey));
    final JCTree.JCAssign useThisAsOnlyParam = maker.Assign(maker.Ident(tableElement.toName("useThisAsOnlyParam")),
        maker.Literal(true));
    final JCTree.JCAnnotation invokesAnnotation = maker.Annotation(chainDotsString(tableElement, Invokes.class.getCanonicalName()),
        List.<JCTree.JCExpression>of(value, useThisAsOnlyParam));
    final JCTree.JCModifiers mods = maker.Modifiers(PUBLIC_FINAL, 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 3
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateBulkMethod(JavacTreeMaker maker, JavacNode tableElement,
                                Set<String> allStaticMethodNames, String methodName,
                                String callClassName, String tableClassName,
                                CollectionType collectionType) {
  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.JCExpression tableClassType = chainDotsString(tableElement, tableElement.getPackageDeclaration() + "." + tableClassName);
    final JCTree.JCExpression paramType = maker.TypeApply(collectionType.genericType(tableElement), List.of(tableClassType));
    long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, tableElement.getContext());
    final JCTree.JCVariableDecl param = maker.VarDef(maker.Modifiers(flags), tableElement.toName("o"), paramType, null);
    final JCTree.JCBlock body = defaultMagicMethodBody(maker, tableElement);
    final JCTree.JCMethodDecl method = maker.MethodDef(mods, name, returnType,
        List.<JCTree.JCTypeParameter>nil(),
        List.of(param),
        List.<JCTree.JCExpression>nil(),
        body,
        null);
    injectMethod(tableElement, recursiveSetGeneratedBy(method, tableElement.get(), tableElement.getContext()));
  }
}
 
Example 4
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 5
Source File: SampleJavacPlugin.java    From tutorials with MIT License 6 votes vote down vote up
private static JCTree.JCBlock createIfBlock(TreeMaker factory, Names symbolsTable, VariableTree parameter) {
    String parameterName = parameter.getName().toString();
    Name parameterId = symbolsTable.fromString(parameterName);
    
    String errorMessagePrefix = String.format("Argument '%s' of type %s is marked by @%s but got '", 
      parameterName, parameter.getType(), Positive.class.getSimpleName());
    String errorMessageSuffix = "' for it";
    
    return factory.Block(0, com.sun.tools.javac.util.List.of(
      factory.Throw(
        factory.NewClass(null, nil(), 
          factory.Ident(symbolsTable.fromString(IllegalArgumentException.class.getSimpleName())),
            com.sun.tools.javac.util.List.of(factory.Binary(JCTree.Tag.PLUS, 
              factory.Binary(JCTree.Tag.PLUS, factory.Literal(TypeTag.CLASS, errorMessagePrefix), 
                factory.Ident(parameterId)), 
                factory.Literal(TypeTag.CLASS, errorMessageSuffix))), null))));
}
 
Example 6
Source File: GenerateGetMethodProcessor.java    From java-master with Apache License 2.0 5 votes vote down vote up
private JCTree.JCMethodDecl createGetterMethodDecl(JCTree.JCVariableDecl jcVariableDecl) {

        ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
        statements.append(treeMaker.Return(treeMaker.Select(treeMaker.Ident(names.fromString("this")), jcVariableDecl.getName())));
        JCTree.JCBlock body = treeMaker.Block(0, statements.toList());
        return treeMaker.MethodDef(treeMaker.Modifiers(Flags.PUBLIC), getNewMethodName(jcVariableDecl.getName()),
                jcVariableDecl.vartype, List.nil(), List.nil(), List.nil(), body, null);
    }
 
Example 7
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 8
Source File: JavaParserVisitor.java    From rewrite with Apache License 2.0 5 votes vote down vote up
@Override
public J visitLambdaExpression(LambdaExpressionTree node, Formatting fmt) {
    var parenthesized = source.charAt(cursor) == '(';
    skip("(");

    List<Expression> paramList;
    if (parenthesized && node.getParameters().isEmpty()) {
        paramList = singletonList(new J.Empty(randomId(), format(sourceBefore(")"))));
    } else {
        paramList = convertAll(node.getParameters(), commaDelim,
                t -> parenthesized ? sourceBefore(")") : "");
    }

    var params = new J.Lambda.Parameters(randomId(), parenthesized, paramList);
    var arrow = new J.Lambda.Arrow(randomId(), format(sourceBefore("->")));

    J body;
    if (node.getBody() instanceof JCTree.JCBlock) {
        var prefix = sourceBefore("{");
        cursor--;
        body = convert(node.getBody());
        body = body.withPrefix(prefix);
    } else {
        body = convert(node.getBody());
    }

    return new J.Lambda(randomId(),
            params,
            arrow,
            body,
            type(node),
            fmt
    );
}
 
Example 9
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private static void analyzeTry(SourceContext context, JCTree.JCTry tryExpr) throws IOException {
  JCTree.JCBlock block = tryExpr.getBlock();
  List<JCTree> resources = tryExpr.getResources();
  List<JCTree.JCCatch> catches = tryExpr.getCatches();
  JCTree.JCBlock lyBlock = tryExpr.getFinallyBlock();

  if (nonNull(resources)) {
    for (JCTree resource : resources) {
      analyzeParsedTree(context, resource);
    }
  }

  analyzeParsedTree(context, block);

  if (nonNull(catches)) {

    for (JCTree.JCCatch jcCatch : catches) {

      JCTree.JCVariableDecl parameter = jcCatch.getParameter();
      analyzeParsedTree(context, parameter);

      JCTree.JCBlock catchBlock = jcCatch.getBlock();
      analyzeParsedTree(context, catchBlock);
    }
  }

  analyzeParsedTree(context, lyBlock);
}
 
Example 10
Source File: SingletonJavacHandler.java    From tutorials with MIT License 5 votes vote down vote up
private void addFactoryMethod(JavacNode singletonClass, JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) {
    JCTree.JCModifiers modifiers = singletonClassTreeMaker.Modifiers(Flags.PUBLIC | Flags.STATIC);

    JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get();
    JCTree.JCIdent singletonClassType = singletonClassTreeMaker.Ident(singletonClassDecl.name);

    JCTree.JCBlock block = addReturnBlock(singletonClassTreeMaker, holderInnerClass);

    JCTree.JCMethodDecl factoryMethod = singletonClassTreeMaker.MethodDef(modifiers, singletonClass.toName("getInstance"), singletonClassType, List.nil(), List.nil(), List.nil(), block, null);
    JavacHandlerUtil.injectMethod(singletonClass, factoryMethod);
}
 
Example 11
Source File: SingletonJavacHandler.java    From tutorials with MIT License 5 votes vote down vote up
private JCTree.JCBlock addReturnBlock(JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) {

        JCTree.JCClassDecl holderInnerClassDecl = (JCTree.JCClassDecl) holderInnerClass.get();
        JavacTreeMaker holderInnerClassTreeMaker = holderInnerClass.getTreeMaker();
        JCTree.JCIdent holderInnerClassType = holderInnerClassTreeMaker.Ident(holderInnerClassDecl.name);

        JCTree.JCFieldAccess instanceVarAccess = holderInnerClassTreeMaker.Select(holderInnerClassType, holderInnerClass.toName("INSTANCE"));
        JCTree.JCReturn returnValue = singletonClassTreeMaker.Return(instanceVarAccess);

        ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
        statements.append(returnValue);

        return singletonClassTreeMaker.Block(0L, statements.toList());
    }
 
Example 12
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 13
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 4 votes vote down vote up
private static JCTree.JCBlock defaultMagicMethodBody(JavacTreeMaker maker, JavacNode tableElement) {
  JCTree.JCExpression exType = genTypeRef(tableElement, RuntimeException.class.getCanonicalName());
  JCTree.JCExpression exception = maker.NewClass(null, List.<JCTree.JCExpression>nil(), exType, List.<JCTree.JCExpression>of(maker.Literal(ERROR_PROCESSOR_DID_NOT_RUN)), null);
  final JCTree.JCStatement statement = maker.Throw(exception);
  return maker.Block(0, List.of(statement));
}
 
Example 14
Source File: SampleJavacPlugin.java    From tutorials with MIT License 4 votes vote down vote up
private void addCheck(MethodTree method, VariableTree parameter, Context context) {
    JCTree.JCIf check = createCheck(parameter, context);
    JCTree.JCBlock body = (JCTree.JCBlock) method.getBody();
    body.stats = body.stats.prepend(check);
}