com.sun.tools.javac.tree.JCTree.JCStatement Java Examples

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCStatement. 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: HandleBuilder.java    From EasyMPermission with MIT License 6 votes vote down vote up
private JCMethodDecl generateCleanMethod(java.util.List<BuilderFieldData> builderFields, JavacNode type, JCTree source) {
	JavacTreeMaker maker = type.getTreeMaker();
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	
	for (BuilderFieldData bfd : builderFields) {
		if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
			bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, type, source, statements);
		}
	}
	
	statements.append(maker.Exec(maker.Assign(maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean")), maker.Literal(CTC_BOOLEAN, false))));
	JCBlock body = maker.Block(0, statements.toList());
	return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName("$lombokClean"), maker.Type(Javac.createVoidType(maker, CTC_VOID)), List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
	/*
	 * 		if (shouldReturnThis) {
		methodType = cloneSelfType(field);
	}
	
	if (methodType == null) {
		//WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6.
		methodType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID));
		shouldReturnThis = false;
	}

	 */
}
 
Example #2
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 6 votes vote down vote up
public void visitForLoop(JCForLoop tree) {
	try {
		print("for (");
		if (tree.init.nonEmpty()) {
			if (VARDEF.equals(treeTag(tree.init.head))) {
				printExpr(tree.init.head);
				for (List<JCStatement> l = tree.init.tail; l.nonEmpty(); l = l.tail) {
					JCVariableDecl vdef = (JCVariableDecl)l.head;
					print(", " + vdef.name + " = ");
					printExpr(vdef.init);
				}
			} else {
				printExprs(tree.init);
			}
		}
		print("; ");
		if (tree.cond != null) printExpr(tree.cond);
		print("; ");
		printExprs(tree.step);
		print(") ");
		printStat(tree.body);
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
Example #3
Source File: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void doAnalysis(RewritingContext rewriting) {
    DiagnosticSource prevSource = log.currentSource();
    LocalCacheContext localCacheContext = argumentAttr.withLocalCacheContext();
    try {
        log.useSource(rewriting.env.toplevel.getSourceFile());

        JCStatement treeToAnalyze = (JCStatement)rewriting.originalTree;
        if (rewriting.env.info.scope.owner.kind == Kind.TYP) {
            //add a block to hoist potential dangling variable declarations
            treeToAnalyze = make.Block(Flags.SYNTHETIC, List.of((JCStatement)rewriting.originalTree));
        }

        //TODO: to further refine the analysis, try all rewriting combinations
        deferredAttr.attribSpeculative(treeToAnalyze, rewriting.env, attr.statInfo, new TreeRewriter(rewriting),
                t -> rewriting.diagHandler(), argumentAttr.withLocalCacheContext());
        rewriting.analyzer.process(rewriting.oldTree, rewriting.replacement, rewriting.erroneous);
    } catch (Throwable ex) {
        Assert.error("Analyzer error when processing: " + rewriting.originalTree);
    } finally {
        log.useSource(prevSource.getFile());
        localCacheContext.leave();
    }
}
 
Example #4
Source File: JavacJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
	if (useGuavaInstead(builderType)) {
		guavaMapSingularizer.generateMethods(data, builderType, source, fluent, chain);
		return;
	}
	
	JavacTreeMaker maker = builderType.getTreeMaker();
	
	JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
	generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
	
	returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
	generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
}
 
Example #5
Source File: BlockTemplate.java    From Refaster with Apache License 2.0 6 votes vote down vote up
/**
 * If the tree is a {@link JCBlock}, returns a list of disjoint matches corresponding to
 * the exact list of template statements found consecutively; otherwise, returns an
 * empty list.
 */
@Override
public Iterable<BlockTemplateMatch> match(JCTree tree, Context context) {
  // TODO(lowasser): consider nonconsecutive matches?
  if (tree instanceof JCBlock) {
    JCBlock block = (JCBlock) tree;
    List<JCStatement> targetStatements = ImmutableList.copyOf(block.getStatements());
    ImmutableList.Builder<BlockTemplateMatch> builder = ImmutableList.builder();
    for (int start = 0; start + templateStatements().size() <= targetStatements.size(); 
        start++) {
      int end = start + templateStatements().size();
      Unifier unifier = match(targetStatements.subList(start, end), context);
      if (unifier != null) {
        builder.add(new BlockTemplateMatch(block, unifier, start, end));
        start = end - 1;
      }
    }
    return builder.build();
  }
  return ImmutableList.of();
}
 
Example #6
Source File: JavacJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "add");
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getSingularName())));
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("add", name.toString()));
	JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #7
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 6 votes vote down vote up
public JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception, JCTree source) {
	JavacTreeMaker maker = node.getTreeMaker();
	
	Context context = node.getContext();
	JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source, context);
	JCExpression varType = chainDots(node, exception.split("\\."));
	
	JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL | Flags.PARAMETER), node.toName("$ex"), varType, null);
	JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow");
	JCBlock catchBody = maker.Block(0, List.<JCStatement>of(maker.Throw(maker.Apply(
			List.<JCExpression>nil(), lombokLombokSneakyThrowNameRef,
			List.<JCExpression>of(maker.Ident(node.toName("$ex")))))));
	JCTry tryStatement = maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source, context)), null);
	if (JavacHandlerUtil.inNetbeansEditor(node)) {
		//set span (start and end position) of the try statement and the main block
		//this allows NetBeans to dive into the statement correctly:
		JCCompilationUnit top = (JCCompilationUnit) node.top().get();
		int startPos = contents.head.pos;
		int endPos = Javac.getEndPosition(contents.last().pos(), top);
		tryBlock.pos = startPos;
		tryStatement.pos = startPos;
		Javac.storeEnd(tryBlock, endPos, top);
		Javac.storeEnd(tryStatement, endPos, top);
	}
	return setGeneratedBy(tryStatement, source, context);
}
 
Example #8
Source File: JavacJavaUtilListSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
private List<JCStatement> createListCopy(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	Name thisName = builderType.toName("this");
	
	JCExpression argToUnmodifiable; {
		 // new java.util.ArrayList<Generics>(this.pluralName);
		List<JCExpression> constructorArgs = List.nil();
		JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName());
		constructorArgs = List.<JCExpression>of(thisDotPluralName);
		JCExpression targetTypeExpr = chainDots(builderType, "java", "util", "ArrayList");
		targetTypeExpr = addTypeArgs(1, false, builderType, targetTypeExpr, data.getTypeArgs(), source);
		argToUnmodifiable = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null);
	}
	
	JCStatement unmodifiableStat; {
		// pluralname = Collections.unmodifiableInterfaceType(-newlist-);
		JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiableList"), List.of(argToUnmodifiable));
		unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke));
	}
	
	return List.of(unmodifiableStat);
}
 
Example #9
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private JCStatement makeResourceCloseInvocation(JCExpression resource) {
    // convert to AutoCloseable if needed
    if (types.asSuper(resource.type, syms.autoCloseableType.tsym) == null) {
        resource = convert(resource, syms.autoCloseableType);
    }

    // create resource.close() method invocation
    JCExpression resourceClose = makeCall(resource,
                                          names.close,
                                          List.nil());
    return make.Exec(resourceClose);
}
 
Example #10
Source File: PartialReparserService.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public JCBlock reparseMethodBody(CompilationUnitTree topLevel, MethodTree methodToReparse, String newBodyText, int annonIndex,
        final Map<? super JCTree,? super LazyDocCommentTable.Entry> docComments) {
    CharBuffer buf = CharBuffer.wrap((newBodyText+"\u0000").toCharArray(), 0, newBodyText.length());
    JavacParser parser = newParser(context, buf, ((JCBlock)methodToReparse.getBody()).pos, ((JCCompilationUnit)topLevel).endPositions);
    final JCStatement statement = parser.parseStatement();
    NBParserFactory.assignAnonymousClassIndices(Names.instance(context), statement, Names.instance(context).empty, annonIndex);
    if (statement.getKind() == Tree.Kind.BLOCK) {
        if (docComments != null) {
            docComments.putAll(((LazyDocCommentTable) parser.getDocComments()).table);
        }
        return (JCBlock) statement;
    }
    return null;
}
 
Example #11
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Add any variables defined in stats to inits and uninits. */
private void addVars(List<JCStatement> stats, final Bits inits,
                            final Bits uninits) {
    for (;stats.nonEmpty(); stats = stats.tail) {
        JCTree stat = stats.head;
        if (stat.hasTag(VARDEF)) {
            int adr = ((JCVariableDecl) stat).sym.adr;
            inits.excl(adr);
            uninits.incl(adr);
        }
    }
}
 
Example #12
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Return tree simulating the assignment {@code this.this$n = this$n}.
 */
JCStatement initOuterThis(int pos) {
    VarSymbol rhs = outerThisStack.head;
    Assert.check(rhs.owner.kind == MTH);
    VarSymbol lhs = outerThisStack.tail.head;
    Assert.check(rhs.owner.owner == lhs.owner);
    make.at(pos);
    return
        make.Exec(
            make.Assign(
                make.Select(make.This(lhs.owner.erasure(types)), lhs),
                make.Ident(rhs)).setType(lhs.erasure(types)));
}
 
Example #13
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Return tree simulating the assignment {@code this.name = name}, where
 *  name is the name of a free variable.
 */
JCStatement initField(int pos, Symbol rhs, Symbol lhs) {
    Assert.check(rhs.owner.kind == MTH);
    Assert.check(rhs.owner.owner == lhs.owner);
    make.at(pos);
    return
        make.Exec(
            make.Assign(
                make.Select(make.This(lhs.owner.erasure(types)), lhs),
                make.Ident(rhs)).setType(lhs.erasure(types)));
}
 
Example #14
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private Expression convertInitializer(JCStatement statement) {
  switch (statement.getKind()) {
    case EXPRESSION_STATEMENT:
      return convertExpression(((JCExpressionStatement) statement).expr);
    default:
      throw new AssertionError();
  }
}
 
Example #15
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static JCStatement parseStatement(Context context, CharSequence stmt, SourcePositions[] pos, final List<Diagnostic<? extends JavaFileObject>> errors) {
    if (stmt == null || (pos != null && pos.length != 1))
        throw new IllegalArgumentException();
    JavaCompiler compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(new DummyJFO());
    Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
        @Override
        public void report(JCDiagnostic diag) {
            errors.add(diag);
        }            
    };
    try {
        CharBuffer buf = CharBuffer.wrap((stmt+"\u0000").toCharArray(), 0, stmt.length());
        ParserFactory factory = ParserFactory.instance(context);
        ScannerFactory scannerFactory = ScannerFactory.instance(context);
        Names names = Names.instance(context);
        Parser parser = newParser(context, (NBParserFactory) factory, scannerFactory.newScanner(buf, false), false, false, CancelService.instance(context), names);
        if (parser instanceof JavacParser) {
            if (pos != null)
                pos[0] = new ParserSourcePositions((JavacParser)parser);
            return parser.parseStatement();
        }
        return null;
    } finally {
        compiler.log.useSource(prev);
        compiler.log.popDiagnosticHandler(discardHandler);
    }
}
 
Example #16
Source File: JavacJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
private void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> jceBlank = List.nil();
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source));
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	long baseFlags = JavacHandlerUtil.addFinalIfNeeded(0, builderType.getContext());
	Name entryName = builderType.toName("$lombokEntry");
	
	JCExpression forEachType = chainDots(builderType, "java", "util", "Map", "Entry");
	forEachType = addTypeArgs(2, true, builderType, forEachType, data.getTypeArgs(), source);
	JCExpression keyArg = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(entryName), builderType.toName("getKey")), List.<JCExpression>nil());
	JCExpression valueArg = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(entryName), builderType.toName("getValue")), List.<JCExpression>nil());
	JCExpression addKey = maker.Apply(List.<JCExpression>nil(), chainDots(builderType, "this", data.getPluralName() + "$key", "add"), List.of(keyArg));
	JCExpression addValue = maker.Apply(List.<JCExpression>nil(), chainDots(builderType, "this", data.getPluralName() + "$value", "add"), List.of(valueArg));
	JCBlock forEachBody = maker.Block(0, List.<JCStatement>of(maker.Exec(addKey), maker.Exec(addValue)));
	JCExpression entrySetInvocation = maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("entrySet")), jceBlank);
	JCStatement forEach = maker.ForeachLoop(maker.VarDef(maker.Modifiers(baseFlags), entryName, forEachType, null), entrySetInvocation, forEachBody);
	statements.append(forEach);
	
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getPluralName();
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("putAll", name.toString()));
	JCExpression paramType = chainDots(builderType, "java", "util", "Map");
	paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs(), source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), jceBlank, body, null);
	injectMethod(builderType, method);
}
 
Example #17
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName) {
	JavacTreeMaker maker = builderType.getTreeMaker();
	List<JCExpression> jceBlank = List.nil();
	boolean mapMode = isMap();
	
	JCExpression varType = chainDotsString(builderType, data.getTargetFqn());
	varType = addTypeArgs(mapMode ? 2 : 1, false, builderType, varType, data.getTypeArgs(), source);
	
	JCExpression empty; {
		//ImmutableX.of()
		JCExpression emptyMethod = chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), "of");
		List<JCExpression> invokeTypeArgs = createTypeArgs(mapMode ? 2 : 1, false, builderType, data.getTypeArgs(), source);
		empty = maker.Apply(invokeTypeArgs, emptyMethod, jceBlank);
	}
	
	JCExpression invokeBuild; {
		//this.pluralName.build();
		invokeBuild = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName().toString(), "build"), jceBlank);
	}
	
	JCExpression isNull; {
		//this.pluralName == null
		isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()), maker.Literal(CTC_BOT, null));
	}
	
	JCExpression init = maker.Conditional(isNull, empty, invokeBuild); // this.pluralName == null ? ImmutableX.of() : this.pluralName.build()
	
	JCStatement jcs = maker.VarDef(maker.Modifiers(0), data.getPluralName(), varType, init);
	statements.append(jcs);
}
 
Example #18
Source File: JavacJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName) {
	if (useGuavaInstead(builderType)) {
		guavaMapSingularizer.appendBuildCode(data, builderType, source, statements, targetVariableName);
		return;
	}
	
	JavacTreeMaker maker = builderType.getTreeMaker();
	
	if (data.getTargetFqn().equals("java.util.Map")) {
		statements.appendList(createJavaUtilSetMapInitialCapacitySwitchStatements(maker, data, builderType, true, "emptyMap", "singletonMap", "LinkedHashMap", source));
	} else {
		statements.appendList(createJavaUtilSimpleCreationAndFillStatements(maker, data, builderType, true, true, false, true, "TreeMap", source));
	}
}
 
Example #19
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private List<Expression> convertInitializers(List<JCStatement> statements) {
  if (statements.stream().anyMatch(s -> s.getKind() == Kind.VARIABLE)) {
    // The statements are all variable declaration statements, collect them into one
    // variable declaration expression.
    return convertVariableDeclarations(statements);
  }

  return statements.stream().map(this::convertInitializer).collect(toImmutableList());
}
 
Example #20
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private List<Expression> convertVariableDeclarations(List<JCStatement> statements) {
  return ImmutableList.of(
      VariableDeclarationExpression.newBuilder()
          .addVariableDeclarationFragments(
              statements.stream()
                  .map(s -> createVariableDeclarationFragment((JCVariableDecl) s))
                  .collect(toImmutableList()))
          .build());
}
 
Example #21
Source File: HandleBuilder.java    From EasyMPermission with MIT License 5 votes vote down vote up
public JCMethodDecl generateBuilderMethod(String builderMethodName, String builderClassName, JavacNode type, List<JCTypeParameter> typeParams) {
	JavacTreeMaker maker = type.getTreeMaker();
	
	ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
	for (JCTypeParameter typeParam : typeParams) {
		typeArgs.append(maker.Ident(typeParam.name));
	}
	
	JCExpression call = maker.NewClass(null, List.<JCExpression>nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCExpression>nil(), null);
	JCStatement statement = maker.Return(call);
	
	JCBlock body = maker.Block(0, List.<JCStatement>of(statement));
	return maker.MethodDef(maker.Modifiers(Flags.STATIC | Flags.PUBLIC), type.toName(builderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), copyTypeParams(maker, typeParams), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
}
 
Example #22
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void handleMethod(JavacNode annotation, JCMethodDecl method, Collection<String> exceptions) {
	JavacNode methodNode = annotation.up();
	
	if ( (method.mods.flags & Flags.ABSTRACT) != 0) {
		annotation.addError("@SneakyThrows can only be used on concrete methods.");
		return;
	}
	
	if (method.body == null || method.body.stats.isEmpty()) {
		generateEmptyBlockWarning(methodNode, annotation, false);
		return;
	}
	
	final JCStatement constructorCall = method.body.stats.get(0);
	final boolean isConstructorCall = isConstructorCall(constructorCall);
	List<JCStatement> contents = isConstructorCall ? method.body.stats.tail : method.body.stats;
	
	if (contents == null || contents.isEmpty()) {
		generateEmptyBlockWarning(methodNode, annotation, true);
		return;
	}
	
	for (String exception : exceptions) {
		contents = List.of(buildTryCatchBlock(methodNode, contents, exception, annotation.get()));
	}
	
	method.body.stats = isConstructorCall ? List.of(constructorCall).appendList(contents) : contents;
	methodNode.rebuild();
}
 
Example #23
Source File: Analyzer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Analyze an AST node if needed.
 */
void analyzeIfNeeded(JCTree tree, Env<AttrContext> env) {
    if (!analyzerModes.isEmpty() &&
            !env.info.isSpeculative &&
            TreeInfo.isStatement(tree)) {
        JCStatement stmt = (JCStatement)tree;
        analyze(stmt, env);
    }
}
 
Example #24
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
	JavacTreeMaker maker = builderType.getTreeMaker();
	JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
	generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
	
	returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
	generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
}
 
Example #25
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	boolean mapMode = isMap();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, mapMode, source));
	JCExpression thisDotFieldDotAddAll = chainDots(builderType, "this", data.getPluralName().toString(), mapMode ? "putAll" : "addAll");
	JCExpression invokeAddAll = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAddAll, List.<JCExpression>of(maker.Ident(data.getPluralName())));
	statements.append(maker.Exec(invokeAddAll));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name methodName = data.getPluralName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(mapMode ? "putAll" : "addAll", methodName.toString()));
	JCExpression paramType;
	if (mapMode) {
		paramType = chainDots(builderType, "java", "util", "Map");
	} else {
		paramType = genJavaLangTypeRef(builderType, "Iterable");
	}
	paramType = addTypeArgs(mapMode ? 2 : 1, true, builderType, paramType, data.getTypeArgs(), source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #26
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	
	JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
	JCExpression thisDotField2 = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
	JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
	
	JCExpression create = maker.Apply(jceBlank, chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), getBuilderMethodName(data)), jceBlank);
	JCStatement thenPart = maker.Exec(maker.Assign(thisDotField2, create));
	
	return maker.If(cond, thenPart, null);
}
 
Example #27
Source File: JavacJavaUtilSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, JCTree source) {
	List<JCExpression> jceBlank = List.nil();

	Name v1Name = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName();
	Name v2Name = mapMode ? builderType.toName(data.getPluralName() + "$value") : null;
	JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v1Name);
	JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
	thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v1Name);
	JCExpression v1Type = chainDots(builderType, "java", "util", "ArrayList");
	v1Type = addTypeArgs(1, false, builderType, v1Type, data.getTypeArgs(), source);
	JCExpression constructArrayList = maker.NewClass(null, jceBlank, v1Type, jceBlank, null);
	JCStatement initV1 = maker.Exec(maker.Assign(thisDotField, constructArrayList));
	JCStatement thenPart;
	if (mapMode) {
		thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v2Name);
		JCExpression v2Type = chainDots(builderType, "java", "util", "ArrayList");
		List<JCExpression> tArgs = data.getTypeArgs();
		if (tArgs != null && tArgs.tail != null) tArgs = tArgs.tail;
		else tArgs = List.nil();
		v2Type = addTypeArgs(1, false, builderType, v2Type, tArgs, source);
		constructArrayList = maker.NewClass(null, jceBlank, v2Type, jceBlank, null);
		JCStatement initV2 = maker.Exec(maker.Assign(thisDotField, constructArrayList));
		thenPart = maker.Block(0, List.of(initV1, initV2));
	} else {
		thenPart = initV1;
	}
	return maker.If(cond, thenPart, null);
}
 
Example #28
Source File: HandleUtilityClass.java    From EasyMPermission with MIT License 5 votes vote down vote up
private List<JCStatement> createThrowStatement(JavacNode typeNode, JavacTreeMaker maker) {
	JCExpression exceptionType = genJavaLangTypeRef(typeNode, "UnsupportedOperationException");
	List<JCExpression> jceBlank = List.nil();
	JCExpression message = maker.Literal("This is a utility class and cannot be instantiated");
	JCExpression exceptionInstance = maker.NewClass(null, jceBlank, exceptionType, List.of(message), null);
	JCStatement throwStatement = maker.Throw(exceptionInstance);
	return List.of(throwStatement);
}
 
Example #29
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
/** For javac, both JCExpression and JCStatement are considered as valid children types. */
@Override
protected Collection<Class<? extends JCTree>> getStatementTypes() {
	Collection<Class<? extends JCTree>> collection = new ArrayList<Class<? extends JCTree>>(3);
	collection.add(JCStatement.class);
	collection.add(JCExpression.class);
	collection.add(JCCatch.class);
	return collection;
}
 
Example #30
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private JavacNode buildMethod(JCMethodDecl method) {
	if (setAndGetAsHandled(method)) return null;
	List<JavacNode> childNodes = new ArrayList<JavacNode>();
	for (JCAnnotation annotation : method.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, false));
	for (JCVariableDecl param : method.params) addIfNotNull(childNodes, buildLocalVar(param, Kind.ARGUMENT));
	if (method.body != null && method.body.stats != null) {
		for (JCStatement statement : method.body.stats) addIfNotNull(childNodes, buildStatement(statement));
	}
	return putInMap(new JavacNode(this, method, childNodes, Kind.METHOD));
}