Java Code Examples for org.codehaus.groovy.ast.ClassNode#getField()

The following examples show how to use org.codehaus.groovy.ast.ClassNode#getField() . 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: GroovyASTUtils.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public static FieldNode getFieldFromExpression(PropertyExpression node, ASTNodeVisitor astVisitor) {
    ClassNode classNode = getTypeOfNode(node.getObjectExpression(), astVisitor);
    if (classNode != null) {
        return classNode.getField(node.getProperty().getText());
    }
    return null;
}
 
Example 2
Source File: DetectorTransform.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}
 
Example 3
Source File: DetectorTransform.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}
 
Example 4
Source File: UnionTypeClassNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public FieldNode getField(final String name) {
    for (ClassNode delegate : delegates) {
        FieldNode field = delegate.getField(name);
        if (field != null) return field;
    }
    return null;
}
 
Example 5
Source File: ImmutableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addProperty(ClassNode cNode, PropertyNode pNode) {
    final FieldNode fn = pNode.getField();
    cNode.getFields().remove(fn);
    cNode.addProperty(pNode.getName(), pNode.getModifiers() | ACC_FINAL, pNode.getType(),
            pNode.getInitialExpression(), pNode.getGetterBlock(), pNode.getSetterBlock());
    final FieldNode newfn = cNode.getField(fn.getName());
    cNode.getFields().remove(newfn);
    cNode.addField(fn);
}
 
Example 6
Source File: MemoizedASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static String buildUniqueName(ClassNode owner, String ident, MethodNode methodNode) {
    StringBuilder nameBuilder = new StringBuilder("memoizedMethod" + ident + "$").append(methodNode.getName());
    if (methodNode.getParameters() != null) {
        for (Parameter parameter : methodNode.getParameters()) {
            nameBuilder.append(buildTypeName(parameter.getType()));
        }
    }
    while (owner.getField(nameBuilder.toString()) != null) {
        nameBuilder.insert(0, "_");
    }

    return nameBuilder.toString();
}
 
Example 7
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean checkStaticOuterField(final PropertyExpression pexp, final String propertyName) {
    for (final ClassNode outer : controller.getClassNode().getOuterClasses()) {
        FieldNode field = outer.getDeclaredField(propertyName);
        if (field != null) {
            if (!field.isStatic()) break;

            Expression outerClass = classX(outer);
            outerClass.setNodeMetaData(PROPERTY_OWNER, outer);
            outerClass.setSourcePosition(pexp.getObjectExpression());

            Expression outerField = attrX(outerClass, pexp.getProperty());
            outerField.setSourcePosition(pexp);
            outerField.visit(this);
            return true;
        } else {
            field = outer.getField(propertyName); // checks supers
            if (field != null && !field.isPrivate() && (field.isPublic() || field.isProtected()
                    || Objects.equals(field.getDeclaringClass().getPackageName(), outer.getPackageName()))) {
                if (!field.isStatic()) break;

                Expression upperClass = classX(field.getDeclaringClass());
                upperClass.setNodeMetaData(PROPERTY_OWNER, field.getDeclaringClass());
                upperClass.setSourcePosition(pexp.getObjectExpression());

                Expression upperField = propX(upperClass, pexp.getProperty());
                upperField.setSourcePosition(pexp);
                upperField.visit(this);
                return true;
            }
        }
    }
    return false;
}
 
Example 8
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean makeSetPrivateFieldWithBridgeMethod(final Expression receiver, final ClassNode receiverType, final String fieldName, final Expression arguments, final boolean safe, final boolean spreadSafe, final boolean implicitThis) {
    FieldNode field = receiverType.getField(fieldName);
    ClassNode outerClass = receiverType.getOuterClass();
    if (field == null && implicitThis && outerClass != null && !receiverType.isStaticClass()) {
        Expression pexp;
        if (controller.isInGeneratedFunction()) {
            MethodCallExpression mce = callThisX("getThisObject");
            mce.setImplicitThis(true);
            mce.setMethodTarget(CLOSURE_GETTHISOBJECT_METHOD);
            mce.putNodeMetaData(INFERRED_TYPE, controller.getOutermostClass());
            pexp = castX(controller.getOutermostClass(), mce);
        } else {
            pexp = propX(classX(outerClass), "this");
            ((PropertyExpression) pexp).setImplicitThis(true);
        }
        pexp.putNodeMetaData(INFERRED_TYPE, outerClass);
        pexp.setSourcePosition(receiver);
        return makeSetPrivateFieldWithBridgeMethod(pexp, outerClass, fieldName, arguments, safe, spreadSafe, true);
    }
    ClassNode classNode = controller.getClassNode();
    if (field != null && field.isPrivate() && !receiverType.equals(classNode)
            && (StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(receiverType, classNode)
                || StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(classNode,receiverType))) {
        Map<String, MethodNode> mutators = receiverType.redirect().getNodeMetaData(StaticCompilationMetadataKeys.PRIVATE_FIELDS_MUTATORS);
        if (mutators != null) {
            MethodNode methodNode = mutators.get(fieldName);
            if (methodNode != null) {
                MethodCallExpression call = callX(receiver, methodNode.getName(), args(field.isStatic() ? nullX() : receiver, arguments));
                call.setImplicitThis(implicitThis);
                call.setMethodTarget(methodNode);
                call.setSafe(safe);
                call.setSpreadSafe(spreadSafe);
                call.visit(controller.getAcg());
                return true;
            }
        }
    }
    return false;
}
 
Example 9
Source File: DetectorTransform.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}
 
Example 10
Source File: DetectorTransform.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}
 
Example 11
Source File: DriverCompilationCustomizer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
   LOGGER.trace("Customize [phase: {} {}, classNode: {}]", source.getPhase(), source.getPhaseDescription(), classNode);
   if(classNode.getField("_HASH") == null) {
      String hash = hash(source);
      if(hash != null) {
         classNode.addField(
               "_HASH", 
               Modifier.PUBLIC | Modifier.FINAL, 
               new ClassNode(String.class), 
               new ConstantExpression(hash)
         );
      }
   }
   
   ClassNode groovyCapabilityDefinition = new ClassNode(GroovyCapabilityDefinition.class);
   for(CapabilityDefinition definition: capabilityRegistry.listCapabilityDefinitions()) {
      if(classNode.getProperty(definition.getCapabilityName()) != null) {
         continue;
      }
      
      if(!isDeviceCapability(definition)) {
         continue;
      }
      
      String fieldName = definition.getNamespace();
      FieldNode field = classNode.addField(
            fieldName,
            Modifier.PRIVATE | Modifier.FINAL, 
            groovyCapabilityDefinition,
            new StaticMethodCallExpression(
                  new ClassNode(GroovyCapabilityDefinitionFactory.class),
                  "create",
                  new TupleExpression(
                        new ConstantExpression(definition.getCapabilityName()),
                        VariableExpression.THIS_EXPRESSION
                  )
            )
      );
      
      
      classNode.addProperty(
            definition.getCapabilityName(),
            Modifier.PUBLIC | Modifier.FINAL,
            groovyCapabilityDefinition,
            new FieldExpression(field),
            new ReturnStatement(new FieldExpression(field)),
            null
       );
   }
}
 
Example 12
Source File: GeneralUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static FieldExpression fieldX(final ClassNode owner, final String fieldName) {
    return new FieldExpression(owner.getField(fieldName));
}
 
Example 13
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void visitAttributeOrProperty(final PropertyExpression pexp, final MethodCallerMultiAdapter adapter) {
    ClassNode classNode = controller.getClassNode();
    String propertyName = pexp.getPropertyAsString();
    Expression objectExpression = pexp.getObjectExpression();

    if (objectExpression instanceof ClassExpression && "this".equals(propertyName)) {
        // we have something like A.B.this, and need to make it
        // into this.this$0.this$0, where this.this$0 returns
        // A.B and this.this$0.this$0 return A.
        ClassNode type = objectExpression.getType();
        if (controller.getCompileStack().isInSpecialConstructorCall() && type.equals(classNode.getOuterClass())) {
            // Outer.this in a special constructor call
            ConstructorNode ctor = controller.getConstructorNode();
            Expression receiver = !classNode.isStaticClass() ? new VariableExpression(ctor.getParameters()[0]) : new ClassExpression(type);
            receiver.setSourcePosition(pexp);
            receiver.visit(this);
            return;
        }

        MethodVisitor mv = controller.getMethodVisitor();
        mv.visitVarInsn(ALOAD, 0);
        ClassNode iterType = classNode;
        while (!iterType.equals(type)) {
            String ownerName = BytecodeHelper.getClassInternalName(iterType);
            if (iterType.getOuterClass() == null) break;
            FieldNode thisField = iterType.getField("this$0");
            iterType = iterType.getOuterClass();
            if (thisField == null) {
                // closure within inner class
                while (ClassHelper.isGeneratedFunction(iterType)) {
                    // GROOVY-8881: cater for closures within closures - getThisObject is already outer class of all closures
                    iterType = iterType.getOuterClass();
                }
                mv.visitMethodInsn(INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(ClassHelper.CLOSURE_TYPE), "getThisObject", "()Ljava/lang/Object;", false);
                mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(iterType));
            } else {
                ClassNode thisFieldType = thisField.getType();
                if (ClassHelper.CLOSURE_TYPE.equals(thisFieldType)) {
                    mv.visitFieldInsn(GETFIELD, ownerName, "this$0", BytecodeHelper.getTypeDescription(ClassHelper.CLOSURE_TYPE));
                    mv.visitMethodInsn(INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(ClassHelper.CLOSURE_TYPE), "getThisObject", "()Ljava/lang/Object;", false);
                    mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(iterType));
                } else {
                    String typeName = BytecodeHelper.getTypeDescription(iterType);
                    mv.visitFieldInsn(GETFIELD, ownerName, "this$0", typeName);
                }
            }
        }
        controller.getOperandStack().push(type);
        return;
    }

    if (propertyName != null) {
        // TODO: spread safe should be handled inside
        if (adapter == getProperty && !pexp.isSpreadSafe()) {
            controller.getCallSiteWriter().makeGetPropertySite(objectExpression, propertyName, pexp.isSafe(), pexp.isImplicitThis());
        } else if (adapter == getGroovyObjectProperty && !pexp.isSpreadSafe()) {
            controller.getCallSiteWriter().makeGroovyObjectGetPropertySite(objectExpression, propertyName, pexp.isSafe(), pexp.isImplicitThis());
        } else {
            controller.getCallSiteWriter().fallbackAttributeOrPropertySite(pexp, objectExpression, propertyName, adapter);
        }
    } else {
        controller.getCallSiteWriter().fallbackAttributeOrPropertySite(pexp, objectExpression, null, adapter);
    }
}
 
Example 14
Source File: StaticInvocationWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Attempts to make a direct method call on a bridge method, if it exists.
 */
protected boolean tryBridgeMethod(final MethodNode target, final Expression receiver, final boolean implicitThis, final TupleExpression args, final ClassNode thisClass) {
    ClassNode lookupClassNode;
    if (target.isProtected()) {
        lookupClassNode = controller.getClassNode();
        while (lookupClassNode != null && !lookupClassNode.isDerivedFrom(target.getDeclaringClass())) {
            lookupClassNode = lookupClassNode.getOuterClass();
        }
        if (lookupClassNode == null) {
            return false;
        }
    } else {
        lookupClassNode = target.getDeclaringClass().redirect();
    }
    Map<MethodNode, MethodNode> bridges = lookupClassNode.getNodeMetaData(StaticCompilationMetadataKeys.PRIVATE_BRIDGE_METHODS);
    MethodNode bridge = bridges == null ? null : bridges.get(target);
    if (bridge != null) {
        Expression fixedReceiver = receiver;
        if (implicitThis) {
            if (!controller.isInGeneratedFunction()) {
                fixedReceiver = propX(classX(lookupClassNode), "this");
            } else if (thisClass != null) {
                ClassNode current = thisClass.getOuterClass();
                fixedReceiver = varX("thisObject", current);
                // adjust for multiple levels of nesting if needed
                while (current.getOuterClass() != null && !lookupClassNode.equals(current)) {
                    FieldNode thisField = current.getField("this$0");
                    current = current.getOuterClass();
                    if (thisField != null) {
                        fixedReceiver = propX(fixedReceiver, "this$0");
                        fixedReceiver.setType(current);
                    }
                }
            }
        }
        ArgumentListExpression newArgs = args(target.isStatic() ? nullX() : fixedReceiver);
        for (Expression expression : args.getExpressions()) {
            newArgs.addExpression(expression);
        }
        return writeDirectMethodCall(bridge, implicitThis, fixedReceiver, newArgs);
    }
    return false;
}
 
Example 15
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
boolean makeGetField(final Expression receiver, final ClassNode receiverType, final String fieldName, final boolean safe, final boolean implicitThis) {
    FieldNode field = receiverType.getField(fieldName);

    if (field != null && isDirectAccessAllowed(field, controller.getClassNode())) {
        CompileStack compileStack = controller.getCompileStack();
        MethodVisitor mv = controller.getMethodVisitor();
        ClassNode replacementType = field.getOriginType();
        OperandStack operandStack = controller.getOperandStack();
        if (field.isStatic()) {
            mv.visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(field.getOwner()), fieldName, BytecodeHelper.getTypeDescription(replacementType));
            operandStack.push(replacementType);
        } else {
            if (implicitThis) {
                compileStack.pushImplicitThis(implicitThis);
                receiver.visit(controller.getAcg());
                compileStack.popImplicitThis();
            } else {
                receiver.visit(controller.getAcg());
            }
            Label exit = new Label();
            if (safe) {
                mv.visitInsn(DUP);
                Label doGet = new Label();
                mv.visitJumpInsn(IFNONNULL, doGet);
                mv.visitInsn(POP);
                mv.visitInsn(ACONST_NULL);
                mv.visitJumpInsn(GOTO, exit);
                mv.visitLabel(doGet);
            }
            if (!operandStack.getTopOperand().isDerivedFrom(field.getOwner())) {
                mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(field.getOwner()));
            }
            mv.visitFieldInsn(GETFIELD, BytecodeHelper.getClassInternalName(field.getOwner()), fieldName, BytecodeHelper.getTypeDescription(replacementType));
            if (safe) {
                if (ClassHelper.isPrimitiveType(replacementType)) {
                    operandStack.replace(replacementType);
                    operandStack.box();
                    replacementType = operandStack.getTopOperand();
                }
                mv.visitLabel(exit);
            }
        }
        operandStack.replace(replacementType);
        return true;
    }

    for (ClassNode face : receiverType.getInterfaces()) {
        // GROOVY-7039
        if (face != receiverType && makeGetField(receiver, face, fieldName, safe, implicitThis)) {
            return true;
        }
    }

    ClassNode superClass = receiverType.getSuperClass();
    if (superClass != null && !OBJECT_TYPE.equals(superClass)) {
        return makeGetField(receiver, superClass, fieldName, safe, implicitThis);
    }
    return false;
}