private static boolean createField(LoggingFramework framework, JavacNode typeNode, JCFieldAccess loggingType, JCTree source, String logFieldName, boolean useStatic, String loggerTopic) { JavacTreeMaker maker = typeNode.getTreeMaker(); // private static final <loggerType> log = <factoryMethod>(<parameter>); JCExpression loggerType = chainDotsString(typeNode, framework.getLoggerTypeName()); JCExpression factoryMethod = chainDotsString(typeNode, framework.getLoggerFactoryMethodName()); JCExpression loggerName; if (loggerTopic == null || loggerTopic.trim().length() == 0) { loggerName = framework.createFactoryParameter(typeNode, loggingType); } else { loggerName = maker.Literal(loggerTopic); } JCMethodInvocation factoryMethodCall = maker.Apply(List.<JCExpression>nil(), factoryMethod, List.<JCExpression>of(loggerName)); JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef( maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (useStatic ? Flags.STATIC : 0)), typeNode.toName(logFieldName), loggerType, factoryMethodCall), source, typeNode.getContext()); injectFieldAndMarkGenerated(typeNode, fieldDecl); return true; }
@Override public void visitApply(JCMethodInvocation tree) { boolean prevCheckThis = checkThis; try { Symbol meth = TreeInfo.symbol(tree.meth); Name methName = TreeInfo.name(tree.meth); if (meth != null && meth.name == names.init) { Symbol c = meth.owner; if (c.hasOuterInstance()) { checkThis = false; if (tree.meth.getTag() != JCTree.Tag.SELECT && (c.isLocal() || methName == names._this)) { checkThis(tree.meth.pos(), c.type.getEnclosingType().tsym); } } } super.visitApply(tree); } finally { checkThis = prevCheckThis; } }
@Override public Void visitMethodInvocation(MethodInvocationTree node, Void p) { super.visitMethodInvocation(node, p); JCMethodInvocation apply = (JCMethodInvocation)node; JCIdent ident = (JCIdent)apply.meth; Symbol oldSym = ident.sym; if (!oldSym.isConstructor()) { Object[] staticArgs = new Object[arity.arity]; for (int i = 0; i < arity.arity ; i++) { staticArgs[i] = saks[i].getValue(syms, names, types); } ident.sym = new Symbol.DynamicMethodSymbol(oldSym.name, oldSym.owner, REF_invokeStatic, bsm, oldSym.type, staticArgs); } return null; }
private boolean suppress(JCTree tree) { if (tree instanceof JCBlock) { JCBlock block = (JCBlock) tree; return (Position.NOPOS == block.pos) && block.stats.isEmpty(); } if (tree instanceof JCExpressionStatement) { JCExpression expr = ((JCExpressionStatement)tree).expr; if (expr instanceof JCMethodInvocation) { JCMethodInvocation inv = (JCMethodInvocation) expr; if (!inv.typeargs.isEmpty() || !inv.args.isEmpty()) return false; if (!(inv.meth instanceof JCIdent)) return false; return ((JCIdent) inv.meth).name.toString().equals("super"); } } return false; }
@Override public void visitApply(JCMethodInvocation tree) { if (tree.typeargs.nonEmpty()) { if (tree.meth instanceof JCFieldAccess) { JCFieldAccess fa = (JCFieldAccess) tree.meth; print(fa.selected); print(".<"); print(tree.typeargs, ", "); print(">"); print(fa.name); } else { print("<"); print(tree.typeargs, ", "); print(">"); print(tree.meth); } } else { print(tree.meth); } print("("); print(tree.args, ", "); print(")"); }
public static boolean isConstructorCall(final JCStatement statement) { if (!(statement instanceof JCExpressionStatement)) return false; JCExpression expr = ((JCExpressionStatement) statement).expr; if (!(expr instanceof JCMethodInvocation)) return false; JCExpression invocation = ((JCMethodInvocation) expr).meth; String name; if (invocation instanceof JCFieldAccess) { name = ((JCFieldAccess) invocation).name.toString(); } else if (invocation instanceof JCIdent) { name = ((JCIdent) invocation).name.toString(); } else { name = ""; } return "super".equals(name) || "this".equals(name); }
public void visitApply(JCMethodInvocation tree) { try { if (!tree.typeargs.isEmpty()) { if (SELECT.equals(treeTag(tree.meth))) { JCFieldAccess left = (JCFieldAccess)tree.meth; printExpr(left.selected); print(".<"); printExprs(tree.typeargs); print(">" + left.name); } else { print("<"); printExprs(tree.typeargs); print(">"); printExpr(tree.meth); } } else { printExpr(tree.meth); } print("("); printExprs(tree.args); print(")"); } catch (IOException e) { throw new UncheckedIOException(e); } }
/** * Gets the symbol for a tree. Returns null if this tree does not have a symbol because it is of * the wrong type, if {@code tree} is null, or if the symbol cannot be found due to a compilation * error. */ // TODO(eaftan): refactor other code that accesses symbols to use this method public static Symbol getSymbol(Tree tree) { if (tree instanceof JCFieldAccess) { return ((JCFieldAccess) tree).sym; } if (tree instanceof JCIdent) { return ((JCIdent) tree).sym; } if (tree instanceof JCMethodInvocation) { return ASTHelpers.getSymbol((MethodInvocationTree) tree); } if (tree instanceof JCNewClass) { return ASTHelpers.getSymbol((NewClassTree) tree); } if (tree instanceof MemberReferenceTree) { return ((JCMemberReference) tree).sym; } if (tree instanceof JCAnnotatedType) { return getSymbol(((JCAnnotatedType) tree).underlyingType); } return getDeclaredSymbol(tree); }
/** * Returns the type of a receiver of a method call expression. Precondition: the expressionTree * corresponds to a method call. * * <p>Examples: * * <pre>{@code * a.b.foo() ==> type of a.b * a.bar().foo() ==> type of a.bar() * this.foo() ==> type of this * foo() ==> type of this * TheClass.aStaticMethod() ==> TheClass * aStaticMethod() ==> type of class in which method is defined * }</pre> */ public static Type getReceiverType(ExpressionTree expressionTree) { if (expressionTree instanceof JCFieldAccess) { JCFieldAccess methodSelectFieldAccess = (JCFieldAccess) expressionTree; return methodSelectFieldAccess.selected.type; } else if (expressionTree instanceof JCIdent) { JCIdent methodCall = (JCIdent) expressionTree; return methodCall.sym.owner.type; } else if (expressionTree instanceof JCMethodInvocation) { return getReceiverType(((JCMethodInvocation) expressionTree).getMethodSelect()); } else if (expressionTree instanceof JCMemberReference) { return ((JCMemberReference) expressionTree).getQualifierExpression().type; } throw new IllegalArgumentException( "Expected a JCFieldAccess or JCIdent from expression " + expressionTree); }
@Override public Description matchMethodInvocation( MethodInvocationTree methodInvocationTree, VisitorState state) { if (!MATCHER.matches(methodInvocationTree, state)) { return Description.NO_MATCH; } if (methodInvocationTree.getArguments().size() % 2 == 0) { return Description.NO_MATCH; } JCMethodInvocation methodInvocation = (JCMethodInvocation) methodInvocationTree; List<JCExpression> arguments = methodInvocation.getArguments(); Type typeVargs = methodInvocation.varargsElement; if (typeVargs == null) { return Description.NO_MATCH; } Type typeVarargsArr = state.arrayTypeForType(typeVargs); Type lastArgType = ASTHelpers.getType(Iterables.getLast(arguments)); if (typeVarargsArr.equals(lastArgType)) { return Description.NO_MATCH; } return describeMatch(methodInvocationTree); }
/** * Returns a {@link JCMethodInvocation} node which calls the query call method defined * by the defineQueryCallMethod method. * <p> * The returned node is intended to replace the {@link JCSqlQuery} node, as it is a normal * method call that can be handled appropriately. * @param memberEnter The current MemberEnter instance to enter live-generated code. * @return A {@link JCMethodInvocation} node which is intended to replace the {@link JCSqlQuery} node. */ public JCMethodInvocation getQueryCallExpression(MemberEnter memberEnter) { MethodCallCodeGenerator codeGenerator = new MethodCallCodeGenerator(); String queryCall = codeGenerator.getQueryCall(this); // create expression parse node from string JCExpression queryCallExpression = Reifier.getInstance().reifyExpression(queryCall); if (queryCallExpression instanceof JCMethodInvocation) { // enter it to symbol table queryCallExpression.accept(memberEnter); // note: attribution will happen in the calling method in the Attr // class, as this will need the expected type return (JCMethodInvocation) queryCallExpression; } // tbd: checked exception handling throw new RuntimeException("Parsed query call expression is no method invocation"); }
public void visitApply(JCMethodInvocation tree) { try { if (!tree.typeargs.isEmpty()) { if (tree.meth.getTag() == JCTree.SELECT) { JCFieldAccess left = (JCFieldAccess)tree.meth; printExpr(left.selected); print(".<"); printExprs(tree.typeargs); print(">" + left.name); } else { print("<"); printExprs(tree.typeargs); print(">"); printExpr(tree.meth); } } else { printExpr(tree.meth); } print("("); printExprs(tree.args); print(")"); } catch (IOException e) { throw new UncheckedIOException(e); } }
private static boolean delegatingConstructor(List<JCStatement> stats) { if (stats.isEmpty()) { return false; } JCStatement stat = stats.get(0); if (stat.getKind() != Kind.EXPRESSION_STATEMENT) { return false; } JCExpression expr = ((JCExpressionStatement) stat).getExpression(); if (expr.getKind() != Kind.METHOD_INVOCATION) { return false; } JCExpression method = ((JCMethodInvocation) expr).getMethodSelect(); Name name; switch (method.getKind()) { case IDENTIFIER: name = ((JCIdent) method).getName(); break; case MEMBER_SELECT: name = ((JCFieldAccess) method).getIdentifier(); break; default: return false; } return name.contentEquals("this") || name.contentEquals("super"); }
@Override public IsType getInvocationTargetType(CompilationUnitTree cup, MethodInvocationTree node) { if (node instanceof JCMethodInvocation) { final TreePath path = trees.getPath(cup, node); final TreePath parent = path.getParentPath(); final Tree target = parent.getLeaf(); switch (target.getKind()) { case VARIABLE: JCVariableDecl var = (JCVariableDecl) target; final JCTree type = var.getType(); final JavacScope scope = trees.getScope(path); final IsType cls = getTypeOf(cup, scope, type); return cls; default: X_Log.error(getClass(), "Unhandled invocation target type: ", target.getKind(), target); } } else { X_Log.warn(getClass(), "Does not support MethodInvocationTree ", node); } return null; }
public void visitApply(JCMethodInvocation tree) { try { if (!tree.typeargs.isEmpty()) { if (getTag(tree.meth) == SELECT) { JCFieldAccess left = (JCFieldAccess)tree.meth; printExpr(left.selected); print(".<"); printExprs(tree.typeargs); print(">" + left.name); } else { print("<"); printExprs(tree.typeargs); print(">"); printExpr(tree.meth); } } else { printExpr(tree.meth); } print("("); printExprs(tree.args); print(")"); } catch (IOException e) { throw new UncheckedIOException(e); } }
private static boolean createField(LoggingFramework framework, JavacNode typeNode, JCFieldAccess loggingType, JCTree source) { TreeMaker maker = typeNode.getTreeMaker(); // private static final <loggerType> log = <factoryMethod>(<parameter>); JCExpression loggerType = chainDotsString(typeNode, framework.getLoggerTypeName()); JCExpression factoryMethod = chainDotsString(typeNode, framework.getLoggerFactoryMethodName()); JCExpression loggerName = framework.createFactoryParameter(typeNode, loggingType); JCMethodInvocation factoryMethodCall = maker.Apply(List.<JCExpression>nil(), factoryMethod, List.<JCExpression>of(loggerName)); JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef( maker.Modifiers(Flags.PRIVATE | Flags.FINAL | Flags.STATIC), typeNode.toName("log"), loggerType, factoryMethodCall), source); injectField(typeNode, fieldDecl); return true; }
protected int diffApply(JCMethodInvocation oldT, JCMethodInvocation newT, int[] bounds) { int localPointer = bounds[0]; int[] methBounds = getBounds(oldT.meth); if (Kind.MEMBER_SELECT == oldT.meth.getKind() && oldT.meth.getKind() == newT.meth.getKind()) { localPointer = diffSelect((JCFieldAccess) oldT.meth, (JCFieldAccess) newT.meth, methBounds, oldT.typeargs, newT.typeargs); } else if (oldT.typeargs.isEmpty() && newT.typeargs.isEmpty()) { localPointer = diffTree(oldT.meth, newT.meth, methBounds); } else { copyTo(localPointer, methBounds[0]); printer.printMethodSelect(newT); localPointer = methBounds[1]; } if (!listsMatch(oldT.args, newT.args)) { if (oldT.args.nonEmpty()) { int startArg1 = getCommentCorrectedOldPos(oldT.args.head); tokenSequence.move(startArg1); moveToSrcRelevant(tokenSequence, Direction.BACKWARD); tokenSequence.moveNext(); copyTo(localPointer, localPointer = tokenSequence.offset()); } else { copyTo(localPointer, localPointer = methBounds[1]); tokenSequence.move(localPointer); moveToSrcRelevant(tokenSequence, Direction.FORWARD); tokenSequence.moveNext(); copyTo(localPointer, localPointer = tokenSequence.offset()); } localPointer = diffParameterList(oldT.args, newT.args, null, localPointer, Measure.ARGUMENT); } copyTo(localPointer, bounds[1]); return bounds[1]; }
@Override public void visitApply(JCMethodInvocation tree) { Symbol m = TreeInfo.symbolFor(tree); AssertOverloadKind ak = assertOverloadKind(m); if (ak != AssertOverloadKind.NONE && !m.name.contentEquals("error")) { JCExpression lastParam = tree.args.last(); if (isSimpleStringArg(lastParam) != ak.simpleArgExpected()) { messages.error(lastParam, ak.errKey); } } super.visitApply(tree); }
void checkLegacyLogMethod(JCMethodInvocation tree) { Symbol method = TreeInfo.symbolFor(tree); if (method == null || method.kind != Kinds.Kind.MTH || !typeToCheck(method.owner.type) || !LEGACY_METHOD_NAMES.contains(method.name.toString()) || !((MethodSymbol) method).isVarArgs() || method.type.getParameterTypes().size() < 2) { return ; } JCExpression key = tree.args.get(method.type.getParameterTypes().size() - 2); if (key.hasTag(Tag.LITERAL)) { messages.error(tree, "crules.use.of.legacy.log.method", tree); } }
@Override public void visitApply(JCMethodInvocation that) { if (that.getTypeArguments().isEmpty()) { processArg(that, speculativeTree -> new ResolvedMethodType(that, env, speculativeTree)); } else { //not a poly expression, just call Attr setResult(that, attr.attribTree(that, env, attr.unknownExprInfo)); } }
@Override void process (JCMethodInvocation oldTree, JCMethodInvocation newTree, boolean hasErrors){ if (!hasErrors) { //exact match log.warning(oldTree, Warnings.MethodRedundantTypeargs); } }
@Override public Void visitMethodInvocation(MethodInvocationTree node, Void p) { super.visitMethodInvocation(node, p); JCMethodInvocation apply = (JCMethodInvocation)node; JCIdent ident = (JCIdent)apply.meth; Symbol oldSym = ident.sym; if (!oldSym.isConstructor()) { ident.sym = new Symbol.DynamicMethodSymbol(oldSym.name, oldSym.owner, REF_invokeStatic, bsm, oldSym.type, new Object[0]); } return null; }
@Override void process (JCMethodInvocation oldTree, JCMethodInvocation newTree, boolean hasErrors){ if (!hasErrors) { //exact match log.warning(oldTree, "method.redundant.typeargs"); } }
static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess, JCExpression receiver) { boolean lookForGetter = lookForGetter(field, fieldAccess); GetterMethod getter = lookForGetter ? findGetter(field) : null; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); if (getter == null) { if (receiver == null) { if ((fieldDecl.mods.flags & Flags.STATIC) == 0) { receiver = maker.Ident(field.toName("this")); } else { JavacNode containerNode = field.up(); if (containerNode != null && containerNode.get() instanceof JCClassDecl) { JCClassDecl container = (JCClassDecl) field.up().get(); receiver = maker.Ident(container.name); } } } return receiver == null ? maker.Ident(fieldDecl.name) : maker.Select(receiver, fieldDecl.name); } if (receiver == null) receiver = maker.Ident(field.toName("this")); JCMethodInvocation call = maker.Apply(List.<JCExpression>nil(), maker.Select(receiver, getter.name), List.<JCExpression>nil()); return call; }
private JCMethodDecl createHelloWorld(JavacNode type) { //This is the artist/ bad guy JavacTreeMaker treeMaker = type.getTreeMaker(); //Define public JCModifiers modifiers = treeMaker.Modifiers(Modifier.PUBLIC); //Define Generic type List<JCTree.JCTypeParameter> methodGenericTypes = List.<JCTypeParameter>nil(); //Define return type JCExpression methodType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID)); //Define method name Name methodName = type.toName("helloWorld"); //Define parameter List<JCTree.JCVariableDecl> methodParameters = List.<JCVariableDecl>nil(); //Define throw List<JCTree.JCExpression> methodThrows = List.<JCExpression>nil(); //Write our system.out.prinln("hello world") method JCExpression printlnMethod = JavacHandlerUtil.chainDots(type, "System", "out", "println"); List<JCTree.JCExpression> printlnArgs = List.<JCExpression>of(treeMaker.Literal("hello world")); JCMethodInvocation printlnInvocation = treeMaker.Apply(List.<JCExpression>nil(), printlnMethod, printlnArgs); //Define method JCBlock methodBody = treeMaker.Block(0, List.<JCStatement>of(treeMaker.Exec(printlnInvocation))); //Default value JCExpression defaultValue = null; return treeMaker.MethodDef( modifiers, methodName, methodType, methodGenericTypes, methodParameters, methodThrows, methodBody, defaultValue ); }
public JCExpression preventNullAnalysis(JavacTreeMaker maker, JavacNode node, JCExpression expression) { if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().danceAroundIdeChecks()) { JCMethodInvocation singletonList = maker.Apply(List.<JCExpression>nil(), chainDotsString(node, "java.util.Collections.singletonList"), List.of(expression)); JCMethodInvocation cleanedExpr = maker.Apply(List.<JCExpression>nil(), maker.Select(singletonList, node.toName("get")) , List.<JCExpression>of(maker.Literal(CTC_INT, 0))); return cleanedExpr; } else { return expression; } }
private void handleMethodCall(final JCMethodInvocation methodCall) { JavacNode methodCallNode = annotationNode.getAst().get(methodCall); if (methodCallNode == null) { // This should mean the node does not exist in the source at all. This is the case for generated nodes, such as implicit super() calls. return; } JavacNode surroundingType = upToTypeNode(methodCallNode); TypeSymbol surroundingTypeSymbol = ((JCClassDecl)surroundingType.get()).sym; JCExpression receiver = receiverOf(methodCall); String methodName = methodNameOf(methodCall); if ("this".equals(methodName) || "super".equals(methodName)) return; Type resolvedMethodCall = CLASS_AND_METHOD.resolveMember(methodCallNode, methodCall); if (resolvedMethodCall == null) return; if (!suppressBaseMethods && !(resolvedMethodCall instanceof ErrorType)) return; Type receiverType = CLASS_AND_METHOD.resolveMember(methodCallNode, receiver); if (receiverType == null) return; if (receiverType.tsym.toString().endsWith(receiver.toString())) return; Types types = Types.instance(annotationNode.getContext()); for (Extension extension : extensions) { TypeSymbol extensionProvider = extension.extensionProvider; if (surroundingTypeSymbol == extensionProvider) continue; for (MethodSymbol extensionMethod : extension.extensionMethods) { if (!methodName.equals(extensionMethod.name.toString())) continue; Type extensionMethodType = extensionMethod.type; if (!MethodType.class.isInstance(extensionMethodType) && !ForAll.class.isInstance(extensionMethodType)) continue; Type firstArgType = types.erasure(extensionMethodType.asMethodType().argtypes.get(0)); if (!types.isAssignable(receiverType, firstArgType)) continue; methodCall.args = methodCall.args.prepend(receiver); methodCall.meth = chainDotsString(annotationNode, extensionProvider.toString() + "." + methodName); return; } } }
private String methodNameOf(final JCMethodInvocation methodCall) { if (methodCall.meth instanceof JCIdent) { return ((JCIdent) methodCall.meth).name.toString(); } else { return ((JCFieldAccess) methodCall.meth).name.toString(); } }
private JCExpression receiverOf(final JCMethodInvocation methodCall) { if (methodCall.meth instanceof JCIdent) { return annotationNode.getTreeMaker().Ident(annotationNode.toName("this")); } else { return ((JCFieldAccess) methodCall.meth).selected; } }
public void visitApply(JCMethodInvocation that) { try { print("JCMethodInvocation:"); } catch (Exception e) { } super.visitApply(that); }