Exemplo n.º 1
0
 private static String getResultType(ExecutableElement method, boolean native_stub) {
   if (native_stub && method.getAnnotation(PointerWrapper.class) != null) {
     return "long";
   } else if (!native_stub && method.getAnnotation(GLreturn.class) != null) {
     return Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false);
   } else {
     return Utils.getJavaType(Utils.getMethodReturnType(method)).getSimpleName();
   }
 }
Exemplo n.º 2
0
  public TargetMethodInjector(ExecutableElement executableElement) {
    this.executableElement = executableElement;
    this.methodName = executableElement.getSimpleName().toString();
    this.returnType = executableElement.getReturnType();
    this.arguments = executableElement.getParameters();

    if (executableElement.getAnnotation(POST.class) != null) {
      httpMethod = _POST;
      url = executableElement.getAnnotation(POST.class).value();
    } else if (executableElement.getAnnotation(GET.class) != null) {
      httpMethod = _GET;
      url = executableElement.getAnnotation(GET.class).value();
    }
  }
Exemplo n.º 3
0
  private static boolean printMethodCallArguments(
      PrintWriter writer,
      ExecutableElement method,
      Map<VariableElement, TypeInfo> typeinfos_instance,
      Mode mode,
      TypeMap type_map) {
    boolean first_parameter = true;
    for (VariableElement param : method.getParameters()) {
      if (param.getAnnotation(Result.class) != null
          || (param.getAnnotation(Helper.class) != null
              && !param.getAnnotation(Helper.class).passToNative())) {
        continue;
      }

      final Constant constant_annotation = param.getAnnotation(Constant.class);
      if (constant_annotation == null || !constant_annotation.isNative()) {
        first_parameter =
            printMethodCallArgument(
                writer, method, param, typeinfos_instance, mode, first_parameter, type_map);
      }
    }
    if (Utils.getNIOBufferType(Utils.getMethodReturnType(method)) != null) {
      if (method.getAnnotation(CachedResult.class) != null
          && method.getAnnotation(CachedResult.class).isRange()) {
        first_parameter = false;
        Utils.printExtraCallArguments(writer, method, "");
      } else {
        AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class);
        if (auto_size_annotation == null || !auto_size_annotation.isNative()) {
          if (!first_parameter) {
            writer.print(", ");
          }
          first_parameter = false;

          String result_size_expression;
          if (mode == Mode.CACHEDRESULT) {
            result_size_expression = Utils.CACHED_BUFFER_LENGTH_NAME;
          } else if (auto_size_annotation == null) {
            result_size_expression = Utils.RESULT_SIZE_NAME;
          } else {
            result_size_expression = auto_size_annotation.value();
          }

          Utils.printExtraCallArguments(writer, method, result_size_expression);
        }
      }
    }
    return first_parameter;
  }
Exemplo n.º 4
0
 @Override
 public void printErrorCheckMethod(
     final PrintWriter writer, final ExecutableElement method, final String tabs) {
   final Check check = method.getAnnotation(Check.class);
   if (check != null) // Get the error code from an IntBuffer output parameter
   writer.println(
         tabs + "Util.checkCLError(" + check.value() + ".get(" + check.value() + ".position()));");
   else {
     final Class return_type = Utils.getJavaType(method.getReturnType());
     if (return_type == int.class) writer.println(tabs + "Util.checkCLError(__result);");
     else {
       boolean hasErrCodeParam = false;
       for (final VariableElement param : method.getParameters()) {
         if ("errcode_ret".equals(param.getSimpleName().toString())
             && Utils.getJavaType(param.asType()) == IntBuffer.class) {
           hasErrCodeParam = true;
           break;
         }
       }
       if (hasErrCodeParam)
         throw new RuntimeException(
             "A method is missing the @Check annotation: " + method.toString());
     }
   }
 }
Exemplo n.º 5
0
  private void parseMethod(Api api, ExecutableElement executableElement) throws IOException {

    Element actionElement =
        generator
            .getProcessingEnvironment()
            .getElementUtils()
            .getTypeElement(ApiMethodDoc.class.getName());
    TypeMirror apiMethodDocType = actionElement.asType();

    for (AnnotationMirror am : executableElement.getAnnotationMirrors()) {
      if (am.getAnnotationType().equals(apiMethodDocType)) {
        api.apiMethodDoc = Maps.newHashMap();
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> ee :
            am.getElementValues().entrySet()) {
          api.apiMethodDoc.put(ee.getKey().getSimpleName().toString(), ee.getValue());
        }
        break;
      }
    }

    // generator.log("apiMethodDoc: " + api.apiMethodDoc);

    if (null == api.apiMethodDoc) {
      generator.log("Method miss @ApiMethodDoc. " + executableElement);
      return;
    }

    api.methodName = executableElement.getSimpleName().toString();
    api.methodMapping = executableElement.getAnnotation(RequestMapping.class);
    api.parameters = Lists.newArrayList();

    for (VariableElement var : executableElement.getParameters()) {
      api.parameters.add(var);
    }
  }
Exemplo n.º 6
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   // System.out.println("supported options: "+
   // Arrays.toString(getSupportedOptions().toArray()));
   if (!roundEnv.processingOver()) {
     for (TypeElement currAnno : annotations) {
       // System.out.println("Found " + currAnno.getQualifiedName());
       if (currAnno.getQualifiedName().contentEquals(GENERATE_POJO_BUILDER_CLASS.getName())) {
         Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(currAnno);
         // System.out.println("[GenerateBuilder] annotatedElements="+
         // Arrays.toString(annotatedElements.toArray()));
         for (Element elem : annotatedElements) {
           if (elem.getKind() == ElementKind.CLASS) {
             TypeElement typeElem = (TypeElement) elem;
             GeneratePojoBuilder annotation = typeElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS);
             generatePojoBuilderProcessor.process(typeElem, annotation);
           } else if (elem.getKind() == ElementKind.METHOD) {
             ExecutableElement execElem = (ExecutableElement) elem;
             GeneratePojoBuilder annotation = execElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS);
             generatePojoBuilderProcessor.process(execElem, annotation);
           }
         }
       }
     }
   }
   return false;
 }
Exemplo n.º 7
0
 private boolean checkForMultibindings(List<ExecutableElement> providerMethods) {
   for (ExecutableElement element : providerMethods) {
     if (element.getAnnotation(Provides.class).type() == Provides.Type.SET) {
       return true;
     }
   }
   return false;
 }
Exemplo n.º 8
0
  private static String getPostfixStrippedName(
      TypeMap type_map, TypeElement interface_decl, ExecutableElement method) {
    StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class);
    VariableElement postfix_parameter = Utils.findParameter(method, strip_annotation.value());
    String postfix = strip_annotation.postfix();
    boolean postfixOverride = !("NULL".equals(postfix) && strip_annotation.hasPostfix());
    if (!postfixOverride) {
      PostfixTranslator translator = new PostfixTranslator(type_map, postfix_parameter);
      postfix_parameter.asType().accept(translator, null);
      postfix = translator.getSignature();
    } else if (!strip_annotation.hasPostfix()) {
      postfix = "";
    }

    String method_name;
    Alternate alt_annotation = method.getAnnotation(Alternate.class);
    method_name =
        alt_annotation == null || alt_annotation.javaAlt()
            ? method.getSimpleName().toString()
            : alt_annotation.value();

    String extension_postfix =
        "NULL".equals(strip_annotation.extension())
            ? getExtensionPostfix(interface_decl)
            : strip_annotation.extension();

    Matcher matcher =
        getPostfixPattern(
                postfixOverride
                    ? (postfix + "(?:v)?" + extension_postfix + "$")
                    : ("(?:" + postfix + "(?:v)?|i(?:64)?_v|v)" + extension_postfix + "$"))
            .matcher(method_name);

    if (!matcher.find()) {
      throw new RuntimeException(
          method_name
              + " is specified as being postfix stripped on parameter "
              + postfix_parameter
              + ", but it's postfix is neither '"
              + postfix
              + "' nor 'v'");
    }

    return method_name.substring(0, matcher.start()) + extension_postfix;
  }
Exemplo n.º 9
0
 private static void printParameterCheck(
     PrintWriter writer,
     ExecutableElement method,
     String name,
     String type,
     String check_value,
     boolean can_be_null,
     NullTerminated null_terminated,
     boolean generate_error_checks) {
   String tabs;
   if (can_be_null) {
     writer.print("\t\tif (" + name + " != null)");
     if (null_terminated != null) {
       writer.println(" {");
     } else {
       writer.println();
     }
     tabs = "\t\t\t";
   } else {
     tabs = "\t\t";
   }
   writer.print(tabs + "BufferChecks.check");
   if (check_value != null && check_value.length() > 0) {
     writer.print("Buffer");
     if ("Buffer".equals(type)) {
       writer.print(
           "Size"); // Check size only, Buffer.isDirect() was added in 1.6, cannot use yet. TODO:
                    // Remove?
     }
     writer.print("(" + name + ", " + check_value);
   } else {
     writer.print("Direct(" + name);
   }
   writer.println(");");
   if (can_be_null && generate_error_checks) {
     final Check check_annotation = method.getAnnotation(Check.class);
     if (check_annotation != null && check_annotation.value().equals(name)) {
       writer.println("\t\telse");
       writer.println(
           "\t\t\t" + name + " = APIUtil.getBufferIntDebug();"); // Use an exclusive buffer here
     }
   }
   if (null_terminated != null) {
     writer.print(tabs + "BufferChecks.checkNullTerminated(");
     writer.print(name);
     if (null_terminated.value().length() > 0) {
       writer.print(", ");
       writer.print(null_terminated.value());
     }
     writer.println(");");
     if (can_be_null) {
       writer.println("\t\t}");
     }
   }
 }
Exemplo n.º 10
0
  /**
   * @param env the environment
   * @param annUtil utils
   * @param d the method
   */
  public MethodHandler(
      final ProcessingEnvironment env, final AnnUtil annUtil, final ExecutableElement d) {
    this.env = env;
    this.annUtil = annUtil;
    msg = env.getMessager();

    staticMethod = d.getModifiers().contains(Modifier.STATIC);
    methName = d.getSimpleName().toString();
    getter = methName.startsWith("get");
    setter = methName.startsWith("set");

    immutable = d.getAnnotation(Immutable.class) != null;

    CloneForOverride cfo = d.getAnnotation(CloneForOverride.class);
    cloneForOverride = cfo != null;
    if (cloneForOverride) {
      cloneCollectionType = cfo.cloneCollectionType();
      cloneElementType = cfo.cloneElementType();
    }

    returnType = d.getReturnType();
    returnsVoid = env.getTypeUtils().getNoType(TypeKind.VOID).equals(returnType);

    pars = d.getParameters();
    thrownTypes = d.getThrownTypes();

    if ((setter) && (pars != null) && (pars.size() == 1)) {
      fieldType = pars.iterator().next().asType();
      basicType = fieldType.getKind().isPrimitive();
    }

    if (getter) {
      fieldType = returnType;
      basicType = returnType.getKind().isPrimitive();
    }

    if (setter || getter) {
      ucFieldName = methName.substring(3);
      fieldName = ucFieldName.substring(0, 1).toLowerCase() + ucFieldName.substring(1);
    }
  }
Exemplo n.º 11
0
 private static String getDefaultResultValue(ExecutableElement method) {
   if (method.getAnnotation(GLreturn.class) != null) {
     final String type =
         Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false);
     if ("boolean".equals(type)) {
       return "false";
     } else if (Character.isLowerCase(type.charAt(0))) {
       return "0";
     } else {
       return "null";
     }
   } else {
     final Class type = Utils.getJavaType(Utils.getMethodReturnType(method));
     if (type.isPrimitive()) {
       if (type == boolean.class) {
         return "false";
       } else {
         return "0";
       }
     } else {
       return "null";
     }
   }
 }
Exemplo n.º 12
0
  private void processRequestMappingMethod(ExecutableElement executableElement) {
    TypeElement cls = (TypeElement) executableElement.getEnclosingElement();
    String path = getClassLevelUrlPath(cls);

    RequestMapping anno = executableElement.getAnnotation(RequestMapping.class);
    path = addMethodPathComponent(executableElement, cls, path, anno);
    RequestMethod meth = getRequestMethod(executableElement, cls, anno);

    RestDocumentation.Resource.Method doc =
        _docs.getResourceDocumentation(path).newMethodDocumentation(meth);
    String docComment = processingEnv.getElementUtils().getDocComment(executableElement);
    if (StringUtils.isNotBlank(docComment)) {
      MethodStructure methodStructure = generateMethodStructure(docComment);
      doc.setCommentText(generateJavaDocHTML(methodStructure));
      doc.setCommentSummary(methodStructure.getDescription());
    }
    buildParameterData(executableElement, doc);
    buildResponseFormat(executableElement.getReturnType(), doc);
  }
Exemplo n.º 13
0
    public SectorMethod build() {
      SectorMethod method = new SectorMethod();
      String methodName = methodElement.getSimpleName().toString();
      SectorOperation operationAnnotation = methodElement.getAnnotation(SectorOperation.class);
      if (operationAnnotation == null) {
        return null;
      }

      int argCount = methodElement.getParameters().size();

      method.cellbased = operationAnnotation.cellbased();
      method.name = "hz_" + methodName;

      method.returnType = methodElement.getReturnType().toString();
      method.invocationClassName =
          CodeGenerationUtils.capitalizeFirstLetter(methodName) + argCount + "Invocation";
      method.targetMethod = methodName;
      method.readonly = operationAnnotation.readonly();
      method.functionId = sectorClassModel.getMethods().size();

      List<FormalArgument> args = new LinkedList<>();

      for (VariableElement variableElement : methodElement.getParameters()) {
        FormalArgument formalArgument = new FormalArgument();
        if (method.cellbased && args.isEmpty()) {
          formalArgument.name = "id";
          formalArgument.type = "long";
        } else {
          formalArgument.name = "arg" + (args.size() + 1);
          formalArgument.type = variableElement.asType().toString();
        }
        args.add(formalArgument);
      }

      method.formalArguments = args;

      buildOriginalMethos(method);

      buildAsyncMethod(method);

      return method;
    }
Exemplo n.º 14
0
    private boolean isJsonBeanGetter(ExecutableElement executableElement) {
      if (executableElement.getKind() != ElementKind.METHOD) {
        return false;
      }

      if (executableElement.getReturnType().getKind() == TypeKind.NULL) {
        return false;
      }

      if (!(executableElement.getSimpleName().toString().startsWith("get")
          || executableElement.getSimpleName().toString().startsWith("is"))) {
        return false;
      }

      if (executableElement.getParameters().size() > 0) {
        return false;
      }

      return executableElement.getAnnotation(JsonIgnore.class) == null;
    }
Exemplo n.º 15
0
  private void processLabels(TypeElement resourcesType, List<LabelTemplateMethod> methods) {
    for (Element element : resourcesType.getEnclosedElements()) {
      if (element.getKind() != ElementKind.METHOD) {
        continue;
      }
      final ExecutableElement method = (ExecutableElement) element;
      Message labelAnnotation = element.getAnnotation(Message.class);
      final TemplateParam returnType = new TemplateParam(method.getReturnType().toString());
      final boolean deprecated = method.getAnnotation(Deprecated.class) != null;
      final LabelTemplateMethod labelMethod;
      try {
        labelMethod =
            new LabelTemplateMethod(
                method.getSimpleName().toString(),
                deprecated,
                returnType,
                labelAnnotation.value(),
                labelAnnotation.mobile());
      } catch (Throwable t) {
        processingEnv.getMessager().printMessage(Kind.WARNING, t.getMessage(), resourcesType);
        continue;
      }

      for (VariableElement variable : method.getParameters()) {
        final String paramName = variable.getSimpleName().toString();
        final String paramType = variable.asType().toString();

        List<TemplateAnnotation> annotations = new ArrayList<TemplateAnnotation>();
        for (AnnotationMirror annotationMirrors : variable.getAnnotationMirrors()) {
          annotations.add(new TemplateAnnotation(annotationMirrors.getAnnotationType().toString()));
        }

        labelMethod.getParams().add(new TemplateParam(paramType, paramName, annotations));
      }
      methods.add(labelMethod);
    }
  }
Exemplo n.º 16
0
  private void traverse() {
    DataObject ann = modelElt.getAnnotation(DataObject.class);
    this.generateConverter = ann.generateConverter();
    this.inheritConverter = ann.inheritConverter();
    this.isClass = modelElt.getKind() == ElementKind.CLASS;
    this.concrete = isClass && !modelElt.getModifiers().contains(Modifier.ABSTRACT);
    try {
      this.type = (ClassTypeInfo) typeFactory.create(modelElt.asType());
    } catch (ClassCastException e) {
      throw new GenException(
          modelElt, "Data object must be a plain java class with no type parameters");
    }
    Helper.checkUnderModule(this, "@VertxGen");
    doc = docFactory.createDoc(modelElt);

    if (getModule() == null) {
      throw new GenException(
          modelElt, "Data object must have an ancestor package annotated with @ModuleGen");
    }

    modelElt
        .getInterfaces()
        .stream()
        .filter(
            superTM ->
                superTM instanceof DeclaredType
                    && ((DeclaredType) superTM).asElement().getAnnotation(DataObject.class) != null)
        .map(e -> (ClassTypeInfo) typeFactory.create(e))
        .forEach(abstractSuperTypes::add);

    superTypes.addAll(abstractSuperTypes);

    TypeMirror superClass = modelElt.getSuperclass();
    if (superClass instanceof DeclaredType
        && ((DeclaredType) superClass).asElement().getAnnotation(DataObject.class) != null) {
      superType = (ClassTypeInfo) typeFactory.create(superClass);
      superTypes.add(superType);
    }

    int result = 0;
    List<ExecutableElement> methodsElt = new ArrayList<>();
    for (Element enclosedElt : elementUtils.getAllMembers(modelElt)) {
      switch (enclosedElt.getKind()) {
        case CONSTRUCTOR:
          ExecutableElement constrElt = (ExecutableElement) enclosedElt;
          result |= processConstructor(constrElt);
          break;
        case METHOD:
          {
            ExecutableElement methodElt = (ExecutableElement) enclosedElt;
            if (methodElt.getSimpleName().toString().equals("toJson")
                && methodElt.getParameters().isEmpty()
                && typeFactory.create(methodElt.getReturnType()).getKind()
                    == ClassKind.JSON_OBJECT) {
              jsonifiable = true;
            }
            if (methodElt.getAnnotation(GenIgnore.class) == null) {
              methodsElt.add(methodElt);
            }
            break;
          }
      }
    }

    processMethods(methodsElt);

    boolean hasJsonConstructor = (result & 2) == 2;

    if (concrete && !hasJsonConstructor) {
      throw new GenException(
          modelElt,
          "Data object "
              + modelElt
              + " class does not have a constructor "
              + modelElt.getSimpleName()
              + "("
              + JsonObject.class.getSimpleName()
              + ")");
    }

    // Sort the properties so we do have a consistent order
    ArrayList<PropertyInfo> props = new ArrayList<>(propertyMap.values());
    Collections.sort(props, (p1, p2) -> p1.name.compareTo(p2.name));
    propertyMap.clear();
    props.forEach(prop -> propertyMap.put(prop.name, prop));
  }
Exemplo n.º 17
0
  private static void printParameterChecks(
      PrintWriter writer,
      ExecutableElement method,
      Map<VariableElement, TypeInfo> typeinfos,
      Mode mode,
      final boolean generate_error_checks) {
    if (mode == Mode.NORMAL) {
      final GenerateAutos gen_autos_annotation = method.getAnnotation(GenerateAutos.class);
      if (gen_autos_annotation != null && gen_autos_annotation.sizeVariables().length > 0) {
        // For the auto-generated parameters, declare and init a size variable (that can be reused
        // by @Code)
        for (final VariableElement param : method.getParameters()) {
          if (Arrays.binarySearch(
                  gen_autos_annotation.sizeVariables(), param.getSimpleName().toString())
              >= 0) {
            final int shifting = getBufferElementSizeExponent(typeinfos.get(param).getType());
            final Check check_annotation = param.getAnnotation(Check.class);

            writer.print("\t\tlong " + param.getSimpleName() + "_size = ");
            if (check_annotation == null || !check_annotation.canBeNull()) {
              writer.println(param.getSimpleName() + ".remaining() << " + shifting + ";");
            } else {
              writer.println(
                  param.getSimpleName()
                      + " == null ? 0 : "
                      + param.getSimpleName()
                      + ".remaining() << "
                      + shifting
                      + ";");
            }
          }
        }
      }
    }

    for (VariableElement param : method.getParameters()) {
      Class java_type = Utils.getJavaType(param.asType());
      if (java_type.isArray()
          || (Utils.isAddressableType(java_type)
              && (mode != Mode.BUFFEROBJECT || param.getAnnotation(BufferObject.class) == null)
              && (mode != Mode.AUTOS || getAutoTypeParameter(method, param) == null)
              && param.getAnnotation(Result.class) == null
              && !Utils.isReturnParameter(method, param))) {
        String check_value = null;
        boolean can_be_null = false;
        Check check_annotation = param.getAnnotation(Check.class);
        if (check_annotation != null) {
          check_value = check_annotation.value();
          can_be_null = check_annotation.canBeNull();
        }
        if ((Buffer.class.isAssignableFrom(java_type)
                || PointerBuffer.class.isAssignableFrom(java_type))
            && param.getAnnotation(Constant.class) == null) {
          TypeInfo typeinfo = typeinfos.get(param);
          printParameterCheck(
              writer,
              method,
              param.getSimpleName().toString(),
              typeinfo.getType().getSimpleName(),
              check_value,
              can_be_null,
              param.getAnnotation(NullTerminated.class),
              generate_error_checks);
        } else if (String.class.equals(java_type)) {
          if (!can_be_null) {
            writer.println("\t\tBufferChecks.checkNotNull(" + param.getSimpleName() + ");");
          }
        } else if (java_type.isArray()) {
          printArrayParameterCheck(
              writer, param.getSimpleName().toString(), check_value, can_be_null);
        }
      }
    }
    if (method.getAnnotation(CachedResult.class) != null) {
      printParameterCheck(
          writer, method, Utils.CACHED_BUFFER_NAME, null, null, true, null, generate_error_checks);
    }
  }
Exemplo n.º 18
0
  private void writeProvidesAdapter(
      JavaWriter writer,
      ExecutableElement providerMethod,
      Map<ExecutableElement, String> methodToClassName,
      Map<String, AtomicInteger> methodNameToNextId)
      throws IOException {
    String methodName = providerMethod.getSimpleName().toString();
    String moduleType = CodeGen.typeToString(providerMethod.getEnclosingElement().asType());
    String className = bindingClassName(providerMethod, methodToClassName, methodNameToNextId);
    String returnType = CodeGen.typeToString(providerMethod.getReturnType());
    List<? extends VariableElement> parameters = providerMethod.getParameters();
    boolean dependent = !parameters.isEmpty();

    writer.emitEmptyLine();
    writer.emitJavadoc(binderTypeDocs(returnType, false, false, dependent));
    writer.beginType(
        className,
        "class",
        PUBLIC | FINAL | STATIC,
        JavaWriter.type(Binding.class, returnType),
        JavaWriter.type(Provider.class, returnType));
    writer.emitField(moduleType, "module", PRIVATE | FINAL);
    for (Element parameter : parameters) {
      TypeMirror parameterType = parameter.asType();
      writer.emitField(
          JavaWriter.type(Binding.class, CodeGen.typeToString(parameterType)),
          parameterName(parameter),
          PRIVATE);
    }

    writer.emitEmptyLine();
    writer.beginMethod(null, className, PUBLIC, moduleType, "module");
    boolean singleton = providerMethod.getAnnotation(Singleton.class) != null;
    String key = JavaWriter.stringLiteral(GeneratorKeys.get(providerMethod));
    String membersKey = null;
    writer.emitStatement(
        "super(%s, %s, %s, %s.class)",
        key, membersKey, (singleton ? "IS_SINGLETON" : "NOT_SINGLETON"), moduleType);
    writer.emitStatement("this.module = module");
    writer.endMethod();

    if (dependent) {
      writer.emitEmptyLine();
      writer.emitJavadoc(ProcessorJavadocs.ATTACH_METHOD);
      writer.emitAnnotation(Override.class);
      writer.emitAnnotation(SuppressWarnings.class, JavaWriter.stringLiteral("unchecked"));
      writer.beginMethod("void", "attach", PUBLIC, Linker.class.getCanonicalName(), "linker");
      for (VariableElement parameter : parameters) {
        String parameterKey = GeneratorKeys.get(parameter);
        writer.emitStatement(
            "%s = (%s) linker.requestBinding(%s, %s.class)",
            parameterName(parameter),
            writer.compressType(
                JavaWriter.type(Binding.class, CodeGen.typeToString(parameter.asType()))),
            JavaWriter.stringLiteral(parameterKey),
            writer.compressType(moduleType));
      }
      writer.endMethod();

      writer.emitEmptyLine();
      writer.emitJavadoc(ProcessorJavadocs.GET_DEPENDENCIES_METHOD);
      writer.emitAnnotation(Override.class);
      String setOfBindings = JavaWriter.type(Set.class, "Binding<?>");
      writer.beginMethod(
          "void",
          "getDependencies",
          PUBLIC,
          setOfBindings,
          "getBindings",
          setOfBindings,
          "injectMembersBindings");
      for (Element parameter : parameters) {
        writer.emitStatement("getBindings.add(%s)", parameter.getSimpleName().toString());
      }
      writer.endMethod();
    }

    writer.emitEmptyLine();
    writer.emitJavadoc(ProcessorJavadocs.GET_METHOD, returnType);
    writer.emitAnnotation(Override.class);
    writer.beginMethod(returnType, "get", PUBLIC);
    StringBuilder args = new StringBuilder();
    boolean first = true;
    for (Element parameter : parameters) {
      if (!first) args.append(", ");
      else first = false;
      args.append(String.format("%s.get()", parameter.getSimpleName().toString()));
    }
    writer.emitStatement("return module.%s(%s)", methodName, args.toString());
    writer.endMethod();

    writer.endType();
  }
Exemplo n.º 19
0
  /** TODO : fix info multi-type methods print. */
  private static void generateMethodJava(
      ProcessingEnvironment env,
      TypeMap type_map,
      PrintWriter writer,
      TypeElement interface_decl,
      ExecutableElement method,
      boolean generate_error_checks,
      boolean context_specific) {
    writer.println();
    if (Utils.isMethodIndirect(generate_error_checks, context_specific, method)) {
      if (method.getAnnotation(GenerateAutos.class) != null) {
        printMethodWithMultiType(
            env,
            type_map,
            writer,
            interface_decl,
            method,
            TypeInfo.getDefaultTypeInfoMap(method),
            Mode.AUTOS,
            generate_error_checks,
            context_specific);
      }
      Collection<Map<VariableElement, TypeInfo>> cross_product =
          TypeInfo.getTypeInfoCrossProduct(type_map, method);
      for (Map<VariableElement, TypeInfo> typeinfos_instance : cross_product) {
        printMethodWithMultiType(
            env,
            type_map,
            writer,
            interface_decl,
            method,
            typeinfos_instance,
            Mode.NORMAL,
            generate_error_checks,
            context_specific);
      }
    }
    if (method.getAnnotation(CachedResult.class) != null
        && !method.getAnnotation(CachedResult.class).isRange()) {
      printMethodWithMultiType(
          env,
          type_map,
          writer,
          interface_decl,
          method,
          TypeInfo.getDefaultTypeInfoMap(method),
          Mode.CACHEDRESULT,
          generate_error_checks,
          context_specific);
    }

    Reuse reuse_annotation = method.getAnnotation(Reuse.class);
    Alternate alt_annotation = method.getAnnotation(Alternate.class);
    if (alt_annotation == null || (alt_annotation.nativeAlt() && !alt_annotation.skipNative())) {
      if (alt_annotation != null
          && method.getSimpleName().toString().equals(alt_annotation.value())) {
        throw new RuntimeException(
            "An alternate function with native code should have a different name than the main function.");
      }

      if (reuse_annotation == null) {
        printJavaNativeStub(
            env, writer, method, Mode.NORMAL, generate_error_checks, context_specific);
      }

      if (Utils.hasMethodBufferObjectParameter(method)) {
        printMethodWithMultiType(
            env,
            type_map,
            writer,
            interface_decl,
            method,
            TypeInfo.getDefaultTypeInfoMap(method),
            Mode.BUFFEROBJECT,
            generate_error_checks,
            context_specific);
        if (reuse_annotation == null) {
          printJavaNativeStub(
              env, writer, method, Mode.BUFFEROBJECT, generate_error_checks, context_specific);
        }
      }
    }
  }
Exemplo n.º 20
0
  private static void printMethodWithMultiType(
      ProcessingEnvironment env,
      TypeMap type_map,
      PrintWriter writer,
      TypeElement interface_decl,
      ExecutableElement method,
      Map<VariableElement, TypeInfo> typeinfos_instance,
      Mode mode,
      boolean generate_error_checks,
      boolean context_specific) {
    Utils.printDocComment(writer, method, env);
    if (method.getAnnotation(Deprecated.class) != null) {
      writer.println("\t@Deprecated");
    }
    if (interface_decl.getAnnotation(Private.class) == null
        && method.getAnnotation(Private.class) == null) {
      writer.print("\tpublic static ");
    } else {
      writer.print("\tstatic ");
    }
    writer.print(getResultType(method, false));
    StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class);
    String method_name;
    Alternate alt_annotation = method.getAnnotation(Alternate.class);
    method_name =
        alt_annotation == null || alt_annotation.javaAlt()
            ? method.getSimpleName().toString()
            : alt_annotation.value();
    if (strip_annotation != null && mode == Mode.NORMAL) {
      method_name = getPostfixStrippedName(type_map, interface_decl, method);
    }
    writer.print(" " + method_name + "(");
    generateParametersJava(writer, method, typeinfos_instance, false, true, mode);
    writer.println(") {");

    final TypeMirror result_type = Utils.getMethodReturnType(method);
    boolean has_result = !result_type.equals(env.getTypeUtils().getNoType(TypeKind.VOID));

    final Reuse reuse_annotation = method.getAnnotation(Reuse.class);
    if (reuse_annotation != null) {
      writer.print("\t\t");
      if (has_result || method.getAnnotation(GLreturn.class) != null) {
        writer.print("return ");
      }

      writer.print(
          reuse_annotation.value()
              + "."
              + (reuse_annotation.method().length() > 0 ? reuse_annotation.method() : method_name)
              + "(");
      generateParametersJava(writer, method, typeinfos_instance, false, false, mode);
      writer.println(");\n\t}");
      return;
    }

    if (context_specific) {
      type_map.printCapabilitiesInit(writer);
      writer.print(
          "\t\tlong " + Utils.FUNCTION_POINTER_VAR_NAME + " = " + type_map.getCapabilities() + ".");
      writer.println(Utils.getFunctionAddressName(interface_decl, method, true) + ";");
      writer.print("\t\tBufferChecks.checkFunctionAddress(");
      writer.println(Utils.FUNCTION_POINTER_VAR_NAME + ");");
    }
    final Code code_annotation = method.getAnnotation(Code.class);
    if (code_annotation != null && code_annotation.value().length() > 0) {
      writer.println(code_annotation.value());
    }
    printBufferObjectChecks(writer, method, mode, context_specific);
    printParameterChecks(writer, method, typeinfos_instance, mode, generate_error_checks);
    printParameterCaching(writer, interface_decl, method, mode, context_specific);

    if (code_annotation != null && code_annotation.javaBeforeNative().length() > 0) {
      writer.println(code_annotation.javaBeforeNative());
    }
    writer.print("\t\t");

    final PointerWrapper pointer_wrapper_annotation = method.getAnnotation(PointerWrapper.class);
    if (has_result) {
      writer.print(getResultType(method, false) + " " + Utils.RESULT_VAR_NAME);

      if (code_annotation != null && code_annotation.tryBlock()) {
        writer.print(" = " + getDefaultResultValue(method));
        writer.println(";\n\t\ttry {");
        writer.print("\t\t\t" + Utils.RESULT_VAR_NAME);
      }

      writer.print(" = ");
      if (pointer_wrapper_annotation != null) {
        if (pointer_wrapper_annotation.factory().length() > 0) {
          writer.print(pointer_wrapper_annotation.factory() + "(");
        } else {
          writer.print("new " + getResultType(method, false) + "(");
        }
      }
    } else if (method.getAnnotation(GLreturn.class) != null) {
      has_result = true;
      Utils.printGLReturnPre(writer, method, method.getAnnotation(GLreturn.class), type_map);
    }
    writer.print(Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific));
    if (mode == Mode.BUFFEROBJECT) {
      writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
    }
    writer.print("(");
    boolean first_parameter =
        printMethodCallArguments(writer, method, typeinfos_instance, mode, type_map);
    if (context_specific) {
      if (!first_parameter) {
        writer.print(", ");
      }
      writer.print(Utils.FUNCTION_POINTER_VAR_NAME);
    }
    if (has_result && pointer_wrapper_annotation != null) {
      writer.print(")");
      if (pointer_wrapper_annotation.params().length() > 0) {
        writer.print(", " + pointer_wrapper_annotation.params());
      }
    }
    writer.println(");");

    if (code_annotation != null && code_annotation.javaAfterNative().length() > 0) {
      writer.println(code_annotation.javaAfterNative());
    }

    final String tabs = code_annotation != null && code_annotation.tryBlock() ? "\t\t\t" : "\t\t";
    if (generate_error_checks && method.getAnnotation(NoErrorCheck.class) == null) {
      type_map.printErrorCheckMethod(writer, method, tabs);
    }
    // DISABLED: indirect buffer support
    // printNondirectParameterCopies(writer, method, mode);
    if (has_result) {
      if (method.getAnnotation(GLreturn.class) == null) {
        if (ByteBuffer.class.equals(Utils.getJavaType(result_type))) {
          writer.println(
              tabs
                  + "return LWJGLUtil.CHECKS && "
                  + Utils.RESULT_VAR_NAME
                  + " == null ? null : "
                  + Utils.RESULT_VAR_NAME
                  + ".order(ByteOrder.nativeOrder());"); // safeNewBuffer returns a direct
                                                         // ByteBuffer with BIG_ENDIAN order.
        } else {
          writer.println(tabs + "return " + Utils.RESULT_VAR_NAME + ";");
        }
      } else {
        Utils.printGLReturnPost(writer, method, method.getAnnotation(GLreturn.class), type_map);
      }
    }

    if (code_annotation != null && code_annotation.tryBlock()) {
      writer.println("\t\t} finally {");
      writer.println(code_annotation.javaFinally());
      writer.println("\t\t}");
    }
    writer.println("\t}");
  }
Exemplo n.º 21
0
  private static boolean generateParametersJava(
      PrintWriter writer,
      ExecutableElement method,
      Map<VariableElement, TypeInfo> typeinfos_instance,
      boolean native_stub,
      final boolean printTypes,
      Mode mode) {
    boolean first_parameter = true;
    for (VariableElement param : method.getParameters()) {
      if (native_stub
          && (param.getAnnotation(Helper.class) != null
              && !param.getAnnotation(Helper.class).passToNative())) {
        continue;
      }
      final Constant constant_annotation = param.getAnnotation(Constant.class);
      if (constant_annotation != null && constant_annotation.isNative()) {
        continue;
      }
      AnnotationMirror auto_annotation_mirror = Utils.getParameterAutoAnnotation(param);
      boolean hide_auto_parameter =
          mode == Mode.NORMAL && !native_stub && auto_annotation_mirror != null;
      if (hide_auto_parameter) {
        AutoType auto_type_annotation = param.getAnnotation(AutoType.class);
        if (auto_type_annotation != null) {
          VariableElement auto_parameter =
              Utils.findParameter(method, auto_type_annotation.value());
          TypeInfo auto_param_type_info = typeinfos_instance.get(auto_parameter);
          if (auto_param_type_info.getSignedness() == Signedness.BOTH) {
            if (!first_parameter) {
              writer.print(", ");
            }
            first_parameter = false;
            if (printTypes) {
              writer.print("boolean ");
            }
            writer.print(TypeInfo.UNSIGNED_PARAMETER_NAME);
          }
        }
      } else if (param.getAnnotation(Result.class) == null
          && (native_stub
              || ((param.getAnnotation(Constant.class) == null
                      || param.getAnnotation(Constant.class).keepParam())
                  && !Utils.isReturnParameter(method, param)))
          && (mode != Mode.AUTOS || getAutoTypeParameter(method, param) == null)) {
        first_parameter =
            generateParameterJava(
                writer,
                param,
                typeinfos_instance.get(param),
                native_stub,
                printTypes,
                first_parameter,
                mode);
      }
    }
    CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class);
    TypeMirror result_type = Utils.getMethodReturnType(method);
    if ((native_stub && Utils.getNIOBufferType(result_type) != null)
        || Utils.needResultSize(method)) {
      AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class);
      if (auto_size_annotation == null || !auto_size_annotation.isNative()) {
        if (cached_result_annotation == null || !cached_result_annotation.isRange()) {
          if (!first_parameter) {
            writer.print(", ");
          }
          first_parameter = false;
          if (printTypes) {
            writer.print("long ");
          }
          writer.print(Utils.RESULT_SIZE_NAME);
        }
      }
    }
    if (cached_result_annotation != null) {
      if (!first_parameter) {
        writer.print(", ");
      }

      if (mode == Mode.CACHEDRESULT) {
        if (printTypes) {
          writer.print("long ");
        }
        writer.print(Utils.CACHED_BUFFER_LENGTH_NAME + ", ");
      }

      first_parameter = false;
      if (printTypes) {
        writer.print(getResultType(method, native_stub));
      }
      writer.print(" " + Utils.CACHED_BUFFER_NAME);
    }
    return first_parameter;
  }
Exemplo n.º 22
0
  /**
   * Write a companion class for {@code type} that implements {@link ModuleAdapter} to expose its
   * provider methods.
   */
  private void writeModuleAdapter(
      TypeElement type, Map<String, Object> module, List<ExecutableElement> providerMethods)
      throws IOException {
    if (module == null) {
      error(type + " has @Provides methods but no @Module annotation", type);
      return;
    }

    Object[] staticInjections = (Object[]) module.get("staticInjections");
    Object[] entryPoints = (Object[]) module.get("entryPoints");
    Object[] includes = (Object[]) module.get("includes");

    boolean overrides = (Boolean) module.get("overrides");
    boolean complete = (Boolean) module.get("complete");

    String adapterName = CodeGen.adapterName(type, MODULE_ADAPTER_SUFFIX);
    JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(adapterName, type);
    JavaWriter writer = new JavaWriter(sourceFile.openWriter());

    boolean multibindings = checkForMultibindings(providerMethods);
    boolean providerMethodDependencies = checkForDependencies(providerMethods);

    writer.emitEndOfLineComment(ProcessorJavadocs.GENERATED_BY_DAGGER);
    writer.emitPackage(CodeGen.getPackage(type).getQualifiedName().toString());
    writer.emitEmptyLine();
    writer.emitImports(
        getImports(multibindings, !providerMethods.isEmpty(), providerMethodDependencies));

    String typeName = type.getQualifiedName().toString();
    writer.emitEmptyLine();
    writer.emitJavadoc(ProcessorJavadocs.MODULE_TYPE);
    writer.beginType(
        adapterName, "class", PUBLIC | FINAL, JavaWriter.type(ModuleAdapter.class, typeName));

    StringBuilder entryPointsField = new StringBuilder().append("{ ");
    for (Object entryPoint : entryPoints) {
      TypeMirror typeMirror = (TypeMirror) entryPoint;
      String key = GeneratorKeys.rawMembersKey(typeMirror);
      entryPointsField.append(JavaWriter.stringLiteral(key)).append(", ");
    }
    entryPointsField.append("}");
    writer.emitField(
        "String[]", "ENTRY_POINTS", PRIVATE | STATIC | FINAL, entryPointsField.toString());

    StringBuilder staticInjectionsField = new StringBuilder().append("{ ");
    for (Object staticInjection : staticInjections) {
      TypeMirror typeMirror = (TypeMirror) staticInjection;
      staticInjectionsField.append(CodeGen.typeToString(typeMirror)).append(".class, ");
    }
    staticInjectionsField.append("}");
    writer.emitField(
        "Class<?>[]",
        "STATIC_INJECTIONS",
        PRIVATE | STATIC | FINAL,
        staticInjectionsField.toString());

    StringBuilder includesField = new StringBuilder().append("{ ");
    for (Object include : includes) {
      if (!(include instanceof TypeMirror)) {
        // TODO(tbroyer): pass annotation information
        processingEnv
            .getMessager()
            .printMessage(
                Diagnostic.Kind.WARNING,
                "Unexpected value: " + include + " in includes of " + type,
                type);
        continue;
      }
      TypeMirror typeMirror = (TypeMirror) include;
      includesField.append(CodeGen.typeToString(typeMirror)).append(".class, ");
    }
    includesField.append("}");
    writer.emitField("Class<?>[]", "INCLUDES", PRIVATE | STATIC | FINAL, includesField.toString());

    writer.emitEmptyLine();
    writer.beginMethod(null, adapterName, PUBLIC);
    writer.emitStatement(
        "super(ENTRY_POINTS, STATIC_INJECTIONS, %s /*overrides*/, " + "INCLUDES, %s /*complete*/)",
        overrides, complete);
    writer.endMethod();

    ExecutableElement noArgsConstructor = CodeGen.getNoArgsConstructor(type);
    if (noArgsConstructor != null && CodeGen.isCallableConstructor(noArgsConstructor)) {
      writer.emitEmptyLine();
      writer.emitAnnotation(Override.class);
      writer.beginMethod(typeName, "newModule", PROTECTED);
      writer.emitStatement("return new %s()", typeName);
      writer.endMethod();
    }
    // caches
    Map<ExecutableElement, String> methodToClassName =
        new LinkedHashMap<ExecutableElement, String>();
    Map<String, AtomicInteger> methodNameToNextId = new LinkedHashMap<String, AtomicInteger>();

    if (!providerMethods.isEmpty()) {
      writer.emitEmptyLine();
      writer.emitJavadoc(ProcessorJavadocs.GET_DEPENDENCIES_METHOD);
      writer.emitAnnotation(Override.class);
      writer.beginMethod("void", "getBindings", PUBLIC, BINDINGS_MAP, "map");

      for (ExecutableElement providerMethod : providerMethods) {
        Provides provides = providerMethod.getAnnotation(Provides.class);
        switch (provides.type()) {
          case UNIQUE:
            {
              String key = GeneratorKeys.get(providerMethod);
              writer.emitStatement(
                  "map.put(%s, new %s(module))",
                  JavaWriter.stringLiteral(key),
                  bindingClassName(providerMethod, methodToClassName, methodNameToNextId));
              break;
            }
          case SET:
            {
              String key = GeneratorKeys.getElementKey(providerMethod);
              writer.emitStatement(
                  "SetBinding.add(map, %s, new %s(module))",
                  JavaWriter.stringLiteral(key),
                  bindingClassName(providerMethod, methodToClassName, methodNameToNextId));
              break;
            }
          default:
            throw new AssertionError("Unknown @Provides type " + provides.type());
        }
      }
      writer.endMethod();
    }

    for (ExecutableElement providerMethod : providerMethods) {
      writeProvidesAdapter(writer, providerMethod, methodToClassName, methodNameToNextId);
    }

    writer.endType();
    writer.close();
  }