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

The following examples show how to use org.codehaus.groovy.ast.expr.VariableExpression#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: GroovydocVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitDeclarationExpression(DeclarationExpression expression) {
    if (currentClassDoc.isScript()) {
        if (hasAnno(expression, "Field")) {
            VariableExpression varx = expression.getVariableExpression();
            SimpleGroovyFieldDoc field = new SimpleGroovyFieldDoc(varx.getName(), currentClassDoc);
            field.setType(new SimpleGroovyType(makeType(varx.getType())));
            int mods = varx.getModifiers();
            processModifiers(field, varx, mods);
            boolean isProp = (mods & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED)) == 0;
            if (isProp) {
                currentClassDoc.addProperty(field);
            } else {
                currentClassDoc.add(field);
            }
        }
    }
    super.visitDeclarationExpression(expression);
}
 
Example 2
Source File: GroovyGradleParser.java    From size-analyzer with Apache License 2.0 5 votes vote down vote up
/**
 * This returns a String representation of the object if it is a valid expression for a parent
 * object. Otherwise, it will return null. For instance in `defaultConfig.minSdkVersion 14`,
 * defaultConfig would be a valid parent expression.
 */
private String getValidParentString(Expression objectExpression) {
  if (objectExpression instanceof PropertyExpression) {
    return ((PropertyExpression) objectExpression).getPropertyAsString();
  } else if (objectExpression instanceof VariableExpression) {
    VariableExpression variableExpression = (VariableExpression) objectExpression;
    if (!variableExpression.getName().equals("this")) {
      return variableExpression.getName();
    }
  }
  return null;
}
 
Example 3
Source File: ClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    Variable v = expression.getAccessedVariable();
    if (v == null) return;
    if (!(v instanceof FieldNode)) return;
    String name = expression.getName();
    FieldNode fn = icn.getDeclaredField(name);
    if (fn != null) { // only overwrite if we find something more specific
        expression.setAccessedVariable(fn);
    }
}
 
Example 4
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 5
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 6
Source File: MarkupBuilderCodeTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public Expression transform(final Expression exp) {
    if (exp instanceof BinaryExpression) {
        return transformBinaryExpression((BinaryExpression) exp);
    }
    if (exp instanceof MethodCallExpression) {
        return transformMethodCall((MethodCallExpression) exp);
    }
    if (exp instanceof ClosureExpression) {
        ClosureExpression cl = (ClosureExpression) exp;
        cl.getCode().visit(this);
        return cl;
    }
    if (exp instanceof VariableExpression) {
        VariableExpression var = (VariableExpression) exp;
        if (var.getAccessedVariable() instanceof DynamicVariable) {
            MethodCallExpression callGetModel = new MethodCallExpression(
                    new VariableExpression("this"),
                    "getModel",
                    ArgumentListExpression.EMPTY_ARGUMENTS
            );
            callGetModel.setImplicitThis(true);
            callGetModel.setSourcePosition(exp);
            String varName = var.getName();
            if ("model".equals(varName) || "unescaped".equals(varName)) {
                return callGetModel;
            }
            MethodCallExpression mce = new MethodCallExpression(
                    callGetModel,
                    "get",
                    new ArgumentListExpression(new ConstantExpression(varName))
            );
            mce.setSourcePosition(exp);
            mce.setImplicitThis(false);
            MethodCallExpression yield = new MethodCallExpression(
                    new VariableExpression("this"),
                    "tryEscape",
                    new ArgumentListExpression(mce)
            );
            yield.setImplicitThis(true);
            yield.setSourcePosition(exp);
            yield.putNodeMetaData(TARGET_VARIABLE, varName);
            return autoEscape?yield:mce;
        }
    }
    return super.transform(exp);
}
 
Example 7
Source File: SqlWhereVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitVariableExpression(VariableExpression expression) {
    throw new GroovyRuntimeException("DataSet currently doesn't support arbitrary variables, only literals: found attempted reference to variable '" + expression.getName() + "'");
}
 
Example 8
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 9
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);
    }
}
 
Example 10
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    final String variableName = expression.getName();

    if (expression.isThisExpression()) {
        // "this" in static context is Class instance
        if (controller.isStaticMethod() || controller.getCompileStack().isInSpecialConstructorCall()
                || (!controller.getCompileStack().isImplicitThis() && controller.isStaticContext())) {
            ClassNode thisType = controller.getClassNode();
            if (controller.isInGeneratedFunction()) {
                do { thisType = thisType.getOuterClass();
                } while (ClassHelper.isGeneratedFunction(thisType));
            }
            classX(thisType).visit(this);
        } else {
            loadThis(expression);
        }
        return;
    }

    if (expression.isSuperExpression()) {
        // "super" in static context is Class instance
        if (controller.isStaticMethod()) {
            ClassNode superType = controller.getClassNode().getSuperClass();
            classX(superType).visit(this);
        } else {
            loadThis(expression);
        }
        return;
    }

    BytecodeVariable variable = controller.getCompileStack().getVariable(variableName, false);
    if (variable != null) {
        controller.getOperandStack().loadOrStoreVariable(variable, expression.isUseReferenceDirectly());
    } else if (passingParams && controller.isInScriptBody()) {
        MethodVisitor mv = controller.getMethodVisitor();
        mv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/ScriptReference");
        mv.visitInsn(DUP);
        loadThisOrOwner();
        mv.visitLdcInsn(variableName);
        mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/runtime/ScriptReference", "<init>", "(Lgroovy/lang/Script;Ljava/lang/String;)V", false);
    } else {
        PropertyExpression pexp = thisPropX(true, variableName);
        pexp.getObjectExpression().setSourcePosition(expression);
        pexp.getProperty().setSourcePosition(expression);
        pexp.visit(this);
    }

    if (!controller.getCompileStack().isLHS()) {
        controller.getAssertionWriter().record(expression);
    }
}