Java Code Examples for org.codehaus.groovy.ast.expr.VariableExpression#getType()

The following examples show how to use org.codehaus.groovy.ast.expr.VariableExpression#getType() . 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: 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 2
Source File: StatementMetaTypeChooser.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public ClassNode resolveType(final Expression exp, final ClassNode current) {
    ClassNode type = null;
    if (exp instanceof ClassExpression) { type = exp.getType();
        ClassNode classType = ClassHelper.makeWithoutCaching("java.lang.Class");
        classType.setGenericsTypes(new GenericsType[] {new GenericsType(type)});
        classType.setRedirect(ClassHelper.CLASS_Type);
        return classType;
    }

    OptimizingStatementWriter.StatementMeta meta = exp.getNodeMetaData(OptimizingStatementWriter.StatementMeta.class);
    if (meta != null) type = meta.type;
    if (type != null) return type;

    if (exp instanceof VariableExpression) {
        VariableExpression ve = (VariableExpression) exp;
        if (ve.isClosureSharedVariable()) return ve.getType();
        if (ve.isSuperExpression()) return current.getSuperClass();

        type = ve.getOriginType();
    } else if (exp instanceof Variable) {
        Variable v = (Variable) exp;
        type = v.getOriginType();
    } else {
        type = exp.getType();
    }
    return type.redirect();
}
 
Example 3
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getConstructorArgumentType(Expression arg, ConstructorNode node) {
    if (!(arg instanceof VariableExpression)) return arg.getType();
    VariableExpression vexp = (VariableExpression) arg;
    String name = vexp.getName();
    for (Parameter param : node.getParameters()) {
        if (param.getName().equals(name)) {
            return param.getType();
        }
    }
    return vexp.getType();
}
 
Example 4
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void visitVariableExpression(VariableExpression variableExpression) {
    final ClassNode visitedType = variableExpression.getType();
    final String visitedName = variableExpression.getName();

    if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
        addOccurrences(visitedType, (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset));
    } else {
        if (leaf instanceof FieldNode) {
            if (visitedName.equals(((FieldNode) leaf).getName())) {
                occurrences.add(variableExpression);
            }
        } else if (leaf instanceof PropertyNode) {
            if (visitedName.equals(((PropertyNode) leaf).getField().getName())) {
                occurrences.add(variableExpression);
            }
        } else if (leaf instanceof Variable) {
            if (visitedName.equals(((Variable) leaf).getName())) {
                occurrences.add(variableExpression);
            }
        } else if (leaf instanceof ForStatement) {
            if (visitedName.equals(((ForStatement) leaf).getVariable().getName())) {
                occurrences.add(variableExpression);
            }
        } else if (leaf instanceof ConstantExpression && leafParent instanceof PropertyExpression) {
            PropertyExpression property = (PropertyExpression) leafParent;
            if (variableExpression.getName().equals(property.getPropertyAsString())) {
                occurrences.add(variableExpression);
            }

        // #234000
        } else if (leaf instanceof BlockStatement) {
            ASTNode root = path.root();
            if (root instanceof ModuleNode) {
                for (Map.Entry<String, ImportNode> entry : ((ModuleNode) root).getStaticImports().entrySet()) {
                    String alias = entry.getKey();

                    if (!alias.equals(variableExpression.getName())) {
                        continue;
                    }

                    OffsetRange range = ASTUtils.getNextIdentifierByName(doc, alias, cursorOffset);
                    if (range.containsInclusive(cursorOffset)) {
                        occurrences.add(variableExpression);
                    }
                }
            }
        }
    }
    super.visitVariableExpression(variableExpression);
}
 
Example 5
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 6
Source File: FieldASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    sourceUnit = source;
    if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
        throw new GroovyBugError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes));
    }

    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(node.getClassNode())) return;

    if (parent instanceof DeclarationExpression) {
        DeclarationExpression de = (DeclarationExpression) parent;
        ClassNode cNode = de.getDeclaringClass();
        if (!cNode.isScript()) {
            addError("Annotation " + MY_TYPE_NAME + " can only be used within a Script.", parent);
            return;
        }
        candidate = de;
        // GROOVY-4548: temp fix to stop CCE until proper support is added
        if (de.isMultipleAssignmentDeclaration()) {
            addError("Annotation " + MY_TYPE_NAME + " not supported with multiple assignment notation.", parent);
            return;
        }
        VariableExpression ve = de.getVariableExpression();
        variableName = ve.getName();
        // set owner null here, it will be updated by addField
        fieldNode = new FieldNode(variableName, ve.getModifiers(), ve.getType(), null, de.getRightExpression());
        fieldNode.setSourcePosition(de);
        cNode.addField(fieldNode);
        // provide setter for CLI Builder purposes unless final
        if (fieldNode.isFinal()) {
            if (!de.getAnnotations(OPTION_TYPE).isEmpty()) {
                addError("Can't have a final field also annotated with @" + OPTION_TYPE.getNameWithoutPackage(), de);
            }
        } else {
            String setterName = getSetterName(variableName);
            cNode.addMethod(setterName, ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, params(param(ve.getType(), variableName)), ClassNode.EMPTY_ARRAY, block(
                    stmt(assignX(propX(varX("this"), variableName), varX(variableName)))
            ));
        }

        // GROOVY-4833 : annotations that are not Groovy transforms should be transferred to the generated field
        // GROOVY-6112 : also copy acceptable Groovy transforms
        final List<AnnotationNode> annotations = de.getAnnotations();
        for (AnnotationNode annotation : annotations) {
            // GROOVY-6337 HACK: in case newly created field is @Lazy
            if (annotation.getClassNode().equals(LAZY_TYPE)) {
                LazyASTTransformation.visitField(this, annotation, fieldNode);
            }
            final ClassNode annotationClassNode = annotation.getClassNode();
            if (notTransform(annotationClassNode) || acceptableTransform(annotation)) {
                fieldNode.addAnnotation(annotation);
            }
        }

        super.visitClass(cNode);
        // GROOVY-5207 So that Closures can see newly added fields
        // (not super efficient for a very large class with many @Fields but we chose simplicity
        // and understandability of this solution over more complex but efficient alternatives)
        VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source);
        scopeVisitor.visitClass(cNode);
    }
}