Java Code Examples for com.sun.codemodel.JVar

The following examples show how to use com.sun.codemodel.JVar. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   Source File: CodeGenMemberInjector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generated code for a class may have several class members, they
 * are initialized by invoking this method when the instance created.
 *
 * @param cg       the class generator
 * @param instance the class instance created by the compiler
 * @param context  the fragment context
 */
public static void injectMembers(ClassGenerator<?> cg, Object instance, FragmentContext context) {
  Map<Integer, Object> cachedInstances = new HashMap<>();
  for (Map.Entry<Pair<Integer, JVar>, Function<DrillBuf, ? extends ValueHolder>> setter : cg.getConstantVars().entrySet()) {
    try {
      JVar var = setter.getKey().getValue();
      Integer depth = setter.getKey().getKey();
      Object varInstance = getFieldInstance(instance, depth, cachedInstances);
      Field field = varInstance.getClass().getDeclaredField(var.name());
      field.setAccessible(true);
      field.set(varInstance, setter.getValue().apply(context.getManagedBuffer()));
    } catch (ReflectiveOperationException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example 2
Source Project: Bats   Source File: EvaluationVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer visitFunctionHolderExpression(FunctionHolderExpression holderExpr,
    ClassGenerator<?> generator) throws RuntimeException {

  AbstractFuncHolder holder = (AbstractFuncHolder) holderExpr.getHolder();

  JVar[] workspaceVars = holder.renderStart(generator, null, holderExpr.getFieldReference());

  if (holder.isNested()) {
    generator.getMappingSet().enterChild();
  }

  HoldingContainer[] args = new HoldingContainer[holderExpr.args.size()];
  for (int i = 0; i < holderExpr.args.size(); i++) {
    args[i] = holderExpr.args.get(i).accept(this, generator);
  }

  holder.renderMiddle(generator, args, workspaceVars);

  if (holder.isNested()) {
    generator.getMappingSet().exitChild();
  }

  return holder.renderEnd(generator, args, workspaceVars, holderExpr.getFieldReference());
}
 
Example 3
static
private JInvocation createSuperInvocation(JDefinedClass clazz, JMethod method){
	JInvocation invocation;

	if(method.type() != null){
		invocation = JExpr._super().invoke(method.name());
	} else

	{
		invocation = JExpr.invoke("super");
	}

	List<JVar> parameters = method.params();
	for(JVar parameter : parameters){
		invocation.arg(parameter);
	}

	return invocation;
}
 
Example 4
Source Project: Bats   Source File: ClassGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * declare a constant field for the class.
 * argument {@code function} holds the constant value which
 * returns a value holder must be set to the class field when the class instance created.
 * the class field innerClassField will be created if innerClassGenerator exists.
 *
 * @param prefix the prefix name of class field
 * @param t the type of class field
 * @param init init expression
 * @param function the function holds the constant value
 * @return the depth of nested class, class field
 */
public Pair<Integer, JVar> declareClassConstField(String prefix, JType t, JExpression init,
                                                  Function<DrillBuf, ? extends ValueHolder> function) {
  JVar var;
  int depth = 1;
  if (innerClassGenerator != null) {
    Pair<Integer, JVar> nested = innerClassGenerator.declareClassConstField(prefix, t, init, function);
    depth = nested.getKey() + 1;
    var = nested.getValue();
  } else {
    var = clazz.field(JMod.NONE, t, prefix + index++, init);
  }
  Pair<Integer, JVar> depthVar = Pair.of(depth, var);
  constantVars.put(depthVar, function);
  return depthVar;
}
 
Example 5
Source Project: Bats   Source File: ClassGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds local variable declaration based on given name and type.
 *
 * @param t major type
 * @param name variable name
 * @param includeNewInstance whether to create new instance
 * @return holder instance
 */
public HoldingContainer declare(MajorType t, String name, boolean includeNewInstance) {
  JType holderType = getHolderType(t);
  JVar var;
  if (includeNewInstance) {
    var = getEvalBlock().decl(holderType, name + index, JExpr._new(holderType));
  } else {
    var = getEvalBlock().decl(holderType, name + index);
  }
  JFieldRef outputSet = null;
  if (t.getMode() == DataMode.OPTIONAL) {
    outputSet = var.ref("isSet");
  }
  index++;
  return new HoldingContainer(t, var, var.ref("value"), outputSet);
}
 
Example 6
Source Project: Bats   Source File: DrillComplexWriterAggFuncHolder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JVar[] renderStart(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables, FieldReference fieldReference) {
  if (!classGenerator.getMappingSet().isHashAggMapping()) {  //Declare workspace vars for non-hash-aggregation.
    JInvocation container = classGenerator.getMappingSet().getOutgoing().invoke("getOutgoingContainer");

    complexWriter = classGenerator.declareClassField("complexWriter", classGenerator.getModel()._ref(ComplexWriter.class));
    writerIdx = classGenerator.declareClassField("writerIdx", classGenerator.getModel()._ref(int.class));
    lastWriterIdx = classGenerator.declareClassField("lastWriterIdx", classGenerator.getModel()._ref(int.class));
    //Default name is "col", if not passed in a reference name for the output vector.
    String refName = fieldReference == null ? "col" : fieldReference.getRootSegment().getPath();
    JClass cwClass = classGenerator.getModel().ref(VectorAccessibleComplexWriter.class);
    classGenerator.getSetupBlock().assign(complexWriter, cwClass.staticInvoke("getWriter").arg(refName).arg(container));
    classGenerator.getSetupBlock().assign(writerIdx, JExpr.lit(0));
    classGenerator.getSetupBlock().assign(lastWriterIdx, JExpr.lit(-1));

    JVar[] workspaceJVars = declareWorkspaceVariables(classGenerator);
    generateBody(classGenerator, ClassGenerator.BlockType.SETUP, setup(), null, workspaceJVars, true);
    return workspaceJVars;
  } else {
    return super.renderStart(classGenerator, inputVariables, fieldReference);
  }
}
 
Example 7
Source Project: Bats   Source File: DrillAggFuncHolder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer renderEnd(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables,
                                  JVar[] workspaceJVars, FieldReference fieldReference) {
  HoldingContainer out = null;
  JVar internalOutput = null;
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    out = classGenerator.declare(getReturnType(), false);
  }
  JBlock sub = new JBlock();
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    internalOutput = sub.decl(JMod.FINAL, classGenerator.getHolderType(getReturnType()), getReturnValue().getName(), JExpr._new(classGenerator.getHolderType(getReturnType())));
  }
  classGenerator.getEvalBlock().add(sub);
  addProtectedBlock(classGenerator, sub, output(), null, workspaceJVars, false);
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    sub.assign(out.getHolder(), internalOutput);
  }
  //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block.
  if (!classGenerator.getMappingSet().isHashAggMapping()) {
    generateBody(classGenerator, BlockType.RESET, reset(), null, workspaceJVars, false);
  }
  generateBody(classGenerator, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false);

  return out;
}
 
Example 8
Source Project: apicurio-studio   Source File: JaxRsEnumRule.java    License: Apache License 2.0 6 votes vote down vote up
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
    JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);

    JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
    JVar valueParam = fromValue.param(backingType, "value");

    JBlock body = fromValue.body();
    JVar constant = body.decl(_enum, "constant");
    constant.init(quickLookupMap.invoke("get").arg(valueParam));

    JConditional _if = body._if(constant.eq(JExpr._null()));

    JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
    JExpression expr = valueParam;

    // if string no need to add ""
    if(!isString(backingType)){
        expr = expr.plus(JExpr.lit(""));
    }
    
    illegalArgumentException.arg(expr);
    _if._then()._throw(illegalArgumentException);
    _if._else()._return(constant);

    ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue);
}
 
Example 9
Source Project: Bats   Source File: DrillSimpleFuncHolder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer renderEnd(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables,
                                  JVar[] workspaceJVars, FieldReference fieldReference) {
  //If the function's annotation specifies a parameter has to be constant expression, but the HoldingContainer
  //for the argument is not, then raise exception.
  for (int i = 0; i < inputVariables.length; i++) {
    if (getParameters()[i].isConstant() && !inputVariables[i].isConstant()) {
      throw new DrillRuntimeException(String.format("The argument '%s' of Function '%s' has to be constant!", getParameters()[i].getName(), this.getRegisteredNames()[0]));
    }
  }
  generateBody(classGenerator, BlockType.SETUP, setupBody(), inputVariables, workspaceJVars, true);
  HoldingContainer c = generateEvalBody(classGenerator, inputVariables, evalBody(), workspaceJVars, fieldReference);
  generateBody(classGenerator, BlockType.RESET, resetBody(), null, workspaceJVars, false);
  generateBody(classGenerator, BlockType.CLEANUP, cleanupBody(), null, workspaceJVars, false);
  return c;
}
 
Example 10
public EqualsArguments cast(String suffix, JBlock block,
		JType jaxbElementType, boolean suppressWarnings) {
	final JVar castedLeftValue = block.decl(JMod.FINAL, jaxbElementType,
			leftValue().name() + suffix,
			JExpr.cast(jaxbElementType, leftValue()));
	if (suppressWarnings) {
		castedLeftValue.annotate(SuppressWarnings.class).param("value",
				"unchecked");
	}
	final JVar castedRightValue = block.decl(JMod.FINAL, jaxbElementType,
			rightValue().name() + suffix,
			JExpr.cast(jaxbElementType, rightValue()));
	if (suppressWarnings) {
		castedRightValue.annotate(SuppressWarnings.class).param("value",
				"unchecked");
	}
	return new EqualsArguments(getCodeModel(), castedLeftValue, JExpr.TRUE,
			castedRightValue, JExpr.TRUE);
}
 
Example 11
Source Project: jaxb-visitor   Source File: CreateTraversingVisitorClass.java    License: Apache License 2.0 6 votes vote down vote up
private void generateForDirectClass(JDefinedClass traversingVisitor, JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    // add method impl to traversing visitor
    JMethod travViz;
    String visitMethodName = visitMethodNamer.apply(implClass.name());
    travViz = traversingVisitor.method(JMod.PUBLIC, returnType, visitMethodName);
    travViz._throws(exceptionType);
    JVar beanVar = travViz.param(implClass, "aBean");
    travViz.annotate(Override.class);
    JBlock travVizBloc = travViz.body();

    addTraverseBlock(travViz, beanVar, true);

    JVar retVal = travVizBloc.decl(returnType, "returnVal");

    travVizBloc.assign(retVal, JExpr.invoke(JExpr.invoke("getVisitor"), visitMethodName).arg(beanVar));

    travVizBloc._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "visited").arg(beanVar);

    addTraverseBlock(travViz, beanVar, false);

    travVizBloc._return(retVal);
}
 
Example 12
private void processComplexType(JVar fieldSchemaVar, String name, Schema schema, Schema readerFieldSchema,
    JBlock methodBody, FieldAction action, BiConsumer<JBlock, JExpression> putExpressionIntoParent,
    Supplier<JExpression> reuseSupplier) {
  switch (schema.getType()) {
    case RECORD:
      processRecord(fieldSchemaVar, schema.getName(), schema, readerFieldSchema, methodBody, action,
          putExpressionIntoParent, reuseSupplier);
      break;
    case ARRAY:
      processArray(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    case MAP:
      processMap(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    case UNION:
      processUnion(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    default:
      throw new FastDeserializerGeneratorException("Incorrect complex type: " + action.getType());
  }
}
 
Example 13
Source Project: dremio-oss   Source File: AggrFunctionHolder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer renderEnd(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, JVar[]  workspaceJVars) {
  HoldingContainer out = g.declare(resolvedOutput, false);
  JBlock sub = new JBlock();
  g.getEvalBlock().add(sub);
  JVar internalOutput = sub.decl(JMod.FINAL, CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel()), getReturnName(), JExpr._new(CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel())));
  addProtectedBlock(g, sub, output(), null, workspaceJVars, false);
  sub.assign(out.getHolder(), internalOutput);
      //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block.
      if (!g.getMappingSet().isHashAggMapping()) {
        generateBody(g, BlockType.RESET, reset(), null, workspaceJVars, false);
      }
     generateBody(g, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false);

  return out;
}
 
Example 14
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 6 votes vote down vote up
private JExpression getUnmodifiableWrappedExpression(JCodeModel codeModel, JVar param) {
    if (param.type().erasure().equals(codeModel.ref(Collection.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableCollection").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(List.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableList").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(Map.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableMap").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(Set.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSet").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSortedMap").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSortedSet").arg(param);
    }
    return param;
}
 
Example 15
Source Project: avro-fastserde   Source File: FastDeserializerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private JVar declareSchemaVar(Schema valueSchema, String variableName, JInvocation getValueType) {
    if (!useGenericTypes) {
        return null;
    }
    if (SchemaAssistant.isComplexType(valueSchema) || Schema.Type.ENUM.equals(valueSchema.getType())) {
        int schemaId = getSchemaId(valueSchema);
        if (schemaVarMap.get(schemaId) != null) {
            return schemaVarMap.get(schemaId);
        } else {
            JVar schemaVar = schemaMapMethod.body().decl(codeModel.ref(Schema.class),
                    getVariableName(StringUtils.uncapitalize(variableName)), getValueType);
            registerSchema(valueSchema, schemaId, schemaVar);
            schemaVarMap.put(schemaId, schemaVar);
            return schemaVar;
        }
    } else {
        return null;
    }
}
 
Example 16
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 6 votes vote down vote up
private JExpression getEmptyCollectionExpression(JCodeModel codeModel, JVar param) {
    if (param.type().erasure().equals(codeModel.ref(Collection.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyList");
    } else if (param.type().erasure().equals(codeModel.ref(List.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyList");
    } else if (param.type().erasure().equals(codeModel.ref(Map.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyMap");
    } else if (param.type().erasure().equals(codeModel.ref(Set.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptySet");
    } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) {
        return JExpr._new(codeModel.ref(TreeMap.class));
    } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) {
        return JExpr._new(codeModel.ref(TreeSet.class));
    }
    return param;
}
 
Example 17
Source Project: avro-fastserde   Source File: FastSerializerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void processRecord(final Schema recordSchema, JExpression recordExpr, final JBlock containerBody) {
    if (methodAlreadyDefined(recordSchema)) {
        containerBody.invoke(getMethod(recordSchema)).arg(recordExpr).arg(JExpr.direct(ENCODER));
        return;
    }
    JMethod method = createMethod(recordSchema);
    containerBody.invoke(getMethod(recordSchema)).arg(recordExpr).arg(JExpr.direct(ENCODER));

    JBlock body = method.body();
    recordExpr = method.listParams()[0];

    for (Schema.Field field : recordSchema.getFields()) {
        Schema fieldSchema = field.schema();
        if (SchemaAssistant.isComplexType(fieldSchema)) {
            JClass fieldClass = schemaAssistant.classFromSchema(fieldSchema);
            JVar containerVar = declareValueVar(field.name(), fieldSchema, body);
            JExpression valueExpression = JExpr.invoke(recordExpr, "get").arg(JExpr.lit(field.pos()));
            containerVar.init(JExpr.cast(fieldClass, valueExpression));

            processComplexType(fieldSchema, containerVar, body);
        } else {
            processSimpleType(fieldSchema, recordExpr.invoke("get").arg(JExpr.lit(field.pos())), body);
        }

    }
}
 
Example 18
Source Project: jaxb2-rich-contract-plugin   Source File: PluginContext.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
JBlock catchCloneNotSupported(final JBlock body, final JClass elementType) {
	final Class<? extends Cloneable> elementRuntimeClass;
	try {
		elementRuntimeClass = (Class<? extends Cloneable>) Class.forName(elementType.binaryName());
	} catch (final ClassNotFoundException e) {
		return body;
	}
	if (!cloneThrows(elementRuntimeClass)) {
		return body;
	} else {
		final JTryBlock tryBlock = body._try();
		final JCatchBlock catchBlock = tryBlock._catch(this.codeModel.ref(CloneNotSupportedException.class));
		final JVar exceptionVar = catchBlock.param("e");
		catchBlock.body()._throw(JExpr._new(this.codeModel.ref(RuntimeException.class)).arg(exceptionVar));
		return tryBlock.body();
	}
}
 
Example 19
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 6 votes vote down vote up
private JMethod addWithIfNotNullMethod(JDefinedClass builderClass, JFieldVar field, JMethod unconditionalWithMethod, boolean inherit) {
    if (field.type().isPrimitive())
        return null;
    String fieldName = StringUtils.capitalize(field.name());
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "with" + fieldName + "IfNotNull");
    JVar param = generateMethodParameter(method, field);
    JBlock block = method.body();
    if (inherit) {
        generateSuperCall(method);
        method.body()._return(JExpr._this());
    } else {
        JConditional conditional = block._if(param.eq(JExpr._null()));
        conditional._then()._return(JExpr._this());
        conditional._else()._return(JExpr.invoke(unconditionalWithMethod).arg(param));
    }
    return method;
}
 
Example 20
Source Project: springmvc-raml-plugin   Source File: PojoBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, JVar> getSuperParametersToAdd(JClass pojo) {
	Map<String, JVar> tFields = new LinkedHashMap<>();
	JClass parent = pojo._extends();
	if (!parent.name().equals(Object.class.getSimpleName())) {
		parent = CodeModelHelper.findFirstClassBySimpleName(this.pojoModel, parent.name());
		if (parent instanceof JDefinedClass) {
			JDefinedClass jParent = (JDefinedClass) parent;
			JMethod constructor = null;
			Iterator<JMethod> constructors = jParent.constructors();
			while (constructors.hasNext()) {
				JMethod targetConstructor = constructors.next();
				if (constructor == null || constructor.params().size() < targetConstructor.params().size()) {
					constructor = targetConstructor;
				}
			}
			for (JVar var : constructor.params()) {
				tFields.put(var.name(), var);
			}
		}
	}
	return tFields;
}
 
Example 21
Source Project: springmvc-raml-plugin   Source File: PojoBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void withEquals() {
	JMethod equals = this.pojo.method(JMod.PUBLIC, boolean.class, "equals");
	JVar otherObject = equals.param(Object.class, "other");

	Class<?> equalsBuilderClass = org.apache.commons.lang3.builder.EqualsBuilder.class;
	if (!Config.getPojoConfig().isUseCommonsLang3()) {
		equalsBuilderClass = org.apache.commons.lang.builder.EqualsBuilder.class;
	}

	JBlock body = equals.body();

	body._if(otherObject.eq(JExpr._null()))._then()._return(JExpr.FALSE);
	body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE);
	body._if(JExpr._this().invoke("getClass").ne(otherObject.invoke("getClass")))._then()._return(JExpr.FALSE);

	JVar otherObjectVar = body.decl(this.pojo, "otherObject").init(JExpr.cast(this.pojo, otherObject));

	JClass equalsBuilderRef = this.pojo.owner().ref(equalsBuilderClass);

	JInvocation equalsBuilderInvocation = appendFieldsToEquals(getNonTransientAndNonStaticFields(), otherObjectVar, equalsBuilderRef);

	body._return(equalsBuilderInvocation.invoke("isEquals"));
}
 
Example 22
Source Project: dremio-oss   Source File: ClassGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) {
  final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId);

  final Class<?> valueVectorClass = fieldId.getIntermediateClass();
  final JClass vvClass = model.ref(valueVectorClass);
  final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass;

  final JVar vv = declareClassField("vv", retClass);
  final JBlock b = getSetupBlock();
  int[] fieldIndices = fieldId.getFieldIds();
  JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple")
      .arg(batchName)
      .arg(vvClass.dotclass());

  for(int i = 0; i < fieldIndices.length; i++){
    invoke.arg(JExpr.lit(fieldIndices[i]));
  }

  // we have to cast here since Janino doesn't handle generic inference well.
  JExpression casted = JExpr.cast(retClass, invoke);
  b.assign(vv, casted);
  vvDeclaration.put(setup, vv);

  return vv;
}
 
Example 23
Source Project: Bats   Source File: CopyUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void generateCopies(ClassGenerator<?> g, VectorAccessible batch, boolean hyper){
  // we have parallel ids for each value vector so we don't actually have to deal with managing the ids at all.
  int fieldId = 0;

  JExpression inIndex = JExpr.direct("inIndex");
  JExpression outIndex = JExpr.direct("outIndex");
  for(VectorWrapper<?> vv : batch) {
    String copyMethod;
    if (!Types.isFixedWidthType(vv.getField().getType()) || Types.isRepeated(vv.getField().getType()) || Types.isComplex(vv.getField().getType())) {
      copyMethod = "copyFromSafe";
    } else {
      copyMethod = "copyFrom";
    }
    g.rotateBlock();
    JVar inVV = g.declareVectorValueSetupAndMember("incoming", new TypedFieldId(vv.getField().getType(), vv.isHyper(), fieldId));
    JVar outVV = g.declareVectorValueSetupAndMember("outgoing", new TypedFieldId(vv.getField().getType(), false, fieldId));

    if(hyper){

      g.getEvalBlock().add(
              outVV
                      .invoke(copyMethod)
                      .arg(
                              inIndex.band(JExpr.lit((int) Character.MAX_VALUE)))
                      .arg(outIndex)
                      .arg(
                              inVV.component(inIndex.shrz(JExpr.lit(16)))
                      )
      );
    }else{
      g.getEvalBlock().add(outVV.invoke(copyMethod).arg(inIndex).arg(outIndex).arg(inVV));
    }

    g.rotateBlock();
    fieldId++;
  }
}
 
Example 24
public HashCodeArguments element(JBlock subBlock, JType elementType) {
	final JVar elementValue = subBlock.decl(JMod.FINAL, elementType,
			value().name() + "Element", value().invoke("next"));
	final boolean isElementAlwaysSet = elementType.isPrimitive();
	final JExpression elementHasSetValue = isElementAlwaysSet ? JExpr.TRUE
			: elementValue.ne(JExpr._null());
	return spawn(elementValue, elementHasSetValue);

}
 
Example 25
Source Project: jaxb2-rich-contract-plugin   Source File: MetaPlugin.java    License: MIT License 5 votes vote down vote up
private void generateAccessors(final FieldOutline fieldOutline, final String propertyName, final JType returnType, final JDefinedClass declaringClass, final F1<JExpression, JVar> getMaker, final F3<JExpression, JBlock, JVar, JVar> setMaker) {
	final String constantName = getConstantName(fieldOutline);
	final JMethod getMethod = declaringClass.method(JMod.PUBLIC, returnType, "get");
	getMethod.annotate(Override.class);
	final JVar instanceParam = getMethod.param(JMod.FINAL, fieldOutline.parent().implClass, "_instance_");
	getMethod.body()._return(JOp.cond(instanceParam.eq(JExpr._null()), JExpr._null(), getMaker.f(instanceParam)));
	final JMethod setMethod = declaringClass.method(JMod.PUBLIC, void.class, "set");
	setMethod.annotate(Override.class);
	final JVar setInstanceParam = setMethod.param(JMod.FINAL, fieldOutline.parent().implClass, "_instance_");
	final JVar valueParam = setMethod.param(JMod.FINAL, returnType, "_value_");
	if (constantName == null) {
		final JConditional ifNotNull = setMethod.body()._if(setInstanceParam.ne(JExpr._null()));
		setMaker.f(ifNotNull._then(), setInstanceParam, valueParam);
	}
}
 
Example 26
Source Project: jaxb2-rich-contract-plugin   Source File: BuilderGenerator.java    License: MIT License 5 votes vote down vote up
void generateArrayProperty(final JBlock initBody, final JVar productParam, final PropertyOutline fieldOutline, final JType elementType, final JType builderType) {
	final String fieldName = fieldOutline.getFieldName();
	final String propertyName = fieldOutline.getBaseName();
	final JType fieldType = fieldOutline.getRawType();
	final JMethod withVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, builderType, PluginContext.WITH_METHOD_PREFIX + propertyName);
	final JVar withVarargsParam = withVarargsMethod.varParam(elementType, fieldName);
	if (this.implement) {
		final JFieldVar builderField = this.builderClass.raw.field(JMod.PRIVATE, fieldType, fieldName, JExpr._null());
		withVarargsMethod.body().assign(JExpr._this().ref(builderField), withVarargsParam);
		withVarargsMethod.body()._return(JExpr._this());
		initBody.assign(productParam.ref(fieldName), JExpr._this().ref(builderField));
	}
}
 
Example 27
Source Project: jaxb2-basics   Source File: SettersPlugin.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void generateSetter(FieldOutline fieldOutline,
		JDefinedClass theClass, JMethod setter, JVar value) {

	final JFieldVar field = theClass.fields().get(
			fieldOutline.getPropertyInfo().getName(false));

	if (field != null) {
		setter.body().assign(JExpr._this().ref(field), value);
	} else {
		// Fallback to the accessor
		Mode.accessor.generateSetter(fieldOutline, theClass,
				setter, value);
	}
}
 
Example 28
private JMethod generateObject$hashCode(final JDefinedClass theClass) {
	final JMethod object$hashCode = theClass.method(JMod.PUBLIC,
			theClass.owner().INT, "hashCode");
	object$hashCode.annotate(Override.class);
	{
		final JBlock body = object$hashCode.body();
		final JVar hashCodeStrategy = body.decl(JMod.FINAL, theClass
				.owner().ref(HashCodeStrategy2.class), "strategy",
				createHashCodeStrategy(theClass.owner()));
		body._return(JExpr._this().invoke("hashCode").arg(JExpr._null())
				.arg(hashCodeStrategy));
	}
	return object$hashCode;
}
 
Example 29
protected JMethod createSetter() {
	final MethodWriter writer = outline.createMethodWriter();

	final JMethod setter = writer.declareMethod(codeModel.VOID,
			getSetterName());
	final JVar var = writer.addParameter(exposedType, prop.getName(false));
	final JBlock block = setter.body();
	block.assign(field, var);
	block.assign(nameField, codeModel.ref(JAXBElementUtils.class)
			.staticInvoke("getName").arg(var));
	block.assign(valueField, codeModel.ref(JAXBElementUtils.class)
			.staticInvoke("getValue").arg(var));
	return setter;
}
 
Example 30
static
private JInvocation createReportInvocation(JDefinedClass clazz, String operation, List<JVar> parameters, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JClass stringBuilderClazz = codeModel.ref(StringBuilder.class);

	return createReportInvocation(clazz, JExpr._new(stringBuilderClazz).arg(JExpr.lit(256)), operation, parameters, type);
}