public void visitConstructorCallExpression(ConstructorCallExpression call) {
    isSpecialConstructorCall = call.isSpecialCall();
    super.visitConstructorCallExpression(call);
    isSpecialConstructorCall = false;
    if (!call.isUsingAnonymousInnerClass()) return;

    pushState();
    InnerClassNode innerClass = (InnerClassNode) call.getType();
    innerClass.setVariableScope(currentScope);
    for (MethodNode method : innerClass.getMethods()) {
      Parameter[] parameters = method.getParameters();
      if (parameters.length == 0) parameters = null; // null means no implicit "it"
      ClosureExpression cl = new ClosureExpression(parameters, method.getCode());
      visitClosureExpression(cl);
    }

    for (FieldNode field : innerClass.getFields()) {
      final Expression expression = field.getInitialExpression();
      if (expression != null) {
        expression.visit(this);
      }
    }

    for (Statement statement : innerClass.getObjectInitializerStatements()) {
      statement.visit(this);
    }
    markClosureSharedVariables();
    popState();
  }
Exemplo n.º 2
0
  /**
   * Main entry point for the calling the TestForTransformation programmatically.
   *
   * @param classNode The class node that represents th test
   * @param ce The class expression that represents the class to test
   */
  public void testFor(ClassNode classNode, ClassExpression ce) {
    boolean junit3Test = isJunit3Test(classNode);

    // make sure the 'log' property is not the one from GroovyTestCase
    FieldNode log = classNode.getField("log");
    if (log == null || log.getDeclaringClass().equals(GROOVY_TEST_CASE_CLASS)) {
      LoggingTransformer.addLogField(classNode, classNode.getName());
    }
    boolean isSpockTest = isSpockTest(classNode);

    if (!isSpockTest && !junit3Test) {
      // assume JUnit 4
      Map<String, MethodNode> declaredMethodsMap = classNode.getDeclaredMethodsMap();
      for (String methodName : declaredMethodsMap.keySet()) {
        MethodNode methodNode = declaredMethodsMap.get(methodName);
        if (isCandidateMethod(methodNode) && methodNode.getName().startsWith("test")) {
          if (methodNode.getAnnotations().size() == 0) {
            methodNode.addAnnotation(TEST_ANNOTATION);
          }
        }
      }
    }

    final MethodNode methodToAdd = weaveMock(classNode, ce, true);
    if (methodToAdd != null && junit3Test) {
      addMethodCallsToMethod(classNode, SET_UP_METHOD, Arrays.asList(methodToAdd));
    }
  }
 private Statement createConstructorStatementMapSpecial(FieldNode fNode) {
   final Expression fieldExpr = new VariableExpression(fNode);
   Expression initExpr = fNode.getInitialValueExpression();
   if (initExpr == null) initExpr = new ConstantExpression(null);
   Expression namedArgs = findArg(fNode.getName());
   Expression baseArgs = new VariableExpression("args");
   return new IfStatement(
       equalsNullExpr(baseArgs),
       new IfStatement(
           equalsNullExpr(initExpr),
           new EmptyStatement(),
           assignStatement(fieldExpr, cloneCollectionExpr(initExpr))),
       new IfStatement(
           equalsNullExpr(namedArgs),
           new IfStatement(
               isTrueExpr(
                   new MethodCallExpression(
                       baseArgs, "containsKey", new ConstantExpression(fNode.getName()))),
               assignStatement(fieldExpr, namedArgs),
               assignStatement(fieldExpr, cloneCollectionExpr(baseArgs))),
           new IfStatement(
               isOneExpr(
                   new MethodCallExpression(baseArgs, "size", MethodCallExpression.NO_ARGUMENTS)),
               assignStatement(fieldExpr, cloneCollectionExpr(namedArgs)),
               assignStatement(fieldExpr, cloneCollectionExpr(baseArgs)))));
 }
 private Statement createConstructorStatement(
     ClassNode cNode,
     PropertyNode pNode,
     List<String> knownImmutableClasses,
     List<String> knownImmutables) {
   FieldNode fNode = pNode.getField();
   final ClassNode fieldType = fNode.getType();
   Statement statement = null;
   if (fieldType.isArray() || isOrImplements(fieldType, CLONEABLE_TYPE)) {
     statement = createConstructorStatementArrayOrCloneable(fNode);
   } else if (isKnownImmutableClass(fieldType, knownImmutableClasses)
       || isKnownImmutable(pNode.getName(), knownImmutables)) {
     statement = createConstructorStatementDefault(fNode);
   } else if (fieldType.isDerivedFrom(DATE_TYPE)) {
     statement = createConstructorStatementDate(fNode);
   } else if (isOrImplements(fieldType, COLLECTION_TYPE)
       || fieldType.isDerivedFrom(COLLECTION_TYPE)
       || isOrImplements(fieldType, MAP_TYPE)
       || fieldType.isDerivedFrom(MAP_TYPE)) {
     statement = createConstructorStatementCollection(fNode);
   } else if (fieldType.isResolved()) {
     addError(
         createErrorMessage(cNode.getName(), fNode.getName(), fieldType.getName(), "compiling"),
         fNode);
     statement = EmptyStatement.INSTANCE;
   } else {
     statement = createConstructorStatementGuarded(cNode, fNode);
   }
   return statement;
 }
 public void visitField(FieldNode node) {
   if (currentClass.getDeclaredField(node.getName()) != node) {
     addError("The " + getDescription(node) + " is declared multiple times.", node);
   }
   checkInterfaceFieldModifiers(node);
   checkGenericsUsage(node, node.getType());
   super.visitField(node);
 }
 private Expression findStaticField(ClassNode staticImportType, String fieldName) {
   if (staticImportType.isPrimaryClassNode() || staticImportType.isResolved()) {
     FieldNode field = staticImportType.getField(fieldName);
     if (field != null && field.isStatic())
       return new PropertyExpression(new ClassExpression(staticImportType), fieldName);
   }
   return null;
 }
  private List<FieldNode> getAnnotatedFieldOfClass(ClassNode target, ClassNode annotation) {
    List<FieldNode> result = new ArrayList<FieldNode>();

    for (FieldNode fieldNode : target.getFields())
      if (!fieldNode.getAnnotations(annotation).isEmpty()) result.add(fieldNode);

    return result;
  }
 private Expression findConstant(FieldNode fn) {
   if (fn != null && !fn.isEnum() && fn.isStatic() && fn.isFinal()) {
     if (fn.getInitialValueExpression() instanceof ConstantExpression) {
       return fn.getInitialValueExpression();
     }
   }
   return null;
 }
Exemplo n.º 9
0
 public void addFieldFirst(FieldNode node) {
   final ClassNode r = redirect();
   node.setDeclaringClass(r);
   node.setOwner(r);
   if (r.fields == null) r.fields = new LinkedList<FieldNode>();
   if (r.fieldIndex == null) r.fieldIndex = new HashMap<String, FieldNode>();
   r.fields.addFirst(node);
   r.fieldIndex.put(node.getName(), node);
 }
Exemplo n.º 10
0
  private void createMethodsForSingleField(FieldNode fieldNode) {
    if (shouldFieldBeIgnored(fieldNode)) return;

    if (hasAnnotation(fieldNode.getType(), DSL_CONFIG_ANNOTATION)) {
      createSingleDSLObjectClosureMethod(fieldNode);
      createSingleFieldSetterMethod(fieldNode);
    } else if (ASTHelper.isMap(fieldNode.getType())) createMapMethod(fieldNode);
    else if (ASTHelper.isList(fieldNode.getType())) createListMethod(fieldNode);
    else createSingleFieldSetterMethod(fieldNode);
  }
Exemplo n.º 11
0
 @SuppressWarnings("RedundantIfStatement")
 boolean shouldFieldBeIgnored(FieldNode fieldNode) {
   if (fieldNode == keyField) return true;
   if (fieldNode == ownerField) return true;
   if (getAnnotation(fieldNode, IGNORE_ANNOTATION) != null) return true;
   if (fieldNode.isFinal()) return true;
   if (fieldNode.getName().startsWith("$")) return true;
   if ((fieldNode.getModifiers() & ACC_TRANSIENT) != 0) return true;
   return false;
 }
  public void visitField(FieldNode fieldNode) {

    cv.visitField(
        fieldNode.getModifiers(),
        fieldNode.getName(),
        BytecodeHelper.getTypeDescription(fieldNode.getType()),
        null, // fieldValue,  //br  all the sudden that one cannot init the field here. init is done
        // in static initializer and instance initializer.
        null);
  }
Exemplo n.º 13
0
  private void preventOwnerOverride() {

    MethodBuilder.createPublicMethod(setterName(ownerField))
        .param(OBJECT_TYPE, "value")
        .statement(
            ifS(
                andX(
                    isInstanceOfX(varX("value"), ownerField.getType()),
                    notX(propX(varX("this"), ownerField.getName()))),
                assignX(propX(varX("this"), ownerField.getName()), varX("value"))))
        .addTo(annotatedClass);
  }
Exemplo n.º 14
0
 private void printEnumFields(PrintWriter out, List<FieldNode> fields) {
   if (fields.size() == 0) return;
   boolean first = true;
   for (FieldNode field : fields) {
     if (!first) {
       out.print(", ");
     } else {
       first = false;
     }
     out.print(field.getName());
   }
   out.println(";");
 }
 private Statement createConstructorStatementGuarded(ClassNode cNode, FieldNode fNode) {
   final Expression fieldExpr = new VariableExpression(fNode);
   Expression initExpr = fNode.getInitialValueExpression();
   if (initExpr == null) initExpr = new ConstantExpression(null);
   Expression unknown = findArg(fNode.getName());
   return new IfStatement(
       equalsNullExpr(unknown),
       new IfStatement(
           equalsNullExpr(initExpr),
           new EmptyStatement(),
           assignStatement(fieldExpr, checkUnresolved(cNode, fNode, initExpr))),
       assignStatement(fieldExpr, checkUnresolved(cNode, fNode, unknown)));
 }
Exemplo n.º 16
0
 private void checkInterfaceFieldModifiers(FieldNode node) {
   if (!currentClass.isInterface()) return;
   if ((node.getModifiers() & (ACC_PUBLIC | ACC_STATIC | ACC_FINAL)) == 0
       || (node.getModifiers() & (ACC_PRIVATE | ACC_PROTECTED)) != 0) {
     addError(
         "The "
             + getDescription(node)
             + " is not 'public static final' but is defined in "
             + getDescription(currentClass)
             + ".",
         node);
   }
 }
 private Statement createConstructorStatementDate(FieldNode fNode) {
   final Expression fieldExpr = new VariableExpression(fNode);
   Expression initExpr = fNode.getInitialValueExpression();
   if (initExpr == null) initExpr = new ConstantExpression(null);
   final Expression date = findArg(fNode.getName());
   return new IfStatement(
       equalsNullExpr(date),
       new IfStatement(
           equalsNullExpr(initExpr),
           assignStatement(fieldExpr, new ConstantExpression(null)),
           assignStatement(fieldExpr, cloneDateExpr(initExpr))),
       assignStatement(fieldExpr, cloneDateExpr(date)));
 }
 private 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);
 }
 private Statement createConstructorStatementArrayOrCloneable(FieldNode fNode) {
   final Expression fieldExpr = new VariableExpression(fNode);
   Expression initExpr = fNode.getInitialValueExpression();
   ClassNode fieldType = fNode.getType();
   if (initExpr == null) initExpr = new ConstantExpression(null);
   final Expression array = findArg(fNode.getName());
   return new IfStatement(
       equalsNullExpr(array),
       new IfStatement(
           equalsNullExpr(initExpr),
           assignStatement(fieldExpr, new ConstantExpression(null)),
           assignStatement(fieldExpr, cloneArrayOrCloneableExpr(initExpr, fieldType))),
       assignStatement(fieldExpr, cloneArrayOrCloneableExpr(array, fieldType)));
 }
 private void visitDeprecation(AnnotatedNode node, AnnotationNode visited) {
   if (visited.getClassNode().isResolved()
       && visited.getClassNode().getName().equals("java.lang.Deprecated")) {
     if (node instanceof MethodNode) {
       MethodNode mn = (MethodNode) node;
       mn.setModifiers(mn.getModifiers() | Opcodes.ACC_DEPRECATED);
     } else if (node instanceof FieldNode) {
       FieldNode fn = (FieldNode) node;
       fn.setModifiers(fn.getModifiers() | Opcodes.ACC_DEPRECATED);
     } else if (node instanceof ClassNode) {
       ClassNode cn = (ClassNode) node;
       cn.setModifiers(cn.getModifiers() | Opcodes.ACC_DEPRECATED);
     }
   }
 }
 private void visitFieldNode(FieldNode fNode) {
   final ClassNode cNode = fNode.getDeclaringClass();
   final List<PropertyNode> pList = cNode.getProperties();
   PropertyNode foundProp = null;
   for (PropertyNode pNode : pList) {
     if (pNode.getName().equals(fNode.getName())) {
       foundProp = pNode;
       break;
     }
   }
   if (foundProp != null) {
     revertVisibility(fNode);
     pList.remove(foundProp);
   }
 }
 private void ensureNotPublic(String cNode, FieldNode fNode) {
   String fName = fNode.getName();
   // TODO: do we need to lock down things like: $ownClass
   if (fNode.isPublic() && !fName.contains("$") && !(fNode.isStatic() && fNode.isFinal())) {
     addError(
         "Public field '"
             + fName
             + "' not allowed for "
             + MY_TYPE_NAME
             + " class '"
             + cNode
             + "'.",
         fNode);
   }
 }
Exemplo n.º 23
0
 private String getRefDescriptor(ASTNode ref) {
   if (ref instanceof FieldNode) {
     FieldNode f = (FieldNode) ref;
     return "the field " + f.getName() + " ";
   } else if (ref instanceof PropertyNode) {
     PropertyNode p = (PropertyNode) ref;
     return "the property " + p.getName() + " ";
   } else if (ref instanceof ConstructorNode) {
     return "the constructor " + ref.getText() + " ";
   } else if (ref instanceof MethodNode) {
     return "the method " + ref.getText() + " ";
   } else if (ref instanceof ClassNode) {
     return "the super class " + ref + " ";
   }
   return "<unknown with class " + ref.getClass() + "> ";
 }
Exemplo n.º 24
0
 /**
  * Checks that this class node is compatible with the given ASM API version. This methods checks
  * that this node, and all its nodes recursively, do not contain elements that were introduced in
  * more recent versions of the ASM API than the given version.
  *
  * @param api an ASM API version. Must be one of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
  */
 public void check(final int api) {
   if (api == Opcodes.ASM4) {
     if (visibleTypeAnnotations != null && visibleTypeAnnotations.size() > 0) {
       throw new RuntimeException();
     }
     if (invisibleTypeAnnotations != null && invisibleTypeAnnotations.size() > 0) {
       throw new RuntimeException();
     }
     for (FieldNode f : fields) {
       f.check(api);
     }
     for (MethodNode m : methods) {
       m.check(api);
     }
   }
 }
Exemplo n.º 25
0
  private void createMapOfSimpleElementsMethods(
      FieldNode fieldNode, ClassNode keyType, ClassNode valueType) {
    String methodName = fieldNode.getName();

    MethodBuilder.createPublicMethod(methodName)
        .param(fieldNode.getType(), "values")
        .callMethod(propX(varX("this"), fieldNode.getName()), "putAll", varX("values"))
        .addTo(annotatedClass);

    String singleElementMethod = getElementNameForCollectionField(fieldNode);

    MethodBuilder.createPublicMethod(singleElementMethod)
        .param(keyType, "key")
        .param(valueType, "value")
        .callMethod(propX(varX("this"), fieldNode.getName()), "put", args("key", "value"))
        .addTo(annotatedClass);
  }
  private static boolean isDirectAccessAllowed(
      FieldNode a, ClassNode receiver, boolean isSamePackage) {
    ClassNode declaringClass = a.getDeclaringClass().redirect();
    ClassNode receiverType = receiver.redirect();

    // first, direct access from within the class or inner class nodes
    if (declaringClass.equals(receiverType)) return true;
    if (receiverType instanceof InnerClassNode) {
      while (receiverType != null && receiverType instanceof InnerClassNode) {
        if (declaringClass.equals(receiverType)) return true;
        receiverType = receiverType.getOuterClass();
      }
    }

    // no getter
    return a.isPublic() || (a.isProtected() && isSamePackage);
  }
Exemplo n.º 27
0
  @SuppressWarnings("ConstantConditions")
  private GenericsType[] getGenericsTypes(FieldNode fieldNode) {
    GenericsType[] types = fieldNode.getType().getGenericsTypes();

    if (types == null)
      addCompileError("Lists and Maps need to be assigned an explicit Generic Type", fieldNode);
    return types;
  }
 private void visitClassNode(ClassNode cNode, List<PackageScopeTarget> value) {
   String cName = cNode.getName();
   if (cNode.isInterface() && value.size() != 1 && value.get(0) != PackageScopeTarget.CLASS) {
     throw new RuntimeException(
         "Error processing interface '"
             + cName
             + "'. "
             + MY_TYPE_NAME
             + " not allowed for interfaces except when targeting Class level.");
   }
   if (value.contains(groovy.transform.PackageScopeTarget.CLASS)) {
     if (cNode.isSyntheticPublic()) revertVisibility(cNode);
     else
       throw new RuntimeException(
           "Can't use "
               + MY_TYPE_NAME
               + " for class '"
               + cNode.getName()
               + "' which has explicit visibility.");
   }
   if (value.contains(groovy.transform.PackageScopeTarget.METHODS)) {
     final List<MethodNode> mList = cNode.getMethods();
     for (MethodNode mNode : mList) {
       if (mNode.isSyntheticPublic()) revertVisibility(mNode);
     }
   }
   if (value.contains(PackageScopeTarget.FIELDS)) {
     final List<PropertyNode> pList = cNode.getProperties();
     List<PropertyNode> foundProps = new ArrayList<PropertyNode>();
     List<String> foundNames = new ArrayList<String>();
     for (PropertyNode pNode : pList) {
       foundProps.add(pNode);
       foundNames.add(pNode.getName());
     }
     for (PropertyNode pNode : foundProps) {
       pList.remove(pNode);
     }
     final List<FieldNode> fList = cNode.getFields();
     for (FieldNode fNode : fList) {
       if (foundNames.contains(fNode.getName())) {
         revertVisibility(fNode);
       }
     }
   }
 }
Exemplo n.º 29
0
  private void assertMembersNamesAreUnique() {
    Map<String, FieldNode> allDslCollectionFieldNodesOfHierarchy = new HashMap<String, FieldNode>();

    for (ClassNode level : ASTHelper.getHierarchyOfDSLObjectAncestors(annotatedClass)) {
      for (FieldNode field : level.getFields()) {
        if (!ASTHelper.isListOrMap(field.getType())) continue;

        String memberName = getElementNameForCollectionField(field);

        FieldNode conflictingField = allDslCollectionFieldNodesOfHierarchy.get(memberName);

        if (conflictingField != null) {
          addCompileError(
              String.format(
                  "Member name %s is used more than once: %s:%s and %s:%s",
                  memberName,
                  field.getOwner().getName(),
                  field.getName(),
                  conflictingField.getOwner().getName(),
                  conflictingField.getName()),
              field);
          return;
        }

        allDslCollectionFieldNodesOfHierarchy.put(memberName, field);
      }
    }
  }
 private Statement createConstructorStatementCollection(FieldNode fNode) {
   final Expression fieldExpr = new VariableExpression(fNode);
   Expression initExpr = fNode.getInitialValueExpression();
   if (initExpr == null) initExpr = new ConstantExpression(null);
   Expression collection = findArg(fNode.getName());
   ClassNode fieldType = fieldExpr.getType();
   return new IfStatement(
       equalsNullExpr(collection),
       new IfStatement(
           equalsNullExpr(initExpr),
           new EmptyStatement(),
           assignStatement(fieldExpr, cloneCollectionExpr(initExpr))),
       new IfStatement(
           isInstanceOf(collection, CLONEABLE_TYPE),
           assignStatement(
               fieldExpr, cloneCollectionExpr(cloneArrayOrCloneableExpr(collection, fieldType))),
           assignStatement(fieldExpr, cloneCollectionExpr(collection))));
 }