Java Code Examples for org.eclipse.xtext.common.types.JvmOperation#setVisibility()

The following examples show how to use org.eclipse.xtext.common.types.JvmOperation#setVisibility() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JvmTypesBuilder.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a getter method for the given property name and the field name.
 * 
 * Example: <code>
 * public String getPropertyName() {
 *   return this.fieldName;
 * }
 * </code>
 * 
 * @return a getter method for a JavaBeans property, <code>null</code> if sourceElement or name are <code>null</code>.
 */
/* @Nullable */
public JvmOperation toGetter(/* @Nullable */ final EObject sourceElement, /* @Nullable */ final String propertyName, /* @Nullable */ final String fieldName, /* @Nullable */ JvmTypeReference typeRef) {
	if(sourceElement == null || propertyName == null || fieldName == null) 
		return null;
	JvmOperation result = typesFactory.createJvmOperation();
	result.setVisibility(JvmVisibility.PUBLIC);
	String prefix = (isPrimitiveBoolean(typeRef) ? "is" : "get");
	result.setSimpleName(prefix + Strings.toFirstUpper(propertyName));
	result.setReturnType(cloneWithProxies(typeRef));
	setBody(result, new Procedures.Procedure1<ITreeAppendable>() {
		@Override
		public void apply(/* @Nullable */ ITreeAppendable p) {
			if(p != null) {
				p = p.trace(sourceElement);
				p.append("return this.");
				p.append(javaKeywords.isJavaKeyword(fieldName) ? fieldName+"_" : fieldName);
				p.append(";");
			}
		}
	});
	return associate(sourceElement, result);
}
 
Example 2
Source File: JvmTypesBuilder.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a setter method for the given properties name with the standard implementation assigning the passed
 * parameter to a similarly named field.
 * 
 * Example: <code>
 * public void setFoo(String foo) {
 *   this.foo = foo;
 * }
 * </code>
 *
 * @return a setter method for a JavaBeans property with the given name, <code>null</code> if sourceElement or name are <code>null</code>.
 */
/* @Nullable */ 
public JvmOperation toSetter(/* @Nullable */ final EObject sourceElement, /* @Nullable */ final String propertyName, /* @Nullable */ final String fieldName, /* @Nullable */ JvmTypeReference typeRef) {
	if(sourceElement == null || propertyName == null || fieldName == null) 
		return null;
	JvmOperation result = typesFactory.createJvmOperation();
	result.setVisibility(JvmVisibility.PUBLIC);
	result.setReturnType(references.getTypeForName(Void.TYPE,sourceElement));
	result.setSimpleName("set" + Strings.toFirstUpper(propertyName));
	result.getParameters().add(toParameter(sourceElement, propertyName, typeRef));
	setBody(result, new Procedures.Procedure1<ITreeAppendable>() {
		@Override
		public void apply(/* @Nullable */ ITreeAppendable p) {
			if(p != null) {
				p = p.trace(sourceElement);
				p.append("this.");
				p.append(javaKeywords.isJavaKeyword(fieldName) ? fieldName+"_" : fieldName);
				p.append(" = ");
				p.append(javaKeywords.isJavaKeyword(propertyName) ? propertyName+"_" : propertyName);
				p.append(";");
			}
		}
	});
	return associate(sourceElement, result);
}
 
Example 3
Source File: SARLJvmModelInferrer.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
protected JvmOperation deriveGenericDispatchOperationSignature(
		Iterable<JvmOperation> localOperations, JvmGenericType target) {
	final JvmOperation dispatcher = super.deriveGenericDispatchOperationSignature(localOperations, target);
	//
	// Fixing the behavior for determining the visibility of the dispatcher since
	// it does not fit the SARL requirements.
	//
	JvmVisibility higherVisibility = JvmVisibility.PRIVATE;
	for (final JvmOperation jvmOperation : localOperations) {
		final Iterable<XtendFunction> xtendFunctions = Iterables.filter(
				this.sarlAssociations.getSourceElements(jvmOperation), XtendFunction.class);
		for (final XtendFunction func : xtendFunctions) {
			JvmVisibility visibility = func.getVisibility();
			if (visibility == null) {
				visibility = this.defaultVisibilityProvider.getDefaultJvmVisibility(func);
			}
			if (this.visibilityComparator.compare(visibility, higherVisibility) > 0) {
				higherVisibility = visibility;
			}
		}
	}
	dispatcher.setVisibility(higherVisibility);

	return dispatcher;
}
 
Example 4
Source File: JvmInterfaceDeclarationImpl.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public MutableMethodDeclaration addMethod(final String name, final Procedure1<MutableMethodDeclaration> initializer) {
  this.checkMutable();
  ConditionUtils.checkJavaIdentifier(name, "name");
  Preconditions.checkArgument((initializer != null), "initializer cannot be null");
  final JvmOperation newMethod = TypesFactory.eINSTANCE.createJvmOperation();
  newMethod.setVisibility(JvmVisibility.PUBLIC);
  newMethod.setSimpleName(name);
  newMethod.setReturnType(this.getCompilationUnit().toJvmTypeReference(this.getCompilationUnit().getTypeReferenceProvider().getPrimitiveVoid()));
  newMethod.setAbstract(true);
  this.getDelegate().getMembers().add(newMethod);
  MemberDeclaration _memberDeclaration = this.getCompilationUnit().toMemberDeclaration(newMethod);
  final MutableMethodDeclaration mutableMethodDeclaration = ((MutableMethodDeclaration) _memberDeclaration);
  initializer.apply(mutableMethodDeclaration);
  return mutableMethodDeclaration;
}
 
Example 5
Source File: JvmModelCompleter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void completeJvmEnumerationType(JvmEnumerationType element) {
	if (element.getSuperTypes().isEmpty()) {
		JvmTypeReference objectType = references.getTypeForName(Enum.class, element,
				references.createTypeRef(element));
		if (objectType != null)
			element.getSuperTypes().add(objectType);
	}
	addAnnotations(element);
	EObject primarySourceElement = associations.getPrimarySourceElement(element);
	JvmOperation values = typesFactory.createJvmOperation();
	values.setVisibility(JvmVisibility.PUBLIC);
	values.setStatic(true);
	values.setSimpleName("values");
	values.setReturnType(references.createArrayType(references.createTypeRef(element)));
	typeExtensions.setSynthetic(values, true);
	if (primarySourceElement != null) {
		associator.associate(primarySourceElement, values);
	}
	element.getMembers().add(values);
	
	JvmOperation valueOf = typesFactory.createJvmOperation();
	valueOf.setVisibility(JvmVisibility.PUBLIC);
	valueOf.setStatic(true);
	valueOf.setSimpleName("valueOf");
	valueOf.setReturnType(references.createTypeRef(element));
	JvmFormalParameter param = typesFactory.createJvmFormalParameter();
	param.setName("name");
	param.setParameterType(references.getTypeForName(String.class, element));
	valueOf.getParameters().add(param);
	typeExtensions.setSynthetic(valueOf, true);
	if (primarySourceElement != null) {
		associator.associate(primarySourceElement, valueOf);
	}
	element.getMembers().add(valueOf);
}
 
Example 6
Source File: ResolvedOperationTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testVarArgsMismatch_01() {
  final IResolvedOperation operation = this.toOperation("(null as testdata.MethodOverrides4).withVarArgs(null)");
  JvmOperation _declaration = operation.getDeclaration();
  _declaration.setVisibility(JvmVisibility.PROTECTED);
  final Consumer<JvmOperation> _function = (JvmOperation it) -> {
    it.setVisibility(JvmVisibility.PUBLIC);
  };
  operation.getOverriddenAndImplementedMethodCandidates().forEach(_function);
  this.withDetails(this.candidatesAndOverrides(this.has(operation, 1), 1), IOverrideCheckResult.OverrideCheckDetails.REDUCED_VISIBILITY, IOverrideCheckResult.OverrideCheckDetails.VAR_ARG_MISMATCH);
}
 
Example 7
Source File: ResolvedOperationTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testVarArgsMismatch_02() {
  final IResolvedOperation operation = this.toOperation("(null as testdata.MethodOverrides4).withArray(null)");
  JvmOperation _declaration = operation.getDeclaration();
  _declaration.setVisibility(JvmVisibility.PROTECTED);
  final Consumer<JvmOperation> _function = (JvmOperation it) -> {
    it.setVisibility(JvmVisibility.DEFAULT);
  };
  operation.getOverriddenAndImplementedMethodCandidates().forEach(_function);
  this.withDetails(this.candidatesAndOverrides(this.has(operation, 1), 1), IOverrideCheckResult.OverrideCheckDetails.VAR_ARG_MISMATCH);
}
 
Example 8
Source File: XtendJvmModelInferrer.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void initialize(XtendAnnotationType source, JvmAnnotationType inferredJvmType) {
	inferredJvmType.setVisibility(source.getVisibility());
	inferredJvmType.setStatic(source.isStatic() && !isTopLevel(source));
	inferredJvmType.setAbstract(true);
	translateAnnotationsTo(source.getAnnotations(), inferredJvmType);
	jvmTypesBuilder.copyDocumentationTo(source, inferredJvmType);
	for (XtendMember member : source.getMembers()) {
		if (member instanceof XtendField) {
			XtendField field = (XtendField) member;
			if (!Strings.isEmpty(field.getName())) {
				JvmOperation operation = typesFactory.createJvmOperation();
				associator.associatePrimary(member, operation);
				operation.setSimpleName(field.getName());
				JvmTypeReference returnType = null;
				XExpression initialValue = field.getInitialValue();
				if (field.getType() != null) {
					returnType = jvmTypesBuilder.cloneWithProxies(field.getType());
				} else if (initialValue != null) {
					returnType = jvmTypesBuilder.inferredType(initialValue);
				}
				operation.setReturnType(returnType);
				if (initialValue != null) {
					JvmAnnotationValue jvmAnnotationValue = jvmTypesBuilder.toJvmAnnotationValue(initialValue);
					if (jvmAnnotationValue != null) {
						operation.setDefaultValue(jvmAnnotationValue);
						jvmAnnotationValue.setOperation(operation);
					}
					jvmTypesBuilder.setBody(operation, initialValue);
				}
				operation.setVisibility(JvmVisibility.PUBLIC);
				translateAnnotationsTo(member.getAnnotations(), operation);
				jvmTypesBuilder.copyDocumentationTo(member, operation);
				inferredJvmType.getMembers().add(operation);
			}
		}
	}
}
 
Example 9
Source File: MutableJvmAnnotationTypeDeclarationImpl.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public MutableAnnotationTypeElementDeclaration addAnnotationTypeElement(final String name, final Procedure1<MutableAnnotationTypeElementDeclaration> initializer) {
  this.checkMutable();
  ConditionUtils.checkJavaIdentifier(name, "name");
  Preconditions.checkArgument((initializer != null), "initializer cannot be null");
  final JvmOperation newAnnotationElement = TypesFactory.eINSTANCE.createJvmOperation();
  newAnnotationElement.setSimpleName(name);
  newAnnotationElement.setVisibility(JvmVisibility.PUBLIC);
  this.getDelegate().getMembers().add(newAnnotationElement);
  MemberDeclaration _memberDeclaration = this.getCompilationUnit().toMemberDeclaration(newAnnotationElement);
  final MutableAnnotationTypeElementDeclaration mutableAnnotationTypeElementDeclaration = ((MutableAnnotationTypeElementDeclaration) _memberDeclaration);
  initializer.apply(mutableAnnotationTypeElementDeclaration);
  return mutableAnnotationTypeElementDeclaration;
}
 
Example 10
Source File: JvmTypeDeclarationImpl.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public MutableMethodDeclaration addMethod(final String name, final Procedure1<MutableMethodDeclaration> initializer) {
  this.checkMutable();
  ConditionUtils.checkJavaIdentifier(name, "name");
  Preconditions.checkArgument((initializer != null), "initializer cannot be null");
  final JvmOperation newMethod = TypesFactory.eINSTANCE.createJvmOperation();
  newMethod.setVisibility(JvmVisibility.PUBLIC);
  newMethod.setSimpleName(name);
  newMethod.setReturnType(this.getCompilationUnit().toJvmTypeReference(this.getCompilationUnit().getTypeReferenceProvider().getPrimitiveVoid()));
  this.getDelegate().getMembers().add(newMethod);
  MemberDeclaration _memberDeclaration = this.getCompilationUnit().toMemberDeclaration(newMethod);
  final MutableMethodDeclaration mutableMethodDeclaration = ((MutableMethodDeclaration) _memberDeclaration);
  initializer.apply(mutableMethodDeclaration);
  return mutableMethodDeclaration;
}
 
Example 11
Source File: SARLJvmModelInferrer.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Copy the JVM operations from the source to the destination.
 *
 * @param source the source.
 * @param target the destination.
 * @param createdActions the set of actions that are created before (input) or during (output) the invocation.
 * @param bodyBuilder the builder of the target's operations.
 * @since 0.5
 */
@SuppressWarnings("checkstyle:npathcomplexity")
protected void copyNonStaticPublicJvmOperations(JvmGenericType source, JvmGenericType target,
		Set<ActionPrototype> createdActions, Procedure2<? super JvmOperation, ? super ITreeAppendable> bodyBuilder) {
	final Iterable<JvmOperation> operations = Iterables.transform(Iterables.filter(source.getMembers(), it -> {
		if (it instanceof JvmOperation) {
			final JvmOperation op = (JvmOperation) it;
			return !op.isStatic() && op.getVisibility() == JvmVisibility.PUBLIC;
		}
		return false;
	}), it -> (JvmOperation) it);
	for (final JvmOperation operation : operations) {
		final ActionParameterTypes types = this.sarlSignatureProvider.createParameterTypesFromJvmModel(
				operation.isVarArgs(), operation.getParameters());
		final ActionPrototype actSigKey = this.sarlSignatureProvider.createActionPrototype(
				operation.getSimpleName(), types);
		if (createdActions.add(actSigKey)) {
			final JvmOperation newOp = this.typesFactory.createJvmOperation();
			target.getMembers().add(newOp);

			newOp.setAbstract(false);
			newOp.setFinal(false);
			newOp.setNative(false);
			newOp.setStatic(false);
			newOp.setSynchronized(false);
			newOp.setVisibility(JvmVisibility.PUBLIC);

			newOp.setDefault(operation.isDefault());
			newOp.setDeprecated(operation.isDeprecated());
			newOp.setSimpleName(operation.getSimpleName());
			newOp.setStrictFloatingPoint(operation.isStrictFloatingPoint());

			copyTypeParametersFromJvmOperation(operation, newOp);

			for (final JvmTypeReference exception : operation.getExceptions()) {
				newOp.getExceptions().add(cloneWithTypeParametersAndProxies(exception, newOp));
			}

			for (final JvmFormalParameter parameter : operation.getParameters()) {
				final JvmFormalParameter newParam = this.typesFactory.createJvmFormalParameter();
				newOp.getParameters().add(newParam);
				newParam.setName(parameter.getSimpleName());
				newParam.setParameterType(cloneWithTypeParametersAndProxies(parameter.getParameterType(), newOp));
			}

			newOp.setVarArgs(operation.isVarArgs());

			newOp.setReturnType(cloneWithTypeParametersAndProxies(operation.getReturnType(), newOp));

			setBody(newOp, it -> bodyBuilder.apply(operation, it));
		}
	}
}
 
Example 12
Source File: SARLJvmModelInferrer.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Append the guard evaluators.
 *
 * @param container the container type.
 */
protected void appendEventGuardEvaluators(JvmGenericType container) {
	final GenerationContext context = getContext(container);
	if (context != null) {
		final Collection<Pair<SarlBehaviorUnit, Collection<Procedure1<? super ITreeAppendable>>>> allEvaluators
				= context.getGuardEvaluationCodes();
		if (allEvaluators == null || allEvaluators.isEmpty()) {
			return;
		}

		final JvmTypeReference voidType = this._typeReferenceBuilder.typeRef(Void.TYPE);
		final JvmTypeReference runnableType = this._typeReferenceBuilder.typeRef(Runnable.class);
		final JvmTypeReference collectionType = this._typeReferenceBuilder.typeRef(Collection.class, runnableType);
		for (final Pair<SarlBehaviorUnit, Collection<Procedure1<? super ITreeAppendable>>> evaluators : allEvaluators) {
			final SarlBehaviorUnit source = evaluators.getKey();
			// Determine the name of the operation for the behavior output
			final String behName = Utils.createNameForHiddenGuardGeneralEvaluatorMethod(source.getName().getSimpleName());

			// Create the main function
			final JvmOperation operation = this.typesFactory.createJvmOperation();

			// Annotation for the event bus

			appendGeneratedAnnotation(operation, context);
			addAnnotationSafe(operation, PerceptGuardEvaluator.class);

			// Guard evaluator unit parameters
			// - Event occurrence
			JvmFormalParameter jvmParam = this.typesFactory.createJvmFormalParameter();
			jvmParam.setName(this.grammarKeywordAccess.getOccurrenceKeyword());
			jvmParam.setParameterType(this.typeBuilder.cloneWithProxies(source.getName()));
			this.associator.associate(source, jvmParam);
			operation.getParameters().add(jvmParam);
			// - List of runnables
			jvmParam = this.typesFactory.createJvmFormalParameter();
			jvmParam.setName(RUNNABLE_COLLECTION);
			jvmParam.setParameterType(this.typeBuilder.cloneWithProxies(collectionType));
			operation.getParameters().add(jvmParam);

			operation.setAbstract(false);
			operation.setNative(false);
			operation.setSynchronized(false);
			operation.setStrictFloatingPoint(false);
			operation.setFinal(false);
			operation.setVisibility(JvmVisibility.PRIVATE);
			operation.setStatic(false);
			operation.setSimpleName(behName);
			operation.setReturnType(this.typeBuilder.cloneWithProxies(voidType));
			container.getMembers().add(operation);

			setBody(operation, it -> {
				it.append("assert "); //$NON-NLS-1$
				it.append(this.grammarKeywordAccess.getOccurrenceKeyword());
				it.append(" != null;"); //$NON-NLS-1$
				it.newLine();
				it.append("assert "); //$NON-NLS-1$
				it.append(RUNNABLE_COLLECTION);
				it.append(" != null;"); //$NON-NLS-1$
				for (final Procedure1<? super ITreeAppendable> code : evaluators.getValue()) {
					it.newLine();
					code.apply(it);
				}
			});

			this.associator.associatePrimary(source, operation);
			this.typeBuilder.copyDocumentationTo(source, operation);
		}
	}
}
 
Example 13
Source File: SARLJvmModelInferrer.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Transform the uses of SARL capacities.
 *
 * <p>Resolving the calls to the capacities' functions is done in {@link SARLReentrantTypeResolver}.
 *
 * @param source the feature to transform.
 * @param container the target container of the transformation result.
 */
protected void transform(SarlCapacityUses source, JvmGenericType container) {
	final GenerationContext context = getContext(container);
	if (context == null) {
		return;
	}
	for (final JvmTypeReference capacityType : source.getCapacities()) {
		final JvmType type = capacityType.getType();
		if (type instanceof JvmGenericType
				/*&& this.inheritanceHelper.isSubTypeOf(capacityType, Capacity.class, SarlCapacity.class)*/
				&& !context.getGeneratedCapacityUseFields().contains(capacityType.getIdentifier())) {
			// Generate the buffer field
			final String fieldName = Utils.createNameForHiddenCapacityImplementationAttribute(capacityType.getIdentifier());
			final JvmField field = this.typesFactory.createJvmField();
			container.getMembers().add(field);
			field.setVisibility(JvmVisibility.PRIVATE);
			field.setSimpleName(fieldName);
			field.setTransient(true);
			final JvmTypeReference skillClearableReference = this.typeReferences.getTypeForName(AtomicSkillReference.class, container);
			field.setType(skillClearableReference);

			this.associator.associatePrimary(source, field);

			addAnnotationSafe(field, Extension.class);
			field.getAnnotations().add(annotationClassRef(ImportedCapacityFeature.class,
					Collections.singletonList(capacityType)));
			appendGeneratedAnnotation(field, getContext(container));

			// Generate the calling function
			final String methodName = Utils.createNameForHiddenCapacityImplementationCallingMethodFromFieldName(
					fieldName);
			final JvmOperation operation = this.typesFactory.createJvmOperation();
			container.getMembers().add(operation);
			operation.setVisibility(JvmVisibility.PRIVATE);
			operation.setReturnType(cloneWithTypeParametersAndProxies(capacityType, operation));
			operation.setSimpleName(methodName);

			this.associator.associatePrimary(source, operation);

			setBody(operation, it -> {
				it.append("if (this.").append(fieldName).append(" == null || this."); //$NON-NLS-1$ //$NON-NLS-2$
				it.append(fieldName).append(".get() == null) {"); //$NON-NLS-1$
				it.increaseIndentation();
				it.newLine();
				it.append("this.").append(fieldName).append(" = ") //$NON-NLS-1$ //$NON-NLS-2$
						.append(Utils.HIDDEN_MEMBER_CHARACTER).append("getSkill("); //$NON-NLS-1$
				it.append(capacityType.getType()).append(".class);"); //$NON-NLS-1$
				it.decreaseIndentation();
				it.newLine();
				it.append("}"); //$NON-NLS-1$
				it.newLine();
				it.append("return ").append(Utils.HIDDEN_MEMBER_CHARACTER) //$NON-NLS-1$
						.append("castSkill(").append(capacityType.getType()).append(".class, this.") //$NON-NLS-1$ //$NON-NLS-2$
						.append(fieldName).append(");"); //$NON-NLS-1$
			});

			// Add the annotation dedicated to this particular method
			if (context.isAtLeastJava8()) {
				/*context.getPostFinalizationElements().add(() -> {
					final String inlineExpression = Utils.HIDDEN_MEMBER_CHARACTER
							+ "castSkill(" + capacityType.getSimpleName() //$NON-NLS-1$
							+ ".class, ($0" + fieldName //$NON-NLS-1$
							+ " == null || $0" + fieldName //$NON-NLS-1$
							+ ".get() == null) ? ($0" + fieldName //$NON-NLS-1$
							+ " = $0" + Utils.HIDDEN_MEMBER_CHARACTER + "getSkill(" //$NON-NLS-1$ //$NON-NLS-2$
							+ capacityType.getSimpleName()
							+ ".class)) : $0" + fieldName + ")"; //$NON-NLS-1$ //$NON-NLS-2$;
					this.inlineExpressionCompiler.appendInlineAnnotation(
							operation, source.eResource().getResourceSet(), inlineExpression, capacityType);
				});*/
			}
			appendGeneratedAnnotation(operation, context);
			if (context.getGeneratorConfig2().isGeneratePureAnnotation()) {
				addAnnotationSafe(operation, Pure.class);
			}

			context.addGeneratedCapacityUseField(capacityType.getIdentifier());
			context.incrementSerial(capacityType.getIdentifier().hashCode());
		}
	}
}
 
Example 14
Source File: XtendJvmModelInferrer.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected void transformCreateExtension(XtendFunction source, CreateExtensionInfo createExtensionInfo,
		JvmGenericType container, JvmOperation operation, /* @Nullable */ JvmTypeReference returnType) {
	JvmField cacheVar = jvmTypesBuilder.toField(
			source, CREATE_CHACHE_VARIABLE_PREFIX + source.getName(), jvmTypesBuilder.inferredType());
	if (cacheVar != null) {
		cacheVar.setFinal(true);
		jvmTypesBuilder.setInitializer(cacheVar, compileStrategies.forCacheVariable(source));
		container.getMembers().add(cacheVar);

		JvmOperation initializer = typesFactory.createJvmOperation();
		container.getMembers().add(initializer);
		initializer.setSimpleName(CREATE_INITIALIZER_PREFIX + source.getName());
		initializer.setVisibility(JvmVisibility.PRIVATE);
		initializer.setReturnType(typeReferences.getTypeForName(Void.TYPE, source));
		for (JvmTypeReference exception : source.getExceptions()) {
			initializer.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception));
		}

		jvmTypesBuilder.setBody(operation,
				compileStrategies.forCacheMethod(createExtensionInfo, cacheVar, initializer));

		// the first parameter is the created object
		JvmFormalParameter jvmParam = typesFactory.createJvmFormalParameter();
		jvmParam.setName(createExtensionInfo.getName());
		// TODO consider type parameters
		jvmParam.setParameterType(jvmTypesBuilder.inferredType());
		
		initializer.getParameters().add(jvmParam);
		associator.associate(createExtensionInfo, jvmParam);

		// add all others
		for (XtendParameter parameter : source.getParameters()) {
			jvmParam = typesFactory.createJvmFormalParameter();
			jvmParam.setName(parameter.getName());
			jvmParam.setParameterType(jvmTypesBuilder.cloneWithProxies(parameter.getParameterType()));
			initializer.getParameters().add(jvmParam);
			associator.associate(parameter, jvmParam);
		}
		associator.associate(source, initializer);
		setBody(operation, createExtensionInfo.getCreateExpression());
		setBody(initializer, source.getExpression());
	}
}
 
Example 15
Source File: XtendJvmModelInferrer.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected void transform(XtendFunction source, JvmGenericType container, boolean allowDispatch) {
	JvmOperation operation = typesFactory.createJvmOperation();
	operation.setAbstract(source.isAbstract());
	operation.setNative(source.isNative());
	operation.setSynchronized(source.isSynchonized());
	operation.setStrictFloatingPoint(source.isStrictFloatingPoint());
	if (!source.isAbstract())
		operation.setFinal(source.isFinal());
	container.getMembers().add(operation);
	associator.associatePrimary(source, operation);
	String sourceName = source.getName();
	JvmVisibility visibility = source.getVisibility();
	if (allowDispatch && source.isDispatch()) {
		if (source.getDeclaredVisibility() == null)
			visibility = JvmVisibility.PROTECTED;
		sourceName = "_" + sourceName;
	}
	operation.setSimpleName(sourceName);
	operation.setVisibility(visibility);
	operation.setStatic(source.isStatic());
	if (!operation.isAbstract() && !operation.isStatic() && container.isInterface())
		operation.setDefault(true);
	for (XtendParameter parameter : source.getParameters()) {
		translateParameter(operation, parameter);
	}
	XExpression expression = source.getExpression();
	CreateExtensionInfo createExtensionInfo = source.getCreateExtensionInfo();
	
	JvmTypeReference returnType = null;
	if (source.getReturnType() != null) {
		returnType = jvmTypesBuilder.cloneWithProxies(source.getReturnType());
	} else if (createExtensionInfo != null) {
		returnType = jvmTypesBuilder.inferredType(createExtensionInfo.getCreateExpression());
	} else if (expression != null) {
		returnType = jvmTypesBuilder.inferredType(expression);
	} else {
		returnType = jvmTypesBuilder.inferredType();
	}
	
	operation.setReturnType(returnType);
	copyAndFixTypeParameters(source.getTypeParameters(), operation);
	for (JvmTypeReference exception : source.getExceptions()) {
		operation.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception));
	}
	translateAnnotationsTo(source.getAnnotations(), operation);
	if (source.isOverride() && typeReferences.findDeclaredType(Override.class, source) != null)
		setOverride(operation);
	if (createExtensionInfo != null) {
		transformCreateExtension(source, createExtensionInfo, container, operation, returnType);
	} else {
		setBody(operation, expression);
	}
	jvmTypesBuilder.copyDocumentationTo(source, operation);
}
 
Example 16
Source File: XtendJvmModelInferrer.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @return a {@link JvmOperation} with common denominator argument types of all given operations
 */
/* @Nullable */
protected JvmOperation deriveGenericDispatchOperationSignature(Iterable<JvmOperation> localOperations,
		JvmGenericType target) {
	final Iterator<JvmOperation> iterator = localOperations.iterator();
	if (!iterator.hasNext())
		return null;
	JvmOperation first = iterator.next();
	JvmOperation result = typesFactory.createJvmOperation();
	target.getMembers().add(result);
	for (int i = 0; i < first.getParameters().size(); i++) {
		JvmFormalParameter parameter = typesFactory.createJvmFormalParameter();
		result.getParameters().add(parameter);
		parameter.setParameterType(jvmTypesBuilder.inferredType());
		JvmFormalParameter parameter2 = first.getParameters().get(i);
		parameter.setName(parameter2.getName());
	}
	jvmTypesBuilder.setBody(result, compileStrategies.forDispatcher(result));
	JvmVisibility commonVisibility = null;
	boolean isFirst = true;
	boolean allStatic = true;
	boolean override = false;
	for (JvmOperation jvmOperation : localOperations) {
		Iterable<XtendFunction> xtendFunctions = Iterables.filter(associations.getSourceElements(jvmOperation),
				XtendFunction.class);
		for (XtendFunction func : xtendFunctions) {
			JvmVisibility xtendVisibility = func.getDeclaredVisibility();
			if (isFirst) {
				commonVisibility = xtendVisibility;
				isFirst = false;
			} else if (commonVisibility != xtendVisibility) {
				commonVisibility = null;
			}
			associator.associate(func, result);
			if (!func.isStatic())
				allStatic = false;
			if (func.isOverride())
				override = true;
		}
		for (JvmTypeReference declaredException : jvmOperation.getExceptions())
			result.getExceptions().add(jvmTypesBuilder.cloneWithProxies(declaredException));
	}
	if (commonVisibility == null)
		result.setVisibility(JvmVisibility.PUBLIC);
	else
		result.setVisibility(commonVisibility);
	result.setStatic(allStatic);
	if (override)
		setOverride(result);
	return result;
}
 
Example 17
Source File: JvmTypesBuilder.java    From xtext-extras with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a public method with the given name and the given return type and associates it with the given
 * sourceElement.
 * 
 * @param sourceElement 
 * 		the sourceElement the method should be associated with.
 * @param name
 * 		the simple name of the method to be created.
 * @param returnType
 * 		the return type of the created method.
 * @param initializer
 *            the initializer to apply on the created method. If <code>null</code>, the method won't be initialized.
 * 
 * @return a result representing a Java method with the given name, <code>null</code> if sourceElement or name are <code>null</code>.
 */
/* @Nullable */
public JvmOperation toMethod(/* @Nullable */ EObject sourceElement, /* @Nullable */ String name, /* @Nullable */ JvmTypeReference returnType,
		/* @Nullable */ Procedure1<? super JvmOperation> initializer) {
	if(sourceElement == null || name == null) 
		return null;
	JvmOperation result = typesFactory.createJvmOperation();
	result.setSimpleName(name);
	result.setVisibility(JvmVisibility.PUBLIC);
	result.setReturnType(cloneWithProxies(returnType));
	associate(sourceElement, result);
	return initializeSafely(result, initializer);
}