Пример #1
1
 private void makeInterfaceTypes(CompileUnit cu, ClassNode classNode, Class clazz) {
   Type[] interfaceTypes = clazz.getGenericInterfaces();
   if (interfaceTypes.length == 0) {
     classNode.setInterfaces(ClassNode.EMPTY_ARRAY);
   } else {
     ClassNode[] ret = new ClassNode[interfaceTypes.length];
     for (int i = 0; i < interfaceTypes.length; i++) {
       Type type = interfaceTypes[i];
       while (!(type instanceof Class)) {
         ParameterizedType pt = (ParameterizedType) type;
         Type t2 = pt.getRawType();
         if (t2 == type) {
           throw new GroovyBugError(
               "Cannot transform generic signature of "
                   + clazz
                   + " with generic interface "
                   + interfaceTypes[i]
                   + " to a class.");
         }
         type = t2;
       }
       ret[i] = makeClassNode(cu, interfaceTypes[i], (Class) type);
     }
     classNode.setInterfaces(ret);
   }
 }
 public void visitClass(ClassNode node) {
   visitAnnotations(node);
   visitPackage(node.getPackage());
   visitImports(node.getModule());
   node.visitContents(this);
   visitObjectInitializerStatements(node);
 }
Пример #3
0
  public boolean addGeneratedClosureConstructorCall(ConstructorCallExpression call) {
    ClassNode classNode = controller.getClassNode();
    if (!classNode.declaresInterface(ClassHelper.GENERATED_CLOSURE_Type)) return false;

    AsmClassGenerator acg = controller.getAcg();
    OperandStack operandStack = controller.getOperandStack();

    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitVarInsn(ALOAD, 0);
    ClassNode callNode = classNode.getSuperClass();
    TupleExpression arguments = (TupleExpression) call.getArguments();
    if (arguments.getExpressions().size() != 2)
      throw new GroovyBugError(
          "expected 2 arguments for closure constructor super call, but got"
              + arguments.getExpressions().size());
    arguments.getExpression(0).visit(acg);
    operandStack.box();
    arguments.getExpression(1).visit(acg);
    operandStack.box();
    // TODO: replace with normal String, p not needed
    Parameter p = new Parameter(ClassHelper.OBJECT_TYPE, "_p");
    String descriptor =
        BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, new Parameter[] {p, p});
    mv.visitMethodInsn(
        INVOKESPECIAL, BytecodeHelper.getClassInternalName(callNode), "<init>", descriptor, false);
    operandStack.remove(2);
    return true;
  }
Пример #4
0
  public static void loadReference(String name, WriterController controller) {
    CompileStack compileStack = controller.getCompileStack();
    MethodVisitor mv = controller.getMethodVisitor();
    ClassNode classNode = controller.getClassNode();
    AsmClassGenerator acg = controller.getAcg();

    // compileStack.containsVariable(name) means to ask if the variable is already declared
    // compileStack.getScope().isReferencedClassVariable(name) means to ask if the variable is a
    // field
    // If it is no field and is not yet declared, then it is either a closure shared variable or
    // an already declared variable.
    if (!compileStack.containsVariable(name)
        && compileStack.getScope().isReferencedClassVariable(name)) {
      acg.visitFieldExpression(new FieldExpression(classNode.getDeclaredField(name)));
    } else {
      BytecodeVariable v =
          compileStack.getVariable(name, !classNodeUsesReferences(controller.getClassNode()));
      if (v == null) {
        // variable is not on stack because we are
        // inside a nested Closure and this variable
        // was not used before
        // then load it from the Closure field
        FieldNode field = classNode.getDeclaredField(name);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(
            GETFIELD,
            controller.getInternalClassName(),
            name,
            BytecodeHelper.getTypeDescription(field.getType()));
      } else {
        mv.visitVarInsn(ALOAD, v.getIndex());
      }
      controller.getOperandStack().push(ClassHelper.REFERENCE_TYPE);
    }
  }
Пример #5
0
 public static void addMethodIfNotPresent(ClassNode controllerClassNode, MethodNode methodNode) {
   MethodNode existing =
       controllerClassNode.getMethod(methodNode.getName(), methodNode.getParameters());
   if (existing == null) {
     controllerClassNode.addMethod(methodNode);
   }
 }
  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 void printTypeName(PrintWriter out, ClassNode type) {
   if (ClassHelper.isPrimitiveType(type)) {
     if (type == ClassHelper.boolean_TYPE) {
       out.print("boolean");
     } else if (type == ClassHelper.char_TYPE) {
       out.print("char");
     } else if (type == ClassHelper.int_TYPE) {
       out.print("int");
     } else if (type == ClassHelper.short_TYPE) {
       out.print("short");
     } else if (type == ClassHelper.long_TYPE) {
       out.print("long");
     } else if (type == ClassHelper.float_TYPE) {
       out.print("float");
     } else if (type == ClassHelper.double_TYPE) {
       out.print("double");
     } else if (type == ClassHelper.byte_TYPE) {
       out.print("byte");
     } else {
       out.print("void");
     }
   } else {
     String name = type.getName();
     // check for an alias
     ClassNode alias = currentModule.getImportType(name);
     if (alias != null) name = alias.getName();
     out.print(name.replace('$', '.'));
   }
 }
Пример #8
0
 private void configureAnnotationFromDefinition(AnnotationNode definition, AnnotationNode root) {
   ClassNode type = definition.getClassNode();
   if (!type.isResolved()) return;
   Class clazz = type.getTypeClass();
   if (clazz == Retention.class) {
     Expression exp = definition.getMember("value");
     if (!(exp instanceof PropertyExpression)) return;
     PropertyExpression pe = (PropertyExpression) exp;
     String name = pe.getPropertyAsString();
     RetentionPolicy policy = RetentionPolicy.valueOf(name);
     setRetentionPolicy(policy, root);
   } else if (clazz == Target.class) {
     Expression exp = definition.getMember("value");
     if (!(exp instanceof ListExpression)) return;
     ListExpression le = (ListExpression) exp;
     int bitmap = 0;
     for (Expression e : le.getExpressions()) {
       PropertyExpression element = (PropertyExpression) e;
       String name = element.getPropertyAsString();
       ElementType value = ElementType.valueOf(name);
       bitmap |= getElementCode(value);
     }
     root.setAllowedTargets(bitmap);
   }
 }
 /**
  * Snoops through the declaring class and all parents looking for methods
  *
  * <ul>
  *   <li><code>public String getMessage(java.lang.String)</code>
  *   <li><code>public String getMessage(java.lang.String, java.util.Locale)</code>
  *   <li><code>public String getMessage(java.lang.String, java.lang.Object[])</code>
  *   <li><code>public String getMessage(java.lang.String, java.lang.Object[], java.util.Locale)
  *       </code>
  *   <li><code>public String getMessage(java.lang.String, java.util.List)</code>
  *   <li><code>public String getMessage(java.lang.String, java.util.List, java.util.Locale)</code>
  *   <li><code>public String getMessage(java.lang.String, java.util.Map)</code>
  *   <li><code>public String getMessage(java.lang.String, java.util.Map, java.util.Locale)</code>
  *   <li><code>public String getMessage(java.lang.String, java.lang.String)</code>
  *   <li><code>public String getMessage(java.lang.String, java.lang.String, java.util.Locale)
  *       </code>
  *   <li><code>public String getMessage(java.lang.String, java.lang.Object[], java.lang.String)
  *       </code>
  *   <li><code>
  *       public String getMessage(java.lang.String, java.lang.Object[], java.lang.String, java.util.Locale)
  *       </code>
  *   <li><code>public String getMessage(java.lang.String, java.util.List, java.lang.String)</code>
  *   <li><code>
  *       public String getMessage(java.lang.String, java.util.List, java.lang.String, java.util.Locale)
  *       </code>
  *   <li><code>public String getMessage(java.lang.String, java.util.Map, java.lang.String)</code>
  *   <li><code>
  *       public String getMessage(java.lang.String, java.util.Map, java.lang.String, java.util.Locale)
  *       </code>
  * </ul>
  *
  * If any are defined all must be defined or a compilation error results.
  *
  * @param declaringClass the class to search
  * @param sourceUnit the source unit, for error reporting. {@code @NotNull}.
  * @return true if property change support should be added
  */
 protected static boolean needsMessageSource(ClassNode declaringClass, SourceUnit sourceUnit) {
   boolean found = false;
   ClassNode consideredClass = declaringClass;
   while (consideredClass != null) {
     for (MethodNode method : consideredClass.getMethods()) {
       // just check length, MOP will match it up
       found = method.getName().equals(METHOD_GET_MESSAGE) && method.getParameters().length == 1;
       found |= method.getName().equals(METHOD_GET_MESSAGE) && method.getParameters().length == 2;
       found |= method.getName().equals(METHOD_GET_MESSAGE) && method.getParameters().length == 3;
       found |= method.getName().equals(METHOD_GET_MESSAGE) && method.getParameters().length == 4;
       if (found) return false;
     }
     consideredClass = consideredClass.getSuperClass();
   }
   if (found) {
     sourceUnit
         .getErrorCollector()
         .addErrorAndContinue(
             new SimpleMessage(
                 "@MessageSourceAware cannot be processed on "
                     + declaringClass.getName()
                     + " because some but not all of variants of getMessage() were declared in the current class or super classes.",
                 sourceUnit));
     return false;
   }
   return true;
 }
Пример #10
0
  private Expression transformInlineConstants(Expression exp) {
    if (exp instanceof PropertyExpression) {
      PropertyExpression pe = (PropertyExpression) exp;
      if (pe.getObjectExpression() instanceof ClassExpression) {
        ClassExpression ce = (ClassExpression) pe.getObjectExpression();
        ClassNode type = ce.getType();
        if (type.isEnum()) return exp;
        Expression constant = findConstant(type.getField(pe.getPropertyAsString()));
        // GRECLIPSE edit
        // if (constant != null) return constant;
        if (constant != null) {
          String name = pe.getText().replace('$', '.');
          Object alias = pe.getNodeMetaData("static.import.alias");
          if (alias != null && !alias.equals(pe.getPropertyAsString())) {
            name += " as " + alias;
          }
          // store the qualified name to facilitate organizing static imports
          constant.setNodeMetaData("static.import", name);

          return constant;
        }
        // GRECLIPSE end
      }
    } else if (exp instanceof ListExpression) {
      ListExpression le = (ListExpression) exp;
      ListExpression result = new ListExpression();
      for (Expression e : le.getExpressions()) {
        result.addExpression(transformInlineConstants(e));
      }
      return result;
    }

    return exp;
  }
  @Override
  protected void assignToArray(
      Expression orig, Expression receiver, Expression index, Expression rhsValueLoader) {
    ClassNode current = getController().getClassNode();
    ClassNode arrayType = getController().getTypeChooser().resolveType(receiver, current);
    ClassNode arrayComponentType = arrayType.getComponentType();
    int operationType = getOperandType(arrayComponentType);
    BinaryExpressionWriter bew = binExpWriter[operationType];
    AsmClassGenerator acg = getController().getAcg();

    if (bew.arraySet(true) && arrayType.isArray()) {
      OperandStack operandStack = getController().getOperandStack();

      // load the array
      receiver.visit(acg);
      operandStack.doGroovyCast(arrayType);

      // load index
      index.visit(acg);
      operandStack.doGroovyCast(int_TYPE);

      // load rhs
      rhsValueLoader.visit(acg);
      operandStack.doGroovyCast(arrayComponentType);

      // store value in array
      bew.arraySet(false);

      // load return value && correct operand stack stack
      operandStack.remove(3);
      rhsValueLoader.visit(acg);
    } else {
      super.assignToArray(orig, receiver, index, rhsValueLoader);
    }
  }
Пример #12
0
 public static void configureAnnotationFromDefinition(
     AnnotationNode definition, AnnotationNode root) {
   ClassNode type = definition.getClassNode();
   if ("java.lang.annotation.Retention".equals(type.getName())) {
     Expression exp = definition.getMember("value");
     if (!(exp instanceof PropertyExpression)) return;
     PropertyExpression pe = (PropertyExpression) exp;
     String name = pe.getPropertyAsString();
     RetentionPolicy policy = RetentionPolicy.valueOf(name);
     setRetentionPolicy(policy, root);
   } else if ("java.lang.annotation.Target".equals(type.getName())) {
     Expression exp = definition.getMember("value");
     if (!(exp instanceof ListExpression)) return;
     ListExpression le = (ListExpression) exp;
     int bitmap = 0;
     for (Expression e : le.getExpressions()) {
       if (!(e instanceof PropertyExpression)) return;
       PropertyExpression element = (PropertyExpression) e;
       String name = element.getPropertyAsString();
       ElementType value = ElementType.valueOf(name);
       bitmap |= getElementCode(value);
     }
     root.setAllowedTargets(bitmap);
   }
 }
 @Override
 protected ClassNode createClosureClass(final ClosureExpression expression, final int mods) {
   ClassNode closureClass = super.createClosureClass(expression, mods);
   List<MethodNode> methods = closureClass.getDeclaredMethods("call");
   List<MethodNode> doCall = closureClass.getMethods("doCall");
   if (doCall.size() != 1) {
     throw new GroovyBugError(
         "Expected to find one (1) doCall method on generated closure, but found "
             + doCall.size());
   }
   MethodNode doCallMethod = doCall.get(0);
   if (methods.isEmpty() && doCallMethod.getParameters().length == 1) {
     createDirectCallMethod(closureClass, doCallMethod);
   }
   MethodTargetCompletionVisitor visitor = new MethodTargetCompletionVisitor(doCallMethod);
   Object dynamic = expression.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION);
   if (dynamic != null) {
     doCallMethod.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, dynamic);
   }
   for (MethodNode method : methods) {
     visitor.visitMethod(method);
   }
   closureClass.putNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE, Boolean.TRUE);
   return closureClass;
 }
Пример #14
0
  public Map<String, MethodNode> getDeclaredMethodsMap() {
    // Start off with the methods from the superclass.
    ClassNode parent = getSuperClass();
    Map<String, MethodNode> result = null;
    if (parent != null) {
      result = parent.getDeclaredMethodsMap();
    } else {
      result = new HashMap<String, MethodNode>();
    }

    // add in unimplemented abstract methods from the interfaces
    for (ClassNode iface : getInterfaces()) {
      Map<String, MethodNode> ifaceMethodsMap = iface.getDeclaredMethodsMap();
      for (String methSig : ifaceMethodsMap.keySet()) {
        if (!result.containsKey(methSig)) {
          MethodNode methNode = ifaceMethodsMap.get(methSig);
          result.put(methSig, methNode);
        }
      }
    }

    // And add in the methods implemented in this class.
    for (MethodNode method : getMethods()) {
      String sig = method.getTypeDescriptor();
      result.put(sig, method);
    }
    return result;
  }
  private List<PropertyNode> findTags(ClassNode classNode) {
    List<PropertyNode> tags = new ArrayList<PropertyNode>();
    List<PropertyNode> properties = classNode.getProperties();
    List<PropertyNode> potentialAliases = new ArrayList<PropertyNode>();
    for (PropertyNode property : properties) {
      if (property.isPublic()) {
        Expression initialExpression = property.getInitialExpression();
        if (initialExpression instanceof ClosureExpression) {
          ClosureExpression ce = (ClosureExpression) initialExpression;
          Parameter[] parameters = ce.getParameters();

          if (parameters.length <= 2) {
            tags.add(property);
            // force Closure type for DefaultGrailsTagLibClass
            property.setType(CLOSURE_CLASS_NODE);
          }
        } else if (initialExpression instanceof VariableExpression) {
          potentialAliases.add(property);
        }
      }
    }

    for (PropertyNode potentialAlias : potentialAliases) {
      VariableExpression pe = (VariableExpression) potentialAlias.getInitialExpression();

      String propertyName = pe.getName();
      PropertyNode property = classNode.getProperty(propertyName);
      if (property != null && tags.contains(property)) {
        potentialAlias.setType(CLOSURE_CLASS_NODE);
        tags.add(potentialAlias);
      }
    }
    return tags;
  }
 protected void addHasErrorsMethod(final ClassNode paramTypeClassNode) {
   final ASTNode getErrorsMethod =
       paramTypeClassNode.getMethod(
           HAS_ERRORS_METHOD_NAME, GrailsArtefactClassInjector.ZERO_PARAMETERS);
   if (getErrorsMethod == null) {
     final BlockStatement hasErrorsMethodCode = new BlockStatement();
     final Expression initErrorsMethodCallExpression =
         new MethodCallExpression(
             new VariableExpression("this"), INIT_ERRORS_METHOD_NAME, EMPTY_TUPLE);
     hasErrorsMethodCode.addStatement(new ExpressionStatement(initErrorsMethodCallExpression));
     final Statement returnStatement =
         new ReturnStatement(
             new BooleanExpression(
                 new MethodCallExpression(
                     ERRORS_EXPRESSION, HAS_ERRORS_METHOD_NAME, EMPTY_TUPLE)));
     hasErrorsMethodCode.addStatement(returnStatement);
     paramTypeClassNode.addMethod(
         new MethodNode(
             HAS_ERRORS_METHOD_NAME,
             Modifier.PUBLIC,
             new ClassNode(Boolean.class),
             GrailsArtefactClassInjector.ZERO_PARAMETERS,
             GrailsArtefactClassInjector.EMPTY_CLASS_ARRAY,
             hasErrorsMethodCode));
   }
 }
Пример #17
0
  private String genericsBounds(ClassNode theType, Set<String> visited) {
    String ret =
        theType.isArray() ? theType.getComponentType().getName() + "[]" : theType.getName();
    GenericsType[] genericsTypes = theType.getGenericsTypes();
    if (genericsTypes == null || genericsTypes.length == 0) return ret;
    // TODO instead of catching Object<T> here stop it from being placed into type in first place
    if (genericsTypes.length == 1
        && genericsTypes[0].isPlaceholder()
        && theType.getName().equals("java.lang.Object")) {
      return genericsTypes[0].getName();
    }
    ret += "<";
    for (int i = 0; i < genericsTypes.length; i++) {
      if (i != 0) ret += ", ";

      GenericsType type = genericsTypes[i];
      if (type.isPlaceholder() && visited.contains(type.getName())) {
        ret += type.getName();
      } else {
        ret += type.toString(visited);
      }
    }
    ret += ">";
    return ret;
  }
Пример #18
0
 public void removeField(String oldName) {
   ClassNode r = redirect();
   if (r.fieldIndex == null) r.fieldIndex = new HashMap<String, FieldNode>();
   final Map<String, FieldNode> index = r.fieldIndex;
   r.fields.remove(index.get(oldName));
   index.remove(oldName);
 }
Пример #19
0
    protected void addTimeStamp(ClassNode node) {
      if (node.getDeclaredField(Verifier.__TIMESTAMP)
          == null) { // in case if verifier visited the call already
        FieldNode timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP,
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression(System.currentTimeMillis()));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);

        timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP__ + String.valueOf(System.currentTimeMillis()),
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression((long) 0));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);
      }
    }
Пример #20
0
  /**
   * Compile the specified Groovy source files, applying any {@link CompilerAutoConfiguration}s. All
   * classes defined in the files will be returned from this method.
   *
   * @param file the file to compile
   * @return compiled classes
   * @throws CompilationFailedException
   * @throws IOException
   */
  public Class<?>[] compile(File... file) throws CompilationFailedException, IOException {

    this.loader.clearCache();
    List<Class<?>> classes = new ArrayList<Class<?>>();

    CompilerConfiguration configuration = this.loader.getConfiguration();

    CompilationUnit compilationUnit = new CompilationUnit(configuration, null, this.loader);
    SourceUnit sourceUnit =
        new SourceUnit(file[0], configuration, this.loader, compilationUnit.getErrorCollector());
    ClassCollector collector = this.loader.createCollector(compilationUnit, sourceUnit);
    compilationUnit.setClassgenCallback(collector);

    compilationUnit.addSources(file);

    addAstTransformations(compilationUnit);

    compilationUnit.compile(Phases.CLASS_GENERATION);
    for (Object loadedClass : collector.getLoadedClasses()) {
      classes.add((Class<?>) loadedClass);
    }
    ClassNode mainClassNode = (ClassNode) compilationUnit.getAST().getClasses().get(0);
    Class<?> mainClass = null;
    for (Class<?> loadedClass : classes) {
      if (mainClassNode.getName().equals(loadedClass.getName())) {
        mainClass = loadedClass;
      }
    }
    if (mainClass != null) {
      classes.remove(mainClass);
      classes.add(0, mainClass);
    }

    return classes.toArray(new Class<?>[classes.size()]);
  }
Пример #21
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));
    }
  }
Пример #22
0
  protected MethodNode weaveMock(
      ClassNode classNode, ClassExpression value, boolean isClassUnderTest) {

    ClassNode testTarget = value.getType();
    String className = testTarget.getName();
    MethodNode testForMethod = null;
    for (String artefactType : artefactTypeToTestMap.keySet()) {
      if (className.endsWith(artefactType)) {
        Class mixinClass = artefactTypeToTestMap.get(artefactType);
        if (!isAlreadyWoven(classNode, mixinClass)) {
          weaveMixinClass(classNode, mixinClass);
          if (isClassUnderTest) {
            testForMethod = addClassUnderTestMethod(classNode, value, artefactType);
          } else {
            addMockCollaboratorToSetup(classNode, value, artefactType);
          }
          return testForMethod;
        }

        addMockCollaboratorToSetup(classNode, value, artefactType);
        return null;
      }
    }

    // must be a domain class
    weaveMixinClass(classNode, DomainClassUnitTestMixin.class);
    if (isClassUnderTest) {
      testForMethod = addClassUnderTestMethod(classNode, value, DOMAIN_TYPE);
    } else {
      addMockCollaboratorToSetup(classNode, value, DOMAIN_TYPE);
    }

    return testForMethod;
  }
Пример #23
0
        public void call(SourceUnit source) throws CompilationFailedException {
          List<ClassNode> classes = source.ast.getClasses();
          for (ClassNode node : classes) {
            CompileUnit cu = node.getCompileUnit();
            for (Iterator iter = cu.iterateClassNodeToCompile(); iter.hasNext(); ) {
              String name = (String) iter.next();
              SourceUnit su = ast.getScriptSourceLocation(name);
              List<ClassNode> classesInSourceUnit = su.ast.getClasses();
              StringBuffer message = new StringBuffer();
              message
                  .append("Compilation incomplete: expected to find the class ")
                  .append(name)
                  .append(" in ")
                  .append(su.getName());
              if (classesInSourceUnit.isEmpty()) {
                message.append(", but the file seems not to contain any classes");
              } else {
                message.append(", but the file contains the classes: ");
                boolean first = true;
                for (ClassNode cn : classesInSourceUnit) {
                  if (!first) {
                    message.append(", ");
                  } else {
                    first = false;
                  }
                  message.append(cn.getName());
                }
              }

              getErrorCollector()
                  .addErrorAndContinue(new SimpleMessage(message.toString(), CompilationUnit.this));
              iter.remove();
            }
          }
        }
Пример #24
0
 public static String getClassInternalName(ClassNode t) {
   if (t.isPrimaryClassNode()) {
     if (t.isArray()) return "[L" + getClassInternalName(t.getComponentType()) + ";";
     return getClassInternalName(t.getName());
   }
   return getClassInternalName(t.getTypeClass());
 }
  protected void injectMethodMissing(ClassNode classNode) {
    FieldNode methodMissingInterceptor =
        classNode.addField(
            "this$methodMissingInterceptor",
            Modifier.FINAL | Modifier.STATIC | Modifier.PRIVATE | ACC_SYNTHETIC,
            METHOD_MISSING_INTERCEPTOR_CLASS,
            ctor(
                METHOD_MISSING_INTERCEPTOR_CLASS,
                args(classx(classNode), domainHandlerInstance())));

    classNode.addMethod(
        new MethodNode(
            "$static_methodMissing",
            Modifier.PUBLIC | Modifier.STATIC,
            ClassHelper.OBJECT_TYPE,
            params(
                param(ClassHelper.STRING_TYPE, "methodName"),
                param(ClassHelper.makeWithoutCaching(Object[].class), "arguments")),
            ClassNode.EMPTY_ARRAY,
            returns(
                call(
                    field(methodMissingInterceptor),
                    "handleMethodMissing",
                    args(var("methodName"), var("arguments"))))));
  }
  protected void injectDomainHandler(
      ClassNode classNode, String implementation, String datasource) {
    classNode.addMethod(
        new MethodNode(
            DOMAIN_HANDLER_METHOD_NAME,
            Modifier.PUBLIC | Modifier.STATIC,
            GRIFFON_DOMAIN_HANDLER_CLASS,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            returns(domainHandlerInstance())));

    classNode.addMethod(
        new MethodNode(
            MAPPING,
            Modifier.PUBLIC | Modifier.STATIC,
            ClassHelper.STRING_TYPE,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            returns(constx(implementation))));

    classNode.addMethod(
        new MethodNode(
            DATASOURCE,
            Modifier.PUBLIC | Modifier.STATIC,
            ClassHelper.STRING_TYPE,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            returns(constx(datasource))));
  }
  /**
   * Lookup a ClassNode by its name from the source unit
   *
   * @param type the name of the class whose ClassNode we want to lookup
   * @return a ClassNode representing the class
   */
  public ClassNode lookupClassNodeFor(String type) {
    for (ClassNode cn : typeCheckingVisitor.getSourceUnit().getAST().getClasses()) {
      if (cn.getName().equals(type)) return cn;
    }

    return null;
  }
 private boolean isKnownImmutableClass(ClassNode fieldType, List<String> knownImmutableClasses) {
   if (!fieldType.isResolved()) return false;
   return fieldType.isEnum()
       || ClassHelper.isPrimitiveType(fieldType)
       || fieldType.getAnnotations(MY_TYPE).size() != 0
       || inImmutableList(fieldType.getName())
       || knownImmutableClasses.contains(fieldType.getName());
 }
 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;
 }
Пример #30
0
 public void configureAnnotation(AnnotationNode node) {
   ClassNode type = node.getClassNode();
   List<AnnotationNode> annotations = type.getAnnotations();
   for (AnnotationNode an : annotations) {
     configureAnnotationFromDefinition(an, node);
   }
   configureAnnotationFromDefinition(node, node);
 }