org.codehaus.groovy.ast.MethodNode Java Examples
The following examples show how to use
org.codehaus.groovy.ast.MethodNode.
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: Methods.java From netbeans with Apache License 2.0 | 6 votes |
public static boolean isSameMethod(MethodNode methodNode1, MethodNode methodNode2) { if (methodNode1.getName().equals(methodNode2.getName())) { Parameter[] params1 = methodNode1.getParameters(); Parameter[] params2 = methodNode2.getParameters(); if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { ClassNode type1 = params1[i].getType(); ClassNode type2 = params2[i].getType(); if (!type1.equals(type2)) { return false; } } return true; } } return false; }
Example #2
Source File: AbstractFunctionalInterfaceWriter.java From groovy with Apache License 2.0 | 6 votes |
default Object[] createBootstrapMethodArguments(String abstractMethodDesc, int insn, ClassNode methodOwnerClassNode, MethodNode methodNode, boolean serializable) { Parameter[] parameters = methodNode.getNodeMetaData(ORIGINAL_PARAMETERS_WITH_EXACT_TYPE); List<Object> argumentList = new LinkedList<>(); argumentList.add(Type.getType(abstractMethodDesc)); argumentList.add( new Handle( insn, BytecodeHelper.getClassInternalName(methodOwnerClassNode.getName()), methodNode.getName(), BytecodeHelper.getMethodDescriptor(methodNode), methodOwnerClassNode.isInterface() ) ); argumentList.add(Type.getType(BytecodeHelper.getMethodDescriptor(methodNode.getReturnType(), parameters))); if (serializable) { argumentList.add(5); argumentList.add(0); } return argumentList.toArray(); }
Example #3
Source File: TraitReceiverTransformer.java From groovy with Apache License 2.0 | 6 votes |
private Expression transformMethodCallOnThis(final MethodCallExpression call) { Expression method = call.getMethod(); Expression arguments = call.getArguments(); if (method instanceof ConstantExpression) { String methodName = method.getText(); List<MethodNode> methods = traitClass.getMethods(methodName); for (MethodNode methodNode : methods) { if (methodName.equals(methodNode.getName()) && methodNode.isPrivate()) { if (inClosure) { return transformPrivateMethodCallOnThisInClosure(call, arguments, methodName); } return transformPrivateMethodCallOnThis(call, arguments, methodName); } } } if (inClosure) { return transformMethodCallOnThisInClosure(call); } return transformMethodCallOnThisFallBack(call, method, arguments); }
Example #4
Source File: StaticTypesMethodReferenceExpressionWriter.java From groovy with Apache License 2.0 | 6 votes |
private MethodNode addSyntheticMethodForDGSM(MethodNode mn) { Parameter[] parameters = removeFirstParameter(mn.getParameters()); ArgumentListExpression args = args(parameters); args.getExpressions().add(0, ConstantExpression.NULL); MethodNode syntheticMethodNode = controller.getClassNode().addSyntheticMethod( "dgsm$$" + mn.getParameters()[0].getType().getName().replace(".", "$") + "$$" + mn.getName(), Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC, mn.getReturnType(), parameters, ClassNode.EMPTY_ARRAY, block( returnS( callX(new ClassExpression(mn.getDeclaringClass()), mn.getName(), args) ) ) ); syntheticMethodNode.addAnnotation(new AnnotationNode(GENERATED_TYPE)); syntheticMethodNode.addAnnotation(new AnnotationNode(COMPILE_STATIC_TYPE)); return syntheticMethodNode; }
Example #5
Source File: NotYetImplementedASTTransformation.java From groovy with Apache License 2.0 | 6 votes |
public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode anno = (AnnotationNode) nodes[0]; MethodNode methodNode = (MethodNode) nodes[1]; ClassNode exception = getMemberClassValue(anno, "exception"); if (exception == null) { exception = DEFAULT_THROW_TYPE; } ConstructorNode cons = exception.getDeclaredConstructor(new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "dummy")}); if (cons == null) { addError("Error during @NotYetImplemented processing: supplied exception " + exception.getNameWithoutPackage() + " doesn't have expected String constructor", methodNode); } if (methodNode.getCode() instanceof BlockStatement && !methodNode.getCode().isEmpty()) { // wrap code in try/catch with return for failure path followed by throws for success path TryCatchStatement tryCatchStatement = tryCatchS(methodNode.getCode()); tryCatchStatement.addCatch(catchS(param(CATCH_TYPE, "ignore"), ReturnStatement.RETURN_NULL_OR_VOID)); ThrowStatement throwStatement = throwS(ctorX(exception, args(constX("Method is marked with @NotYetImplemented but passes unexpectedly")))); methodNode.setCode(block(tryCatchStatement, throwStatement)); } }
Example #6
Source File: StaticTypesMethodReferenceExpressionWriter.java From groovy with Apache License 2.0 | 6 votes |
private Parameter[] createParametersWithExactType(MethodNode abstractMethodNode, ClassNode[] inferredParameterTypes) { Parameter[] originalParameters = abstractMethodNode.getParameters(); // We MUST clone the parameters to avoid impacting the original parameter type of SAM Parameter[] parameters = GeneralUtils.cloneParams(originalParameters); if (parameters == null) { parameters = Parameter.EMPTY_ARRAY; } for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; ClassNode parameterType = parameter.getType(); ClassNode inferredType = inferredParameterTypes[i]; if (null == inferredType) { continue; } ClassNode type = convertParameterType(parameterType, inferredType); parameter.setType(type); parameter.setOriginType(type); } return parameters; }
Example #7
Source File: TraitComposer.java From groovy with Apache License 2.0 | 6 votes |
/** * Creates, if necessary, a super forwarder method, for stackable traits. * @param forwarder a forwarder method * @param genericsSpec */ private static void createSuperForwarder(ClassNode targetNode, MethodNode forwarder, final Map<String,ClassNode> genericsSpec) { List<ClassNode> interfaces = new ArrayList<ClassNode>(Traits.collectAllInterfacesReverseOrder(targetNode, new LinkedHashSet<ClassNode>())); String name = forwarder.getName(); Parameter[] forwarderParameters = forwarder.getParameters(); LinkedHashSet<ClassNode> traits = new LinkedHashSet<ClassNode>(); List<MethodNode> superForwarders = new LinkedList<MethodNode>(); for (ClassNode node : interfaces) { if (Traits.isTrait(node)) { MethodNode method = node.getDeclaredMethod(name, forwarderParameters); if (method!=null) { // a similar method exists, we need a super bridge // trait$super$foo(Class currentTrait, ...) traits.add(node); superForwarders.add(method); } } } for (MethodNode superForwarder : superForwarders) { doCreateSuperForwarder(targetNode, superForwarder, traits.toArray(ClassNode.EMPTY_ARRAY), genericsSpec); } }
Example #8
Source File: InnerClassCompletionVisitor.java From groovy with Apache License 2.0 | 6 votes |
private void addSyntheticMethod(final InnerClassNode node, final String methodName, final int modifiers, final ClassNode returnType, final Parameter[] parameters, final BiConsumer<BlockStatement, Parameter[]> consumer) { MethodNode method = node.getMethod(methodName, parameters); if (method != null) { // GROOVY-8914: pre-compiled classes lose synthetic boolean - TODO fix earlier as per GROOVY-4346 then remove extra check here if (isStatic(node) && !method.isSynthetic() && (method.getModifiers() & ACC_SYNTHETIC) == 0) { // if there is a user-defined methodNode, add compiler error and continue addError("\"" + methodName + "\" implementations are not supported on static inner classes as " + "a synthetic version of \"" + methodName + "\" is added during compilation for the purpose " + "of outer class delegation.", method); } return; } BlockStatement methodBody = block(); consumer.accept(methodBody, parameters); node.addSyntheticMethod(methodName, modifiers, returnType, parameters, ClassNode.EMPTY_ARRAY, methodBody); }
Example #9
Source File: PowsyblDslAstTransformation.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
protected void visit(SourceUnit sourceUnit, ClassCodeExpressionTransformer transformer) { LOGGER.trace("Apply AST transformation"); ModuleNode ast = sourceUnit.getAST(); BlockStatement blockStatement = ast.getStatementBlock(); if (DEBUG) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(AstUtil.toString(blockStatement)); } } List<MethodNode> methods = ast.getMethods(); for (MethodNode methodNode : methods) { methodNode.getCode().visit(transformer); } blockStatement.visit(transformer); if (DEBUG) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(AstUtil.toString(blockStatement)); } } }
Example #10
Source File: ClassCompletionVerifierTest.java From groovy with Apache License 2.0 | 5 votes |
public void testDetectsFinalAndStaticMethodsInInterface() throws Exception { ClassNode node = new ClassNode("zzz", ACC_ABSTRACT | ACC_INTERFACE, ClassHelper.OBJECT_TYPE); node.addMethod(new MethodNode("xxx", ACC_PUBLIC | ACC_FINAL, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)); node.addMethod(new MethodNode("yyy", ACC_PUBLIC | ACC_STATIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)); addDummyConstructor(node); verifier.visitClass(node); checkErrorCount(2); checkErrorMessage(EXPECTED_INTERFACE_FINAL_METHOD_ERROR_MESSAGE); checkErrorMessage(EXPECTED_INTERFACE_STATIC_METHOD_ERROR_MESSAGE); }
Example #11
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 5 votes |
private static void removeMethodWithSuperReturnType(final List<MethodNode> toBeRemoved, final MethodNode one, final MethodNode two) { ClassNode oneRT = one.getReturnType(); ClassNode twoRT = two.getReturnType(); if (isCovariant(oneRT, twoRT)) { toBeRemoved.add(two); } else if (isCovariant(twoRT, oneRT)) { toBeRemoved.add(one); } }
Example #12
Source File: ReadWriteLockASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; final boolean isWriteLock; if (READ_LOCK_TYPE.equals(node.getClassNode())) { isWriteLock = false; } else if (WRITE_LOCK_TYPE.equals(node.getClassNode())) { isWriteLock = true; } else { throw new GroovyBugError("Internal error: expecting [" + READ_LOCK_TYPE.getName() + ", " + WRITE_LOCK_TYPE.getName() + "]" + " but got: " + node.getClassNode().getName()); } String myTypeName = "@" + node.getClassNode().getNameWithoutPackage(); String value = getMemberStringValue(node, "value"); if (parent instanceof MethodNode) { MethodNode mNode = (MethodNode) parent; ClassNode cNode = mNode.getDeclaringClass(); FieldNode lockExpr = determineLock(value, cNode, mNode.isStatic(), myTypeName); if (lockExpr == null) return; // get lock type final MethodCallExpression lockType = callX(varX(lockExpr), isWriteLock ? "writeLock" : "readLock"); lockType.setImplicitThis(false); MethodCallExpression acquireLock = callX(lockType, "lock"); acquireLock.setImplicitThis(false); MethodCallExpression releaseLock = callX(lockType, "unlock"); releaseLock.setImplicitThis(false); Statement originalCode = mNode.getCode(); mNode.setCode(block( stmt(acquireLock), new TryCatchStatement(originalCode, stmt(releaseLock)))); } }
Example #13
Source File: ClassNodeUtils.java From groovy with Apache License 2.0 | 5 votes |
/** * Add methods from the super class. * * @param cNode The ClassNode * @return A map of methods */ public static Map<String, MethodNode> getDeclaredMethodsFromSuper(ClassNode cNode) { ClassNode parent = cNode.getSuperClass(); if (parent == null) { return new HashMap<>(); } return parent.getDeclaredMethodsMap(); }
Example #14
Source File: ASTMethod.java From netbeans with Apache License 2.0 | 5 votes |
@Override public String getReturnType() { if (returnType == null) { returnType = ((MethodNode) node).getReturnType().getNameWithoutPackage(); } return returnType; }
Example #15
Source File: ValidationCodeVisitorSupport.java From bonita-studio with GNU General Public License v2.0 | 5 votes |
public ValidationCodeVisitorSupport(final IValidationContext context, final Expression expression, final ModuleNode node) { dependenciesName = retrieveDependenciesList(expression); okStatus = context.createSuccessStatus(); errorStatus = new MultiStatus(ValidationPlugin.PLUGIN_ID, IStatus.OK, "", null); this.context = context; for (final MethodNode method : node.getMethods()) { declaredMethodsSignature.add(new MethodSignature(method.getName(), method.getParameters().length)); } }
Example #16
Source File: ASTMethod.java From netbeans with Apache License 2.0 | 5 votes |
@Override public ElementKind getKind() { if (node instanceof ConstructorNode) { return ElementKind.CONSTRUCTOR; } else if (node instanceof MethodNode) { return ElementKind.METHOD; } else { return ElementKind.OTHER; } }
Example #17
Source File: StaticTypesCallSiteWriter.java From groovy with Apache License 2.0 | 5 votes |
private void makeDynamicGetProperty(final Expression receiver, final String propertyName, final boolean safe) { MethodNode target = safe ? INVOKERHELPER_GETPROPERTYSAFE_METHOD : INVOKERHELPER_GETPROPERTY_METHOD; MethodCallExpression call = callX( classX(INVOKERHELPER_TYPE), target.getName(), args(receiver, constX(propertyName)) ); call.setImplicitThis(false); call.setMethodTarget(target); call.setSafe(false); call.visit(controller.getAcg()); }
Example #18
Source File: StaticCompilationVisitor.java From groovy with Apache License 2.0 | 5 votes |
private static List<String> methodSpecificGenerics(final MethodNode method) { List<String> genericTypeNames = new ArrayList<>(); GenericsType[] genericsTypes = method.getGenericsTypes(); if (genericsTypes != null) { for (GenericsType gt : genericsTypes) { genericTypeNames.add(gt.getName()); } } return genericTypeNames; }
Example #19
Source File: StaticInvocationWriter.java From groovy with Apache License 2.0 | 5 votes |
private boolean tryPrivateMethod(final MethodNode target, final boolean implicitThis, final Expression receiver, final TupleExpression args, final ClassNode classNode) { ClassNode declaringClass = target.getDeclaringClass(); if ((isPrivateBridgeMethodsCallAllowed(declaringClass, classNode) || isPrivateBridgeMethodsCallAllowed(classNode, declaringClass)) && declaringClass.getNodeMetaData(StaticCompilationMetadataKeys.PRIVATE_BRIDGE_METHODS) != null && !declaringClass.equals(classNode)) { if (tryBridgeMethod(target, receiver, implicitThis, args, classNode)) { return true; } else { checkAndAddCannotCallPrivateMethodError(target, receiver, classNode, declaringClass); } } checkAndAddCannotCallPrivateMethodError(target, receiver, classNode, declaringClass); return false; }
Example #20
Source File: StaticTypesCallSiteWriter.java From groovy with Apache License 2.0 | 5 votes |
private MethodNode getCompatibleMethod(final ClassNode current, final String getAt, final ClassNode aType) { // TODO this really should find "best" match or find all matches and complain about ambiguity if more than one // TODO handle getAt with more than one parameter // TODO handle default getAt methods on Java 8 interfaces for (MethodNode methodNode : current.getDeclaredMethods("getAt")) { if (methodNode.getParameters().length == 1) { ClassNode paramType = methodNode.getParameters()[0].getType(); if (aType.isDerivedFrom(paramType) || aType.declaresInterface(paramType)) { return methodNode; } } } return null; }
Example #21
Source File: ClassNodeUtils.java From groovy with Apache License 2.0 | 5 votes |
/** * Return an existing method if one exists or else create a new method and mark it as {@code @Generated}. * * @see ClassNode#addMethod(String, int, ClassNode, Parameter[], ClassNode[], Statement) */ public static MethodNode addGeneratedMethod(ClassNode cNode, String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { MethodNode existing = cNode.getDeclaredMethod(name, parameters); if (existing != null) return existing; MethodNode result = new MethodNode(name, modifiers, returnType, parameters, exceptions, code); addGeneratedMethod(cNode, result); return result; }
Example #22
Source File: ModifierManager.java From groovy with Apache License 2.0 | 5 votes |
public MethodNode processMethodNode(MethodNode mn) { modifierNodeList.forEach(e -> { mn.setModifiers((e.isVisibilityModifier() ? clearVisibilityModifiers(mn.getModifiers()) : mn.getModifiers()) | e.getOpcode()); if (e.isAnnotation()) { mn.addAnnotation(e.getAnnotationNode()); } }); return mn; }
Example #23
Source File: AutoFinalASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private void process(ASTNode[] nodes, final ClassCodeVisitorSupport visitor) { candidate = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; if (candidate instanceof ClassNode) { processClass((ClassNode) candidate, visitor); } else if (candidate instanceof MethodNode) { processConstructorOrMethod((MethodNode) candidate, visitor); } else if (candidate instanceof FieldNode) { processField((FieldNode) candidate, visitor); } else if (candidate instanceof DeclarationExpression) { processLocalVariable((DeclarationExpression) candidate, visitor); } }
Example #24
Source File: NamedVariantASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private boolean processDelegateParam(final MethodNode mNode, final Parameter mapParam, final ArgumentListExpression args, final List<String> propNames, final Parameter fromParam) { if (isInnerClass(fromParam.getType())) { if (mNode.isStatic()) { addError("Error during " + NAMED_VARIANT + " processing. Delegate type '" + fromParam.getType().getNameWithoutPackage() + "' is an inner class which is not supported.", mNode); return false; } } Set<String> names = new HashSet<>(); List<PropertyNode> props = getAllProperties(names, fromParam.getType(), true, false, false, true, false, true); for (String next : names) { if (hasDuplicates(mNode, propNames, next)) return false; } List<MapEntryExpression> entries = new ArrayList<>(); for (PropertyNode pNode : props) { String name = pNode.getName(); // create entry [name: __namedArgs.getOrDefault('name', initialValue)] Expression defaultValue = Optional.ofNullable(pNode.getInitialExpression()).orElseGet(() -> getDefaultExpression(pNode.getType())); entries.add(entryX(constX(name), callX(varX(mapParam), "getOrDefault", args(constX(name), defaultValue)))); // create annotation @NamedParam(value='name', type=DelegateType) AnnotationNode namedParam = new AnnotationNode(NAMED_PARAM_TYPE); namedParam.addMember("value", constX(name)); namedParam.addMember("type", classX(pNode.getType())); mapParam.addAnnotation(namedParam); } Expression delegateMap = mapX(entries); args.addExpression(castX(fromParam.getType(), delegateMap)); return true; }
Example #25
Source File: GroovyVirtualSourceProvider.java From netbeans with Apache License 2.0 | 5 votes |
private void genMethod(ClassNode clazz, MethodNode methodNode, PrintWriter out, boolean ignoreSynthetic) { String name = methodNode.getName(); if ((ignoreSynthetic && methodNode.isSynthetic()) || name.startsWith("super$")) { // NOI18N return; } // </netbeans> if (methodNode.getName().equals("<clinit>")) { return; } if (!clazz.isInterface()) { printModifiers(out, methodNode.getModifiers()); } printType(methodNode.getReturnType(), out); out.print(" "); out.print(methodNode.getName()); printParams(methodNode, out); ClassNode[] exceptions = methodNode.getExceptions(); if (exceptions != null && exceptions.length > 0) { out.print(" throws "); for (int i = 0; i < exceptions.length; i++) { if (i > 0) { out.print(", "); } printType(exceptions[i], out); } } if ((methodNode.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) { out.println(";"); } else { out.print(" { "); ClassNode retType = methodNode.getReturnType(); printReturn(out, retType); out.println("}"); } }
Example #26
Source File: FixMainScriptTransformer.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void call(SourceUnit source) throws CompilationFailedException { ClassNode scriptClass = AstUtils.getScriptClass(source); if (scriptClass == null) { return; } for (MethodNode methodNode : scriptClass.getMethods()) { if (methodNode.getName().equals("main")) { AstUtils.removeMethod(scriptClass, methodNode); break; } } }
Example #27
Source File: GroovydocVisitor.java From groovy with Apache License 2.0 | 5 votes |
private void setConstructorOrMethodCommon(MethodNode node, SimpleGroovyExecutableMemberDoc methOrCons) { methOrCons.setRawCommentText(getDocContent(node.getGroovydoc())); processModifiers(methOrCons, node, node.getModifiers()); processAnnotations(methOrCons, node); if (node.isAbstract()) { methOrCons.setAbstract(true); } for (Parameter param : node.getParameters()) { SimpleGroovyParameter p = new SimpleGroovyParameter(param.getName()); p.setType(new SimpleGroovyType(makeType(param.getType()))); processAnnotations(p, param); methOrCons.add(p); } }
Example #28
Source File: StaticTypesLambdaWriter.java From groovy with Apache License 2.0 | 5 votes |
private ClassNode getOrAddLambdaClass(final LambdaExpression expression, final int modifiers, final MethodNode abstractMethod) { return lambdaClassNodes.computeIfAbsent(expression, key -> { ClassNode lambdaClass = createLambdaClass(expression, modifiers, abstractMethod); controller.getAcg().addInnerClass(lambdaClass); lambdaClass.addInterface(GENERATED_LAMBDA_TYPE); lambdaClass.putNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE, Boolean.TRUE); lambdaClass.putNodeMetaData(WriterControllerFactory.class, (WriterControllerFactory) x -> controller); return lambdaClass; }); }
Example #29
Source File: DelegateASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private static List<String> genericPlaceholderNames(MethodNode candidate) { GenericsType[] candidateGenericsTypes = candidate.getGenericsTypes(); List<String> names = new ArrayList<String>(); if (candidateGenericsTypes != null) { for (GenericsType gt : candidateGenericsTypes) { names.add(gt.getName()); } } return names; }
Example #30
Source File: ExternalStrategy.java From groovy with Apache License 2.0 | 5 votes |
private static MethodNode createBuildMethod(BuilderASTTransformation transform, AnnotationNode anno, ClassNode sourceClass, List<PropertyInfo> fields) { String buildMethodName = transform.getMemberStringValue(anno, "buildMethodName", "build"); final BlockStatement body = new BlockStatement(); Expression sourceClassInstance = initializeInstance(sourceClass, fields, body); body.addStatement(returnS(sourceClassInstance)); return new MethodNode(buildMethodName, ACC_PUBLIC, sourceClass, NO_PARAMS, NO_EXCEPTIONS, body); }