Java Code Examples for org.codehaus.groovy.ast.MethodNode#getName()
The following examples show how to use
org.codehaus.groovy.ast.MethodNode#getName() .
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 |
@Override public void visitMethod(MethodNode node) { // GROOVY-3712 - if it's an MOP method, it's an error as they aren't supposed to exist before ACG is invoked if (MopWriter.isMopMethod(node.getName())) { throw new RuntimeParserException("Found unexpected MOP methods in the class node for " + classNode.getName() + "(" + node.getName() + ")", classNode); } adjustTypesIfStaticMainMethod(node); this.methodNode = node; addReturnIfNeeded(node); Statement stmt = node.getCode(); if (stmt != null) { stmt.visit(new VerifierCodeVisitor(getClassNode())); } }
Example 2
Source File: AbstractExtensionMethodCache.java From groovy with Apache License 2.0 | 6 votes |
private void accumulate(Map<String, List<MethodNode>> accumulator, boolean isStatic, MethodNode metaMethod, Function<MethodNode, String> mapperFunction) { Parameter[] types = metaMethod.getParameters(); Parameter[] parameters = new Parameter[types.length - 1]; System.arraycopy(types, 1, parameters, 0, parameters.length); ExtensionMethodNode node = new ExtensionMethodNode( metaMethod, metaMethod.getName(), metaMethod.getModifiers(), metaMethod.getReturnType(), parameters, ClassNode.EMPTY_ARRAY, null, isStatic); node.setGenericsTypes(metaMethod.getGenericsTypes()); ClassNode declaringClass = types[0].getType(); node.setDeclaringClass(declaringClass); String key = mapperFunction.apply(metaMethod); List<MethodNode> nodes = accumulator.computeIfAbsent(key, k -> new ArrayList<>()); nodes.add(node); }
Example 3
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 4
Source File: InitializerStrategy.java From groovy with Apache License 2.0 | 5 votes |
private static void createBuildeeMethods(ClassNode buildee, MethodNode mNode, ClassNode builder, List<FieldNode> fields) { ClassNode paramType = makeClassSafeWithGenerics(builder, setGenTypes(fields.size())); List<Expression> argsList = new ArrayList<Expression>(); Parameter initParam = param(paramType, "initializer"); for (FieldNode fieldNode : fields) { argsList.add(propX(varX(initParam), fieldNode.getName())); } String newName = "$" + mNode.getName(); // can't have private and public methods of the same name, so rename original addGeneratedMethod(buildee, mNode.getName(), ACC_PUBLIC | ACC_STATIC, mNode.getReturnType(), params(param(paramType, "initializer")), NO_EXCEPTIONS, block(stmt(callX(buildee, newName, args(argsList))))); renameMethod(buildee, mNode, newName); }
Example 5
Source File: GeneratorContext.java From groovy with Apache License 2.0 | 5 votes |
private String getNextInnerName(ClassNode owner, ClassNode enclosingClass, MethodNode enclosingMethod, String classifier) { String methodName = ""; if (enclosingMethod != null) { methodName = enclosingMethod.getName(); if (enclosingClass.isDerivedFrom(ClassHelper.CLOSURE_TYPE)) { methodName = ""; } else { methodName = "_" + encodeAsValidClassName(methodName); } } return methodName + "_" + classifier + closureClassIdx++; }
Example 6
Source File: Verifier.java From groovy with Apache License 2.0 | 5 votes |
protected void addPropertyMethod(MethodNode method) { classNode.addMethod(method); markAsGenerated(classNode, method); // GROOVY-4415 / GROOVY-4645: check that there's no abstract method which corresponds to this one String methodName = method.getName(); Parameter[] parameters = method.getParameters(); ClassNode methodReturnType = method.getReturnType(); for (MethodNode node : classNode.getAbstractMethods()) { if (!node.getDeclaringClass().equals(classNode)) continue; if (node.getName().equals(methodName) && node.getParameters().length == parameters.length) { if (parameters.length == 1) { // setter ClassNode abstractMethodParameterType = node.getParameters()[0].getType(); ClassNode methodParameterType = parameters[0].getType(); if (!methodParameterType.isDerivedFrom(abstractMethodParameterType) && !methodParameterType.implementsInterface(abstractMethodParameterType)) { continue; } } ClassNode nodeReturnType = node.getReturnType(); if (!methodReturnType.isDerivedFrom(nodeReturnType) && !methodReturnType.implementsInterface(nodeReturnType)) { continue; } // matching method, remove abstract status and use the same body node.setModifiers(node.getModifiers() ^ ACC_ABSTRACT); node.setCode(method.getCode()); } } }
Example 7
Source File: MopWriter.java From groovy with Apache License 2.0 | 5 votes |
/** * Creates a MOP method name from a method. * * @param method the method to be called by the mop method * @param useThis if true, then it is a call on "this", "super" else * @return the mop method name */ public static String getMopMethodName(MethodNode method, boolean useThis) { ClassNode declaringNode = method.getDeclaringClass(); int distance = 0; for (; declaringNode != null; declaringNode = declaringNode.getSuperClass()) { distance += 1; } return (useThis ? "this" : "super") + "$" + distance + "$" + method.getName(); }
Example 8
Source File: ClassCompletionVerifier.java From groovy with Apache License 2.0 | 5 votes |
private void checkMethodsForIncorrectName(ClassNode cn) { if (!strictNames) return; List<MethodNode> methods = cn.getAllDeclaredMethods(); for (MethodNode mNode : methods) { String name = mNode.getName(); if (name.equals("<init>") || name.equals("<clinit>")) continue; // Groovy allows more characters than Character.isValidJavaIdentifier() would allow // if we find a good way to encode special chars we could remove (some of) these checks for (String ch : INVALID_NAME_CHARS) { if (name.contains(ch)) { addError("You are not allowed to have '" + ch + "' in a method name", mNode); } } } }
Example 9
Source File: TraitASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private MethodNode processMethod(ClassNode traitClass, ClassNode traitHelperClass, MethodNode methodNode, ClassNode fieldHelper, Collection<String> knownFields) { Parameter[] initialParams = methodNode.getParameters(); Parameter[] newParams = new Parameter[initialParams.length + 1]; newParams[0] = createSelfParameter(traitClass, methodNode.isStatic()); System.arraycopy(initialParams, 0, newParams, 1, initialParams.length); final int mod = methodNode.isPrivate() ? ACC_PRIVATE : ACC_PUBLIC | (methodNode.isFinal() ? ACC_FINAL : 0); MethodNode mNode = new MethodNode( methodNode.getName(), mod | ACC_STATIC, methodNode.getReturnType(), newParams, methodNode.getExceptions(), processBody(new VariableExpression(newParams[0]), methodNode.getCode(), traitClass, traitHelperClass, fieldHelper, knownFields) ); mNode.setSourcePosition(methodNode); mNode.addAnnotations(filterAnnotations(methodNode.getAnnotations())); mNode.setGenericsTypes(methodNode.getGenericsTypes()); if (methodNode.isAbstract()) { mNode.setModifiers(ACC_PUBLIC | ACC_ABSTRACT); } else { methodNode.addAnnotation(new AnnotationNode(Traits.IMPLEMENTED_CLASSNODE)); } methodNode.setCode(null); if (!methodNode.isPrivate() && !methodNode.isStatic()) { methodNode.setModifiers(ACC_PUBLIC | ACC_ABSTRACT); } return mNode; }
Example 10
Source File: TraitComposer.java From groovy with Apache License 2.0 | 5 votes |
private static SyntaxException createException(ClassNode trait, ClassNode targetNode, MethodNode forwarder, MethodNode existingMethod) { String middle; ASTNode errorTarget; if (existingMethod.getLineNumber() == -1) { // came from a trait errorTarget = targetNode; List<AnnotationNode> allAnnos = existingMethod.getAnnotations(Traits.TRAITBRIDGE_CLASSNODE); AnnotationNode bridgeAnno = allAnnos == null ? null : allAnnos.get(0); String fromTrait = null; if (bridgeAnno != null) { Expression traitClass = bridgeAnno.getMember("traitClass"); if (traitClass instanceof ClassExpression) { ClassExpression ce = (ClassExpression) traitClass; fromTrait = ce.getType().getNameWithoutPackage(); } } middle = "in '" + targetNode.getNameWithoutPackage(); if (fromTrait != null) { middle += "' from trait '" + fromTrait; } } else { errorTarget = existingMethod; middle = "declared in '" + targetNode.getNameWithoutPackage(); } String message = "The static '" + forwarder.getName() + "' method " + middle + "' conflicts with the instance method having the same signature from trait '" + trait.getNameWithoutPackage() + "'"; return new SyntaxException(message, errorTarget); }
Example 11
Source File: MethodNodeUtils.java From groovy with Apache License 2.0 | 5 votes |
/** * For a method node potentially representing a property, returns the name of the property. * * @param mNode a MethodNode * @return the property name without the get/set/is prefix if a property or null */ public static String getPropertyName(MethodNode mNode) { boolean startsWithGet = false; boolean startsWithSet = false; boolean startsWithIs = false; String name = mNode.getName(); if ((startsWithGet = name.startsWith("get")) || (startsWithSet = name.startsWith("set")) || (startsWithIs = name.startsWith("is"))) { final String tmpPname = name.substring(startsWithIs ? 2 : 3); if (!tmpPname.isEmpty()) { if (startsWithSet) { if (mNode.getParameters().length == 1) { return decapitalize(tmpPname); } } else if (mNode.getParameters().length == 0 && !ClassHelper.VOID_TYPE.equals(mNode.getReturnType())) { if (startsWithGet || ClassHelper.boolean_TYPE.equals(mNode.getReturnType())) { return decapitalize(tmpPname); } } } } return null; }
Example 12
Source File: TransformationHandler.java From netbeans with Apache License 2.0 | 5 votes |
private static CompletionItem createMethodProposal( final MethodNode method, final boolean prefixed, final int anchorOffset) { final String methodName = method.getName(); final String[] methodParams = getMethodParams(method); final String returnType = method.getReturnType().getName(); return CompletionItem.forDynamicMethod(anchorOffset, methodName, methodParams, returnType, prefixed); }
Example 13
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 14
Source File: GroovyLanguageServerUtils.java From groovy-language-server with Apache License 2.0 | 4 votes |
public static SymbolInformation astNodeToSymbolInformation(MethodNode node, URI uri, String parentName) { return new SymbolInformation(node.getName(), astNodeToSymbolKind(node), astNodeToLocation(node, uri), parentName); }
Example 15
Source File: BaseScriptASTTransformation.java From groovy with Apache License 2.0 | 4 votes |
private void changeBaseScriptType(final AnnotatedNode parent, final ClassNode cNode, final ClassNode baseScriptType) { if (!cNode.isScriptBody()) { addError("Annotation " + MY_TYPE_NAME + " can only be used within a Script.", parent); return; } if (!baseScriptType.isScript()) { addError("Declared type " + baseScriptType + " does not extend groovy.lang.Script class!", parent); return; } cNode.setSuperClass(baseScriptType); // Method in base script that will contain the script body code. MethodNode runScriptMethod = ClassHelper.findSAM(baseScriptType); // If they want to use a name other than than "run", then make the change. if (isCustomScriptBodyMethod(runScriptMethod)) { MethodNode defaultMethod = cNode.getDeclaredMethod("run", Parameter.EMPTY_ARRAY); // GROOVY-6706: Sometimes an NPE is thrown here. // The reason is that our transform is getting called more than once sometimes. if (defaultMethod != null) { cNode.removeMethod(defaultMethod); MethodNode methodNode = new MethodNode(runScriptMethod.getName(), runScriptMethod.getModifiers() & ~ACC_ABSTRACT , runScriptMethod.getReturnType(), runScriptMethod.getParameters(), runScriptMethod.getExceptions() , defaultMethod.getCode()); // The AST node metadata has the flag that indicates that this method is a script body. // It may also be carrying data for other AST transforms. methodNode.copyNodeMetaData(defaultMethod); addGeneratedMethod(cNode, methodNode); } } // If the new script base class does not have a contextual constructor (g.l.Binding), then we won't either. // We have to do things this way (and rely on just default constructors) because the logic that generates // the constructors for our script class have already run. if (cNode.getSuperClass().getDeclaredConstructor(CONTEXT_CTOR_PARAMETERS) == null) { ConstructorNode orphanedConstructor = cNode.getDeclaredConstructor(CONTEXT_CTOR_PARAMETERS); cNode.removeConstructor(orphanedConstructor); } }
Example 16
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 17
Source File: BeanUtils.java From groovy with Apache License 2.0 | 4 votes |
public static void addPseudoProperties(ClassNode origType, ClassNode cNode, List<PropertyNode> result, Set<String> names, boolean includeStatic, boolean includePseudoGetters, boolean includePseudoSetters) { if (!includePseudoGetters && !includePseudoSetters) return; List<MethodNode> methods = cNode.getAllDeclaredMethods(); for (MethodNode mNode : methods) { if (!includeStatic && mNode.isStatic()) continue; if (hasAnnotation(mNode, INTERNAL_TYPE)) continue; String name = mNode.getName(); if ((name.length() <= 3 && !name.startsWith(IS_PREFIX)) || name.equals("getClass") || name.equals("getMetaClass") || name.equals("getDeclaringClass")) { // Optimization: skip invalid propertyNames continue; } if (mNode.getDeclaringClass() != origType && mNode.isPrivate()) { // skip private super methods continue; } int paramCount = mNode.getParameters().length; ClassNode paramType = mNode.getReturnType(); String propName = null; Statement getter = null; Statement setter = null; if (paramCount == 0) { if (includePseudoGetters && name.startsWith(GET_PREFIX)) { // Simple getter propName = decapitalize(name.substring(3)); getter = mNode.getCode(); } else if (includePseudoGetters && name.startsWith(IS_PREFIX) && paramType.equals(ClassHelper.boolean_TYPE)) { // boolean getter propName = decapitalize(name.substring(2)); getter = mNode.getCode(); } } else if (paramCount == 1) { if (includePseudoSetters && name.startsWith(SET_PREFIX)) { // Simple setter propName = decapitalize(name.substring(3)); setter = mNode.getCode(); paramType = mNode.getParameters()[0].getType(); } } if (propName != null) { addIfMissing(cNode, result, names, mNode, paramType, propName, getter, setter); } } }
Example 18
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 19
Source File: ASTTransformer.java From pom-manipulation-ext with Apache License 2.0 | 4 votes |
private void changeBaseScriptType(final AnnotatedNode parent, final ClassNode cNode, final ClassNode baseScriptType) { if (!cNode.isScriptBody()) { addError( "Annotation " + getType() + " can only be used within a Script.", parent); return; } if (!baseScriptType.isScript()) { addError("Declared type " + baseScriptType + " does not extend groovy.lang.Script class!", parent); return; } List<AnnotationNode> annotations = parent.getAnnotations( DEPRECATED_COMMAND_TYPE ); if (cNode.getAnnotations( DEPRECATED_COMMAND_TYPE ).isEmpty()) { // #388 prevent "Duplicate annotation for class" AnnotationFormatError cNode.addAnnotations(annotations); } annotations = parent.getAnnotations( COMMAND_TYPE ); if (cNode.getAnnotations( COMMAND_TYPE ).isEmpty()) { // #388 prevent "Duplicate annotation for class" AnnotationFormatError cNode.addAnnotations(annotations); } cNode.setSuperClass(baseScriptType); // Method in base script that will contain the script body code. MethodNode runScriptMethod = ClassHelper.findSAM(baseScriptType); // If they want to use a name other than than "run", then make the change. if (isCustomScriptBodyMethod(runScriptMethod)) { MethodNode defaultMethod = cNode.getDeclaredMethod("run", Parameter.EMPTY_ARRAY); // GROOVY-6706: Sometimes an NPE is thrown here. // The reason is that our transform is getting called more than once sometimes. if (defaultMethod != null) { cNode.removeMethod(defaultMethod); MethodNode methodNode = new MethodNode(runScriptMethod.getName(), runScriptMethod.getModifiers() & ~ACC_ABSTRACT , runScriptMethod.getReturnType(), runScriptMethod.getParameters(), runScriptMethod.getExceptions() , defaultMethod.getCode()); // The AST node metadata has the flag that indicates that this method is a script body. // It may also be carrying data for other AST transforms. methodNode.copyNodeMetaData(defaultMethod); addGeneratedMethod(cNode, methodNode); } } // If the new script base class does not have a contextual constructor (g.l.Binding), then we won't either. // We have to do things this way (and rely on just default constructors) because the logic that generates // the constructors for our script class have already run. if (cNode.getSuperClass().getDeclaredConstructor(CONTEXT_CTOR_PARAMETERS) == null) { ConstructorNode orphanedConstructor = cNode.getDeclaredConstructor(CONTEXT_CTOR_PARAMETERS); cNode.removeConstructor(orphanedConstructor); } }
Example 20
Source File: StaticPropertyAccessHelper.java From groovy with Apache License 2.0 | 4 votes |
public PoppingMethodCallExpression(final Expression receiver, final MethodNode setterMethod, final TemporaryVariableExpression tmp) { super(receiver, setterMethod.getName(), tmp); setMethodTarget(setterMethod); this.tmp = tmp; }