Java Code Examples for org.codehaus.groovy.ast.ClassNode#getMethods()
The following examples show how to use
org.codehaus.groovy.ast.ClassNode#getMethods() .
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: Verifier.java From groovy with Apache License 2.0 | 6 votes |
private static void checkForDuplicateMethods(ClassNode cn) { Set<String> descriptors = new HashSet<String>(); for (MethodNode mn : cn.getMethods()) { if (mn.isSynthetic()) continue; String mySig = methodDescriptorWithoutReturnType(mn); if (descriptors.contains(mySig)) { if (mn.isScriptBody() || mySig.equals(scriptBodySignatureWithoutReturnType(cn))) { throw new RuntimeParserException("The method " + mn.getText() + " is a duplicate of the one declared for this script's body code", sourceOf(mn)); } else { throw new RuntimeParserException("The method " + mn.getText() + " duplicates another method of the same signature", sourceOf(mn)); } } descriptors.add(mySig); } }
Example 2
Source File: AnnotationVisitor.java From groovy with Apache License 2.0 | 6 votes |
public void checkCircularReference(ClassNode searchClass, ClassNode attrType, Expression startExp) { if (!isValidAnnotationClass(attrType)) return; if (!(startExp instanceof AnnotationConstantExpression)) { addError("Found '" + startExp.getText() + "' when expecting an Annotation Constant", startExp); return; } AnnotationConstantExpression ace = (AnnotationConstantExpression) startExp; AnnotationNode annotationNode = (AnnotationNode) ace.getValue(); if (annotationNode.getClassNode().equals(searchClass)) { addError("Circular reference discovered in " + searchClass.getName(), startExp); return; } ClassNode cn = annotationNode.getClassNode(); for (MethodNode method : cn.getMethods()) { if (method.getReturnType().equals(searchClass)) { addError("Circular reference discovered in " + cn.getName(), startExp); } ReturnStatement code = (ReturnStatement) method.getCode(); if (code == null) continue; checkCircularReference(searchClass, method.getReturnType(), code.getExpression()); } }
Example 3
Source File: TestMethodUtil.java From netbeans with Apache License 2.0 | 6 votes |
/** * Given a {@link ClassNode ClassNode}, finds and returns the * {@link MethodNode MethodNode} for the given line and column. It is * possible in some situations for this to be null. * * @param cn the ClassNode * @param line the line * @param col the column * @return the MethodNode for the line and column (cursor) */ public static MethodNode getMethodNodeForLineAndColumn(final ClassNode cn, final int line, final int col) { MethodNode ret = null; if (cn != null) { final List<MethodNode> methods = cn.getMethods(); for (MethodNode mn : methods) { if (isBetweenLinesAndColumns(mn.getLineNumber(), mn.getColumnNumber(), mn.getLastLineNumber(), mn.getLastColumnNumber(), line, col)) { return mn; } } } return ret; }
Example 4
Source File: StaticTypesClosureWriter.java From groovy with Apache License 2.0 | 6 votes |
@Override protected ClassNode createClosureClass(final ClosureExpression expression, final int mods) { ClassNode closureClass = super.createClosureClass(expression, mods); List<MethodNode> methods = closureClass.getDeclaredMethods("call"); List<MethodNode> doCall = closureClass.getMethods("doCall"); if (doCall.size() != 1) { throw new GroovyBugError("Expected to find one (1) doCall method on generated closure, but found " + doCall.size()); } MethodNode doCallMethod = doCall.get(0); if (methods.isEmpty() && doCallMethod.getParameters().length == 1) { createDirectCallMethod(closureClass, doCallMethod); } MethodTargetCompletionVisitor visitor = new MethodTargetCompletionVisitor(doCallMethod); Object dynamic = expression.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION); if (dynamic != null) { doCallMethod.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, dynamic); } for (MethodNode method : methods) { visitor.visitMethod(method); } closureClass.putNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE, Boolean.TRUE); return closureClass; }
Example 5
Source File: FixMainScriptTransformer.java From pushfish-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 6
Source File: AnnotationVisitor.java From groovy with Apache License 2.0 | 5 votes |
private ClassNode getAttributeType(AnnotationNode node, String attrName) { ClassNode classNode = node.getClassNode(); List methods = classNode.getMethods(attrName); // if size is >1, then the method was overwritten or something, we ignore that // if it is an error, we have to test it at another place. But size==0 is // an error, because it means that no such attribute exists. if (methods.isEmpty()) { addError("'" + attrName + "'is not part of the annotation " + classNode.getNameWithoutPackage(), node); return ClassHelper.OBJECT_TYPE; } MethodNode method = (MethodNode) methods.get(0); return method.getReturnType(); }
Example 7
Source File: AnnotationVisitor.java From groovy with Apache License 2.0 | 5 votes |
private boolean checkIfMandatoryAnnotationValuesPassed(AnnotationNode node) { boolean ok = true; Map attributes = node.getMembers(); ClassNode classNode = node.getClassNode(); for (MethodNode mn : classNode.getMethods()) { String methodName = mn.getName(); // if the annotation attribute has a default, getCode() returns a ReturnStatement with the default value if (mn.getCode() == null && !attributes.containsKey(methodName)) { addError("No explicit/default value found for annotation attribute '" + methodName + "'", node); ok = false; } } return ok; }
Example 8
Source File: ClassCompletionVerifier.java From groovy with Apache License 2.0 | 5 votes |
private void checkInterfaceMethodVisibility(ClassNode node) { if (!node.isInterface()) return; for (MethodNode method : node.getMethods()) { if (method.isPrivate()) { addError("Method '" + method.getName() + "' is private but should be public in " + getDescription(currentClass) + ".", method); } else if (method.isProtected()) { addError("Method '" + method.getName() + "' is protected but should be public in " + getDescription(currentClass) + ".", method); } } }
Example 9
Source File: BindableASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
/** * Snoops through the declaring class and all parents looking for methods * <code>void addPropertyChangeListener(PropertyChangeListener)</code>, * <code>void removePropertyChangeListener(PropertyChangeListener)</code>, and * <code>void firePropertyChange(String, Object, Object)</code>. If any are defined all * must be defined or a compilation error results. * * @param declaringClass the class to search * @param sourceUnit the source unit, for error reporting. {@code @NotNull}. * @return true if property change support should be added */ protected boolean needsPropertyChangeSupport(ClassNode declaringClass, SourceUnit sourceUnit) { boolean foundAdd = false, foundRemove = false, foundFire = false; ClassNode consideredClass = declaringClass; while (consideredClass!= null) { for (MethodNode method : consideredClass.getMethods()) { // just check length, MOP will match it up foundAdd = foundAdd || method.getName().equals("addPropertyChangeListener") && method.getParameters().length == 1; foundRemove = foundRemove || method.getName().equals("removePropertyChangeListener") && method.getParameters().length == 1; foundFire = foundFire || method.getName().equals("firePropertyChange") && method.getParameters().length == 3; if (foundAdd && foundRemove && foundFire) { return false; } } consideredClass = consideredClass.getSuperClass(); } // check if a super class has @Bindable annotations consideredClass = declaringClass.getSuperClass(); while (consideredClass!=null) { if (hasBindableAnnotation(consideredClass)) return false; for (FieldNode field : consideredClass.getFields()) { if (hasBindableAnnotation(field)) return false; } consideredClass = consideredClass.getSuperClass(); } if (foundAdd || foundRemove || foundFire) { sourceUnit.getErrorCollector().addErrorAndContinue( new SimpleMessage("@Bindable cannot be processed on " + declaringClass.getName() + " because some but not all of addPropertyChangeListener, removePropertyChange, and firePropertyChange were declared in the current or super classes.", sourceUnit) ); return false; } return true; }
Example 10
Source File: UnionTypeClassNode.java From groovy with Apache License 2.0 | 5 votes |
@Override public List<MethodNode> getMethods() { List<MethodNode> nodes = new LinkedList<MethodNode>(); for (ClassNode delegate : delegates) { List<MethodNode> methods = delegate.getMethods(); if (methods != null) nodes.addAll(methods); } return nodes; }
Example 11
Source File: SecureASTCustomizer.java From groovy with Apache License 2.0 | 5 votes |
protected static List<MethodNode> filterMethods(ClassNode owner) { List<MethodNode> result = new LinkedList<>(); List<MethodNode> methods = owner.getMethods(); for (MethodNode method : methods) { if (method.getDeclaringClass() == owner && !method.isSynthetic()) { if ("main".equals(method.getName()) || "run".equals(method.getName()) && owner.isScriptBody()) continue; result.add(method); } } return result; }
Example 12
Source File: StaticTypesMethodReferenceExpressionWriter.java From groovy with Apache License 2.0 | 5 votes |
private MethodNode findMethodRefMethod(String methodRefName, Parameter[] abstractMethodParameters, Expression typeOrTargetRef) { ClassNode typeOrTargetRefType = typeOrTargetRef.getType(); List<MethodNode> methodNodeList = typeOrTargetRefType.getMethods(methodRefName); Set<MethodNode> dgmMethodNodeSet = findDGMMethodsForClassNode(controller.getSourceUnit().getClassLoader(), typeOrTargetRefType, methodRefName); List<MethodNode> allMethodNodeList = new LinkedList<>(methodNodeList); allMethodNodeList.addAll(dgmMethodNodeSet); ClassNode classNode = controller.getClassNode(); List<MethodNode> candidates = new LinkedList<>(); for (MethodNode mn : filterMethodsByVisibility(allMethodNodeList, classNode)) { Parameter[] parameters = abstractMethodParameters; if (isTypeReferingInstanceMethod(typeOrTargetRef, mn)) { if (0 == abstractMethodParameters.length) { continue; } parameters = removeFirstParameter(abstractMethodParameters); } Parameter[] methodParameters; if (isExtensionMethod(mn)) { methodParameters = removeFirstParameter(((ExtensionMethodNode) mn).getExtensionMethodNode().getParameters()); } else { methodParameters = mn.getParameters(); } if (ParameterUtils.parametersCompatible(parameters, methodParameters)) { candidates.add(mn); } } return chooseMethodRefMethodCandidate(typeOrTargetRef, candidates); }
Example 13
Source File: EnumVisitor.java From groovy with Apache License 2.0 | 5 votes |
private static void checkForAbstractMethods(final ClassNode enumClass) { for (MethodNode method : enumClass.getMethods()) { if (method.isAbstract()) { // make the class abstract also; see Effective Java p.152 enumClass.setModifiers(enumClass.getModifiers() | ACC_ABSTRACT); break; } } }
Example 14
Source File: SuperCallTraitTransformer.java From groovy with Apache License 2.0 | 4 votes |
private Expression transformBinaryExpression(final BinaryExpression exp) { Expression trn = super.transform(exp); if (trn instanceof BinaryExpression) { BinaryExpression bin = (BinaryExpression) trn; Expression leftExpression = bin.getLeftExpression(); if (bin.getOperation().getType() == Types.EQUAL && leftExpression instanceof PropertyExpression) { ClassNode traitReceiver = null; PropertyExpression leftPropertyExpression = (PropertyExpression) leftExpression; if (isTraitSuperPropertyExpression(leftPropertyExpression.getObjectExpression())) { PropertyExpression pexp = (PropertyExpression) leftPropertyExpression.getObjectExpression(); traitReceiver = pexp.getObjectExpression().getType(); } if (traitReceiver!=null) { // A.super.foo = ... TraitHelpersTuple helpers = Traits.findHelpers(traitReceiver); ClassNode helper = helpers.getHelper(); String setterName = MetaProperty.getSetterName(leftPropertyExpression.getPropertyAsString()); List<MethodNode> methods = helper.getMethods(setterName); for (MethodNode method : methods) { Parameter[] parameters = method.getParameters(); if (parameters.length==2 && parameters[0].getType().equals(traitReceiver)) { ArgumentListExpression args = new ArgumentListExpression( new VariableExpression("this"), transform(exp.getRightExpression()) ); MethodCallExpression setterCall = new MethodCallExpression( new ClassExpression(helper), setterName, args ); setterCall.setMethodTarget(method); setterCall.setImplicitThis(false); return setterCall; } } return bin; } } } return trn; }
Example 15
Source File: ClassCompletionVerifier.java From groovy with Apache License 2.0 | 4 votes |
private void checkNoStaticMethodWithSameSignatureAsNonStatic(final ClassNode node) { ClassNode parent = node.getSuperClass(); Map<String, MethodNode> result; // start with methods from the parent if any if (parent != null) { result = parent.getDeclaredMethodsMap(); } else { result = new HashMap<String, MethodNode>(); } // add in unimplemented abstract methods from the interfaces ClassNodeUtils.addDeclaredMethodsFromInterfaces(node, result); for (MethodNode methodNode : node.getMethods()) { MethodNode mn = result.get(methodNode.getTypeDescriptor()); if (mn != null && (mn.isStatic() ^ methodNode.isStatic()) && !methodNode.isStaticConstructor()) { if (!mn.isAbstract()) continue; ClassNode declaringClass = mn.getDeclaringClass(); ClassNode cn = declaringClass.getOuterClass(); if (cn == null && declaringClass.isResolved()) { // in case of a precompiled class, the outerclass is unknown Class typeClass = declaringClass.getTypeClass(); typeClass = typeClass.getEnclosingClass(); if (typeClass != null) { cn = ClassHelper.make(typeClass); } } if (!Traits.isTrait(cn)) { ASTNode errorNode = methodNode; String name = mn.getName(); if (errorNode.getLineNumber() == -1) { // try to get a better error message location based on the property for (PropertyNode propertyNode : node.getProperties()) { if (name.startsWith("set") || name.startsWith("get") || name.startsWith("is")) { String propName = Verifier.capitalize(propertyNode.getField().getName()); String shortName = name.substring(name.startsWith("is") ? 2 : 3); if (propName.equals(shortName)) { errorNode = propertyNode; break; } } } } addError("The " + getDescription(methodNode) + " is already defined in " + getDescription(node) + ". You cannot have both a static and an instance method with the same signature", errorNode); } } result.put(methodNode.getTypeDescriptor(), methodNode); } }
Example 16
Source File: Verifier.java From groovy with Apache License 2.0 | 4 votes |
private static String scriptBodySignatureWithoutReturnType(ClassNode cn) { for (MethodNode mn : cn.getMethods()) { if (mn.isScriptBody()) return methodDescriptorWithoutReturnType(mn); } return null; }
Example 17
Source File: ClassCompletionVerifier.java From groovy with Apache License 2.0 | 4 votes |
private void checkMethodsForWeakerAccess(ClassNode cn) { for (MethodNode method : cn.getMethods()) { checkMethodForWeakerAccessPrivileges(method, cn); } }
Example 18
Source File: JavaStubGenerator.java From groovy with Apache License 2.0 | 4 votes |
private void printMethods(PrintWriter out, ClassNode classNode, boolean isEnum) { if (!isEnum) printConstructors(out, classNode); @SuppressWarnings("unchecked") List<MethodNode> methods = (List) propertyMethods.clone(); methods.addAll(classNode.getMethods()); for (MethodNode method : methods) { if (isEnum && method.isSynthetic()) { // skip values() method and valueOf(String) String name = method.getName(); Parameter[] params = method.getParameters(); if (name.equals("values") && params.length == 0) continue; if (name.equals("valueOf") && params.length == 1 && params[0].getType().equals(ClassHelper.STRING_TYPE)) { continue; } } printMethod(out, classNode, method); } // print the methods from traits for (ClassNode trait : findTraits(classNode)) { Map<String, ClassNode> generics = trait.isUsingGenerics() ? createGenericsSpec(trait) : null; List<MethodNode> traitMethods = trait.getMethods(); for (MethodNode traitOrigMethod : traitMethods) { // GROOVY-9606: replace method return type and parameter type placeholder with resolved type from trait generics MethodNode traitMethod = correctToGenericsSpec(generics, traitOrigMethod); MethodNode existingMethod = classNode.getMethod(traitMethod.getName(), traitMethod.getParameters()); if (existingMethod != null) continue; for (MethodNode propertyMethod : propertyMethods) { if (propertyMethod.getName().equals(traitMethod.getName())) { boolean sameParams = sameParameterTypes(propertyMethod, traitMethod); if (sameParams) { existingMethod = propertyMethod; break; } } } if (existingMethod != null) continue; boolean isCandidate = isCandidateTraitMethod(trait, traitMethod); if (!isCandidate) continue; printMethod(out, classNode, traitMethod); } } }
Example 19
Source File: ClassNodeUtils.java From groovy with Apache License 2.0 | 4 votes |
/** * Returns true if the given method has a possibly matching static method with the given name and arguments. * Handles default arguments and optionally spread expressions. * * @param cNode the ClassNode of interest * @param name the name of the method of interest * @param arguments the arguments to match against * @param trySpread whether to try to account for SpreadExpressions within the arguments * @return true if a matching method was found */ public static boolean hasPossibleStaticMethod(ClassNode cNode, String name, Expression arguments, boolean trySpread) { int count = 0; boolean foundSpread = false; if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; for (Expression arg : tuple.getExpressions()) { if (arg instanceof SpreadExpression) { foundSpread = true; } else { count++; } } } else if (arguments instanceof MapExpression) { count = 1; } for (MethodNode method : cNode.getMethods(name)) { if (method.isStatic()) { Parameter[] parameters = method.getParameters(); // do fuzzy match for spread case: count will be number of non-spread args if (trySpread && foundSpread && parameters.length >= count) return true; if (parameters.length == count) return true; // handle varargs case if (parameters.length > 0 && parameters[parameters.length - 1].getType().isArray()) { if (count >= parameters.length - 1) return true; // fuzzy match any spread to a varargs if (trySpread && foundSpread) return true; } // handle parameters with default values int nonDefaultParameters = 0; for (Parameter parameter : parameters) { if (!parameter.hasInitialExpression()) { nonDefaultParameters++; } } if (count < parameters.length && nonDefaultParameters <= count) { return true; } // TODO handle spread with nonDefaultParams? } } return false; }
Example 20
Source File: MethodInference.java From netbeans with Apache License 2.0 | 4 votes |
private static MethodNode tryFindPossibleMethod(ClassNode callerType, String methodName, List<ClassNode> paramTypes, boolean isStatic) { int count = paramTypes.size(); MethodNode res = null; ClassNode node = callerType; do { for (MethodNode method : node.getMethods(methodName)) { if (isStatic && !method.isStatic()) { continue; } if (method.getParameters().length == count) { boolean match = true; for (int i = 0; i != count; ++i) { if (!paramTypes.get(i).isDerivedFrom(method.getParameters()[i].getType())) { match = false; break; } } if (match) { if (res == null) { res = method; } else { if (res.getParameters().length != count) { return null; } if (node.equals(callerType)) { return null; } match = true; for (int i = 0; i != count; ++i) { if (!res.getParameters()[i].getType().equals(method.getParameters()[i].getType())) { match = false; break; } } if (!match) { return null; } } } } } node = node.getSuperClass(); } while (node != null); return res; }