Java Code Examples for org.codehaus.groovy.ast.ClassHelper#make()

The following examples show how to use org.codehaus.groovy.ast.ClassHelper#make() . 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: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static List<AnnotationNode> makeListOfAnnotations(Object[][] data) {
    if (data.length == 0) {
        return Collections.emptyList();
    }
    List<AnnotationNode> ret = new ArrayList<>(data.length);
    for (Object[] inner : data) {
        Class<?> anno = (Class<?>) inner[0];
        AnnotationNode toAdd = new AnnotationNode(ClassHelper.make(anno));
        ret.add(toAdd);

        @SuppressWarnings("unchecked")
        Map<String,Object> member = (Map<String, Object>) inner[1];
        if (member.isEmpty()) {
            continue;
        }
        Map<String, Expression> generated = new HashMap<>(member.size());
        for (Map.Entry<String, Object> entry : member.entrySet()) {
            generated.put(entry.getKey(), makeExpression(entry.getValue()));
        }
        copyMembers(generated, toAdd);
    }
    return ret;
}
 
Example 2
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 6 votes vote down vote up
private MethodNode createBuilderMethodForField(ClassNode builder, List<FieldNode> fields, String prefix, int fieldPos) {
    String fieldName = fields.get(fieldPos).getName();
    String setterName = getSetterName(prefix, fieldName);
    GenericsType[] gtypes = new GenericsType[fields.size()];
    List<Expression> argList = new ArrayList<Expression>();
    for (int i = 0; i < fields.size(); i++) {
        gtypes[i] = i == fieldPos ? new GenericsType(ClassHelper.make(SET.class)) : makePlaceholder(i);
        argList.add(i == fieldPos ? propX(varX("this"), constX(fieldName)) : varX(fields.get(i).getName()));
    }
    ClassNode returnType = makeClassSafeWithGenerics(builder, gtypes);
    FieldNode fNode = fields.get(fieldPos);
    Map<String,ClassNode> genericsSpec = createGenericsSpec(fNode.getDeclaringClass());
    extractSuperClassGenerics(fNode.getType(), builder, genericsSpec);
    ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, fNode.getType());
    return new MethodNode(setterName, ACC_PUBLIC, returnType, params(param(correctedType, fieldName)), NO_EXCEPTIONS, block(
            stmt(assignX(propX(varX("this"), constX(fieldName)), varX(fieldName, correctedType))),
            returnS(ctorX(returnType, args(argList)))
    ));
}
 
Example 3
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private CatchStatement createCatchBlockForOuterNewTryCatchStatement(String primaryExcName) {
    // { ... }
    BlockStatement blockStatement = new BlockStatement();
    String tExcName = this.genTExcName();

    // #primaryExc = #t;
    ExpressionStatement primaryExcAssignStatement =
            new ExpressionStatement(
                    new BinaryExpression(
                            new VariableExpression(primaryExcName),
                            newSymbol(Types.ASSIGN, -1, -1),
                            new VariableExpression(tExcName)));
    astBuilder.appendStatementsToBlockStatement(blockStatement, primaryExcAssignStatement);

    // throw #t;
    ThrowStatement throwTExcStatement = new ThrowStatement(new VariableExpression(tExcName));
    astBuilder.appendStatementsToBlockStatement(blockStatement, throwTExcStatement);

    // Throwable #t
    Parameter tExcParameter = new Parameter(ClassHelper.make(Throwable.class), tExcName);

    return new CatchStatement(tExcParameter, blockStatement);
}
 
Example 4
Source File: MacroCallTransformingVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all extension methods of {@link MacroContext} for given methodName
 * with @{@link org.codehaus.groovy.macro.runtime.Macro} annotation.
 */
private List<MethodNode> findMacroMethods(String methodName, List<Expression> callArguments) {
    List<MethodNode> methods = MACRO_METHOD_CACHE.get(classLoader).get(methodName);

    if (methods == null) {
        // Not a macro call
        return Collections.emptyList();
    }

    ClassNode[] argumentsList = new ClassNode[callArguments.size()];

    for (int i = 0; i < callArguments.size(); i++) {
        argumentsList[i] = ClassHelper.make(callArguments.get(i).getClass());
    }

    return StaticTypeCheckingSupport.chooseBestMethod(MACRO_CONTEXT_CLASS_NODE, methods, argumentsList);
}
 
Example 5
Source File: ClosureSignatureHint.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a class node given a string representing the type. Performs a lookup in the compilation unit to check if it is done in the same source unit.
 * @param sourceUnit source unit
 * @param compilationUnit compilation unit
 * @param className the name of the class we want to get a {@link org.codehaus.groovy.ast.ClassNode} for
 * @return a ClassNode representing the type
 */
protected ClassNode findClassNode(final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final String className) {
    if (className.endsWith("[]")) {
        return findClassNode(sourceUnit, compilationUnit, className.substring(0, className.length() - 2)).makeArray();
    }
    ClassNode cn = compilationUnit.getClassNode(className);
    if (cn == null) {
        try {
            cn = ClassHelper.make(Class.forName(className, false, sourceUnit.getClassLoader()));
        } catch (ClassNotFoundException e) {
            cn = ClassHelper.make(className);
        }
    }
    return cn;
}
 
Example 6
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariableExpression(VariableExpression expression) {
        if (expression.isSuperExpression()) {
            guessedType = expression.getType().getSuperClass();
        }
        if (null != expression.getAccessedVariable()) {
            Variable accessedVariable = expression.getAccessedVariable();

            if (accessedVariable.hasInitialExpression()) {
                Expression initialExpression = expression.getAccessedVariable().getInitialExpression();
                if (initialExpression instanceof ConstantExpression
                        && !initialExpression.getText().equals("null")) { // NOI18N
                    guessedType = ((ConstantExpression) initialExpression).getType();
                } else if (initialExpression instanceof ConstructorCallExpression) {
                    guessedType = ClassHelper.make(((ConstructorCallExpression) initialExpression).getType().getName());
                } else if (initialExpression instanceof MethodCallExpression) {
                    int newOffset = ASTUtils.getOffset(doc, initialExpression.getLineNumber(), initialExpression.getColumnNumber());
                    AstPath newPath = new AstPath(path.root(), newOffset, doc);
                    guessedType = MethodInference.findCallerType(initialExpression, newPath, doc, newOffset);
                } else if (initialExpression instanceof ListExpression) {
                    guessedType = ((ListExpression) initialExpression).getType();
                } else if (initialExpression instanceof MapExpression) {
                    guessedType = ((MapExpression) initialExpression).getType();
                } else if (initialExpression instanceof RangeExpression) {
                    // this should work, but the type is Object - nut sure why
                    // guessedType = ((RangeExpression)initialExpression).getType();
                    guessedType = ClassHelper.makeWithoutCaching(Range.class, true);                
                }
            } else if (accessedVariable instanceof Parameter) {
                Parameter param = (Parameter) accessedVariable;
                guessedType = param.getType();
            }
        } else if (!expression.getType().getName().equals("java.lang.Object")) {
            guessedType = expression.getType();

        }
    super.visitVariableExpression(expression);
}
 
Example 7
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms generics types from an old context to a new context using the
 * given spec. This method assumes all generics types will be placeholders.
 * WARNING: The resulting generics types may or may not be placeholders
 * after the transformation.
 *
 * @param genericsSpec    the generics context information spec
 * @param oldPlaceHolders the old placeholders
 * @return the new generics types
 */
public static GenericsType[] applyGenericsContextToPlaceHolders(Map<String, ClassNode> genericsSpec, GenericsType[] oldPlaceHolders) {
    if (oldPlaceHolders == null || oldPlaceHolders.length == 0) return oldPlaceHolders;
    if (genericsSpec.isEmpty()) return oldPlaceHolders;
    GenericsType[] newTypes = new GenericsType[oldPlaceHolders.length];
    for (int i = 0; i < oldPlaceHolders.length; i++) {
        GenericsType old = oldPlaceHolders[i];
        if (!old.isPlaceholder())
            throw new GroovyBugError("Given generics type " + old + " must be a placeholder!");
        ClassNode fromSpec = genericsSpec.get(old.getName());
        if (fromSpec != null) {
            newTypes[i] = fromSpec.asGenericsType();
        } else {
            ClassNode[] upper = old.getUpperBounds();
            ClassNode[] newUpper = upper;
            if (upper != null && upper.length > 0) {
                ClassNode[] upperCorrected = new ClassNode[upper.length];
                for (ClassNode classNode : upper) {
                    upperCorrected[i] = correctToGenericsSpecRecurse(genericsSpec, classNode);
                }
                upper = upperCorrected;
            }
            ClassNode lower = old.getLowerBound();
            ClassNode newLower = correctToGenericsSpecRecurse(genericsSpec, lower);
            if (lower == newLower && upper == newUpper) {
                newTypes[i] = oldPlaceHolders[i];
            } else {
                ClassNode newPlaceHolder = ClassHelper.make(old.getName());
                GenericsType gt = new GenericsType(newPlaceHolder, newUpper, newLower);
                gt.setPlaceholder(true);
                newTypes[i] = gt;
            }
        }
    }
    return newTypes;
}
 
Example 8
Source File: AsmReferenceResolver.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ClassNode resolveNonArrayType(Type type) {
    String className = type.getClassName();
    if (type.getSort() != Type.OBJECT) {
        return ClassHelper.make(className);
    }

    return resolveClass(className);
}
 
Example 9
Source File: LogASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected ClassNode classNode(String name) {
    ClassLoader cl = loader == null ? this.getClass().getClassLoader() : loader;
    try {
        return ClassHelper.make(Class.forName(name, false, cl));
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Unable to load logging class", e);
    }
}
 
Example 10
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement createSuperFallback(MethodNode forwarderMethod, ClassNode returnType) {
    ArgumentListExpression args = new ArgumentListExpression();
    Parameter[] forwarderMethodParameters = forwarderMethod.getParameters();
    for (final Parameter forwarderMethodParameter : forwarderMethodParameters) {
        args.addExpression(new VariableExpression(forwarderMethodParameter));
    }
    BinaryExpression instanceOfExpr = new BinaryExpression(new VariableExpression("this"), Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1), new ClassExpression(Traits.GENERATED_PROXY_CLASSNODE));
    MethodCallExpression superCall = new MethodCallExpression(
            new VariableExpression("super"),
            forwarderMethod.getName(),
            args
    );
    superCall.setImplicitThis(false);
    CastExpression proxyReceiver = new CastExpression(Traits.GENERATED_PROXY_CLASSNODE, new VariableExpression("this"));
    MethodCallExpression getProxy = new MethodCallExpression(proxyReceiver, "getProxyTarget", ArgumentListExpression.EMPTY_ARGUMENTS);
    getProxy.setImplicitThis(true);
    StaticMethodCallExpression proxyCall = new StaticMethodCallExpression(
            ClassHelper.make(InvokerHelper.class),
            "invokeMethod",
            new ArgumentListExpression(getProxy, new ConstantExpression(forwarderMethod.getName()), new ArrayExpression(ClassHelper.OBJECT_TYPE, args.getExpressions()))
    );
    IfStatement stmt = new IfStatement(
            new BooleanExpression(instanceOfExpr),
            new ExpressionStatement(new CastExpression(returnType,proxyCall)),
            new ExpressionStatement(superCall)
    );
    return stmt;
}
 
Example 11
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static GenericsType[] unsetGenTypes(int numFields) {
    GenericsType[] gtypes = new GenericsType[numFields];
    for (int i = 0; i < gtypes.length; i++) {
        gtypes[i] = new GenericsType(ClassHelper.make(UNSET.class));
    }
    return gtypes;
}
 
Example 12
Source File: MethodInference.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to infer correct {@link ClassNode} representing type of the caller for
 * the given expression. Typically the given parameter is instance of {@link MethodCallExpression}
 * and in that case the return type of the method call is returned.<br/><br/>
 * 
 * The method also handles method chain and in such case the return type of the
 * last method call should be return.
 * 
 * @param expression
 * @return class type of the caller if found, {@code null} otherwise
 */
@CheckForNull
public static ClassNode findCallerType(@NonNull ASTNode expression, @NonNull AstPath path, BaseDocument baseDocument, int offset) {
    // In case if the method call is chained with another method call
    // For example: someInteger.toString().^
    if (expression instanceof MethodCallExpression) {
        MethodCallExpression methodCall = (MethodCallExpression) expression;

        ClassNode callerType = findCallerType(methodCall.getObjectExpression(), path, baseDocument, offset);
        if (callerType != null) {
            return findReturnTypeFor(callerType, methodCall.getMethodAsString(), methodCall.getArguments(), path, false, baseDocument, offset);
        }
    }

    // In case if the method call is directly on a variable
    if (expression instanceof VariableExpression) {
        int newOffset = ASTUtils.getOffset(baseDocument, expression.getLineNumber(), expression.getColumnNumber());
        AstPath newPath = new AstPath(path.root(), newOffset, baseDocument);
        TypeInferenceVisitor tiv = new TypeInferenceVisitor(((ModuleNode)path.root()).getContext(), newPath, baseDocument, newOffset);
        tiv.collect();
        return tiv.getGuessedType();

        }
    if (expression instanceof ConstantExpression) {
        return ((ConstantExpression) expression).getType();
    }
    if (expression instanceof ClassExpression) {
        return ClassHelper.make(((ClassExpression) expression).getType().getName());
    }

    if (expression instanceof StaticMethodCallExpression) {
        StaticMethodCallExpression staticMethodCall = (StaticMethodCallExpression) expression;

        return findReturnTypeFor(staticMethodCall.getOwnerType(), staticMethodCall.getMethod(), staticMethodCall.getArguments(), path, true, baseDocument, offset);
    }
    return null;
}
 
Example 13
Source File: ClassNodeResolver.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Search for classes using ASM decompiler
 */
private LookupResult findDecompiled(String name, CompilationUnit compilationUnit, GroovyClassLoader loader) {
    ClassNode node = ClassHelper.make(name);
    if (node.isResolved()) {
        return new LookupResult(null, node);
    }

    DecompiledClassNode asmClass = null;
    String fileName = name.replace('.', '/') + ".class";
    URL resource = loader.getResource(fileName);
    if (resource != null) {
        try {
            asmClass = new DecompiledClassNode(AsmDecompiler.parseClass(resource), new AsmReferenceResolver(this, compilationUnit));
            if (!asmClass.getName().equals(name)) {
                // this may happen under Windows because getResource is case insensitive under that OS!
                asmClass = null;
            }
        } catch (IOException e) {
            // fall through and attempt other search strategies
        }
    }

    if (asmClass != null) {
        if (isFromAnotherClassLoader(loader, fileName)) {
            return tryAsScript(name, compilationUnit, asmClass);
        }

        return new LookupResult(null, asmClass);
    }
    return null;
}
 
Example 14
Source File: Java8.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void setAnnotationMetaData(Annotation[] annotations, AnnotatedNode an) {
    for (Annotation annotation : annotations) {
        AnnotationNode node = new AnnotationNode(ClassHelper.make(annotation.annotationType()));
        configureAnnotation(node, annotation);
        an.addAnnotation(node);
    }
}
 
Example 15
Source File: VetoableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a setter method with the given body.
 * <p>
 * This differs from normal setters in that we need to add a declared
 * exception java.beans.PropertyVetoException
 *
 * @param declaringClass the class to which we will add the setter
 * @param propertyNode          the field to back the setter
 * @param setterName     the name of the setter
 * @param setterBlock    the statement representing the setter block
 */
protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {
    ClassNode[] exceptions = {ClassHelper.make(PropertyVetoException.class)};
    MethodNode setter = new MethodNode(
            setterName,
            PropertyNodeUtils.adjustPropertyModifiersForMethod(propertyNode),
            ClassHelper.VOID_TYPE,
            params(param(propertyNode.getType(), "value")),
            exceptions,
            setterBlock);
    setter.setSynthetic(true);
    // add it to the class
    addGeneratedMethod(declaringClass, setter);
}
 
Example 16
Source File: Java8.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ClassNode makeClassNode(CompileUnit cu, Type t, Class<?> c) {
    ClassNode back = null;
    if (cu != null) back = cu.getClass(c.getName());
    if (back == null) back = ClassHelper.make(c);
    if (!(t instanceof Class)) {
        ClassNode front = configureType(t);
        front.setRedirect(back);
        return front;
    }
    return back.getPlainNodeReference();
}
 
Example 17
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static GenericsType[] setGenTypes(int numFields) {
    GenericsType[] gtypes = new GenericsType[numFields];
    for (int i = 0; i < gtypes.length; i++) {
        gtypes[i] = new GenericsType(ClassHelper.make(SET.class));
    }
    return gtypes;
}
 
Example 18
Source File: TypeCheckingExtension.java    From groovy with Apache License 2.0 4 votes vote down vote up
public ClassNode classNodeFor(String type) {
    return ClassHelper.make(type);
}
 
Example 19
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected Expression transformVariableExpression(final VariableExpression ve) {
    visitAnnotations(ve);
    Variable v = ve.getAccessedVariable();

    if(!(v instanceof DynamicVariable) && !checkingVariableTypeInDeclaration) {
        /*
         *  GROOVY-4009: when a normal variable is simply being used, there is no need to try to
         *  resolve its type. Variable type resolve should proceed only if the variable is being declared.
         */
        return ve;
    }
    if (v instanceof DynamicVariable) {
        String name = ve.getName();
        ClassNode t = ClassHelper.make(name);
        // asking isResolved here allows to check if a primitive
        // type name like "int" was used to make t. In such a case
        // we have nothing left to do.
        boolean isClass = t.isResolved();
        if (!isClass) {
            // It was no primitive type, so next we see if the name,
            // which is a vanilla name, starts with a lower case letter.
            // In that case we change it to a LowerCaseClass to let the
            // compiler skip the resolving at several places in this class.
            if (Character.isLowerCase(name.charAt(0))) {
                t = new LowerCaseClass(name);
            }
            isClass = resolve(t);
        }
        if (isClass) {
            // the name is a type so remove it from the scoping
            // as it is only a classvariable, it is only in
            // referencedClassVariables, but must be removed
            // for each parentscope too
            for (VariableScope scope = currentScope; scope != null && !scope.isRoot(); scope = scope.getParent()) {
                if (scope.removeReferencedClassVariable(ve.getName()) == null) break;
            }
            return new ClassExpression(t);
        }
    }
    resolveOrFail(ve.getType(), ve);
    ClassNode origin = ve.getOriginType();
    if (origin != ve.getType()) resolveOrFail(origin, ve);
    return ve;
}
 
Example 20
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
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);
    }
}