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

The following examples show how to use org.eclipse.xtext.common.types.JvmOperation#getParameters() . 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: JvmModelGeneratorTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSimple() {
  try {
    final XExpression expression = this.expression("return s.toUpperCase", false);
    final Procedure1<JvmGenericType> _function = (JvmGenericType it) -> {
      EList<JvmMember> _members = it.getMembers();
      final Procedure1<JvmOperation> _function_1 = (JvmOperation it_1) -> {
        EList<JvmFormalParameter> _parameters = it_1.getParameters();
        JvmFormalParameter _parameter = this.builder.toParameter(expression, "s", this.references.getTypeForName(String.class, expression));
        this.builder.<JvmFormalParameter>operator_add(_parameters, _parameter);
        this.builder.setBody(it_1, expression);
      };
      JvmOperation _method = this.builder.toMethod(expression, "doStuff", this.references.getTypeForName(String.class, expression), _function_1);
      this.builder.<JvmOperation>operator_add(_members, _method);
    };
    final JvmGenericType clazz = this.builder.toClass(expression, "my.test.Foo", _function);
    final Class<?> compiledClass = this.compile(expression.eResource(), clazz);
    final Object instance = compiledClass.getDeclaredConstructor().newInstance();
    Assert.assertEquals("FOO", compiledClass.getMethod("doStuff", String.class).invoke(instance, "foo"));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 2
Source File: JvmDeclaredTypeSignatureHashProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected SignatureHashBuilder appendSignature(JvmOperation operation) {
	appendVisibility(operation.getVisibility()).append(" ");
	if (operation.isAbstract())
		append("abstract ");
	if (operation.isStatic())
		append("static ");
	if (operation.isFinal())
		append("final ");
	appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ")
			.append(operation.getSimpleName()).append("(");
	for (JvmFormalParameter p : operation.getParameters()) {
		appendType(p.getParameterType());
		append(" ");
	}
	append(") ");
	for (JvmTypeReference ex : operation.getExceptions()) {
		appendType(ex).append(" ");
	}
	return this;
}
 
Example 3
Source File: DispatchRenameSupportTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public String signature(final JvmOperation it) {
  StringConcatenation _builder = new StringConcatenation();
  String _qualifiedName = it.getQualifiedName();
  _builder.append(_qualifiedName);
  _builder.append("(");
  {
    EList<JvmFormalParameter> _parameters = it.getParameters();
    boolean _hasElements = false;
    for(final JvmFormalParameter p : _parameters) {
      if (!_hasElements) {
        _hasElements = true;
      } else {
        _builder.appendImmediate(",", "");
      }
      String _simpleName = p.getParameterType().getType().getSimpleName();
      _builder.append(_simpleName);
    }
  }
  _builder.append(")");
  return _builder.toString();
}
 
Example 4
Source File: OperationBodyComputationState.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public OperationBodyComputationState(ResolvedTypes resolvedTypes,
		IFeatureScopeSession featureScopeSession,
		JvmOperation operation) {
	super(resolvedTypes.pushExpectedExceptions(operation), featureScopeSession, operation);
	for(JvmFormalParameter parameter: operation.getParameters()) {
		addLocalToCurrentScope(parameter);
	}
}
 
Example 5
Source File: ExtensionScopeHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isMatchingFirstParameter(JvmOperation feature) {
	List<JvmFormalParameter> parameters = feature.getParameters();
	JvmFormalParameter firstParameter = parameters.get(0);
	JvmTypeReference type = firstParameter.getParameterType();
	if (type == null)
		return false;
	JvmType rawParameterType = type.getType();
	if (rawParameterType == null || rawParameterType.eIsProxy())
		return false;
	if (!(rawParameterType instanceof JvmTypeParameter)) {
		if (rawArgumentType.isResolved()) {
			// short circuit - limit extension scope entries to real candidates
			LightweightTypeReference parameterTypeReference = rawArgumentType.getOwner().toPlainTypeReference(rawParameterType);
			if (parameterTypeReference.isResolved() && !parameterTypeReference.isAssignableFrom(rawArgumentType)) {
				if (parameterTypeReference.isArray() && !rawArgumentType.isArray() && rawArgumentType.isSubtypeOf(Iterable.class)) {
					return true;
				}
				return false;
			}
			if (parameterTypeReference.isArray() && !rawArgumentType.isArray() && !rawArgumentType.isSubtypeOf(Iterable.class)) {
				return false;
			}
		} else if (isArrayTypeMismatch(rawArgumentType, rawParameterType)) {
			return false;
		}
	}
	return true;
}
 
Example 6
Source File: JvmModelGeneratorTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBug380754_2() {
  try {
    final XExpression expression = this.expression("null");
    final JvmAnnotationReferenceBuilder jvmAnnotationReferenceBuilder = this.jvmAnnotationReferenceBuilderFactory.create(expression.eResource().getResourceSet());
    final Procedure1<JvmGenericType> _function = (JvmGenericType it) -> {
      EList<JvmMember> _members = it.getMembers();
      final Procedure1<JvmOperation> _function_1 = (JvmOperation it_1) -> {
        this.builder.setBody(it_1, expression);
        final JvmFormalParameter parameter = this.builder.toParameter(expression, "s", this.references.getTypeForName(String.class, expression));
        EList<JvmFormalParameter> _parameters = it_1.getParameters();
        this.builder.<JvmFormalParameter>operator_add(_parameters, parameter);
        EList<JvmAnnotationReference> _annotations = parameter.getAnnotations();
        JvmAnnotationReference _annotationRef = jvmAnnotationReferenceBuilder.annotationRef(TestAnnotation.class);
        this.builder.<JvmAnnotationReference>operator_add(_annotations, _annotationRef);
        EList<JvmAnnotationReference> _annotations_1 = parameter.getAnnotations();
        JvmAnnotationReference _annotationRef_1 = jvmAnnotationReferenceBuilder.annotationRef(TestAnnotation2.class);
        this.builder.<JvmAnnotationReference>operator_add(_annotations_1, _annotationRef_1);
      };
      JvmOperation _method = this.builder.toMethod(expression, "doStuff", this.references.getTypeForName("java.lang.Object", expression), _function_1);
      this.builder.<JvmOperation>operator_add(_members, _method);
    };
    final JvmGenericType clazz = this.builder.toClass(expression, "my.test.Foo", _function);
    this.compile(expression.eResource(), clazz);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 7
Source File: InferredJvmModelTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testExtensionToAnnotation_02() throws Exception {
	XtendFile xtendFile = file("class C { def void m(extension String s) {} }");
	JvmGenericType inferredType = getInferredType(xtendFile);
	JvmOperation jvmOperation = (JvmOperation) inferredType.getMembers().get(1);
	List<JvmFormalParameter> parameters = jvmOperation.getParameters();
	JvmFormalParameter singleParameter = parameters.get(0);
	List<JvmAnnotationReference> annotations = singleParameter.getAnnotations();
	assertEquals(1, annotations.size());
	assertEquals(Extension.class.getCanonicalName(), annotations.get(0).getAnnotation().getQualifiedName());
}
 
Example 8
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected List<JvmType> getParamTypes(JvmOperation jvmOperation, boolean wrapPrimitives) {
	List<JvmType> types = newArrayList();
	for (JvmFormalParameter p : jvmOperation.getParameters()) {
		LightweightTypeReference typeReference = toLightweightTypeReference(p.getParameterType());
		if (wrapPrimitives) {
			typeReference = typeReference.getWrapperTypeIfPrimitive();
		}
		types.add(typeReference.getType());
	}
	return types;
}
 
Example 9
Source File: SARLExpressionHelper.java    From sarl with Apache License 2.0 5 votes vote down vote up
private boolean hasPrimitiveParameters(JvmOperation op) {
	for (final JvmFormalParameter parameter : op.getParameters()) {
		final JvmTypeReference type = parameter.getParameterType();
		if (type == null || !Utils.toLightweightTypeReference(type, this.services).isPrimitive()) {
			return false;
		}
	}
	return true;
}
 
Example 10
Source File: ObjectAndPrimitiveBasedCastOperationCandidateSelector.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Validate the parameters of the operation.
 *
 * @param operation the operation from which the parameters are extracted.
 * @return {@code true} if the return type is valid; otherwise {@code false}.
 */
protected boolean isValidParameters(JvmOperation operation) {
	final List<JvmFormalParameter> parameters = operation.getParameters();
	if (parameters.size() == 0) {
		final JvmType originType = operation.getDeclaringType();
		return this.expressionType.isSubtypeOf(originType);
	} else if (parameters.size() == 1) {
		final JvmTypeReference parameterType = parameters.get(0).getParameterType();
		final LightweightTypeReference paramType = this.state.getReferenceOwner().toLightweightTypeReference(parameterType);
		if (parameterType != null) {
			return paramType.isAssignableFrom(this.expressionType);
		}
	}
	return false;
}
 
Example 11
Source File: SARLOperationHelper.java    From sarl with Apache License 2.0 5 votes vote down vote up
private boolean hasPrimitiveParameters(JvmOperation op) {
	for (final JvmFormalParameter parameter : op.getParameters()) {
		final JvmTypeReference type = parameter.getParameterType();
		if (type == null || !Utils.toLightweightTypeReference(type, this.services).isPrimitive()) {
			return false;
		}
	}
	return true;
}
 
Example 12
Source File: JvmModelGeneratorTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void bug390290InnerClassMemberImport() {
  try {
    final XExpression expression = this.expression("null");
    final Procedure1<JvmGenericType> _function = (JvmGenericType it) -> {
      final JvmGenericType innerClass = this.builder.toClass(it, "InnerClass");
      final JvmGenericType innerClassString = this.builder.toClass(it, "String");
      EList<JvmMember> _members = it.getMembers();
      this.builder.<JvmGenericType>operator_add(_members, innerClass);
      EList<JvmMember> _members_1 = it.getMembers();
      this.builder.<JvmGenericType>operator_add(_members_1, innerClassString);
      EList<JvmMember> _members_2 = it.getMembers();
      final Procedure1<JvmOperation> _function_1 = (JvmOperation fooMethod) -> {
        EList<JvmFormalParameter> _parameters = fooMethod.getParameters();
        JvmFormalParameter _parameter = this.builder.toParameter(it, "p1", this.references.createTypeRef(innerClass));
        this.builder.<JvmFormalParameter>operator_add(_parameters, _parameter);
        EList<JvmFormalParameter> _parameters_1 = fooMethod.getParameters();
        JvmFormalParameter _parameter_1 = this.builder.toParameter(it, "p2", this.references.createTypeRef(innerClassString));
        this.builder.<JvmFormalParameter>operator_add(_parameters_1, _parameter_1);
        this.builder.setBody(fooMethod, expression);
      };
      JvmOperation _method = this.builder.toMethod(it, "foo", this.references.getTypeForName(String.class, expression), _function_1);
      this.builder.<JvmOperation>operator_add(_members_2, _method);
    };
    final JvmGenericType clazz = this.builder.toClass(expression, "my.test.Outer", _function);
    expression.eResource().eSetDeliver(false);
    EList<EObject> _contents = expression.eResource().getContents();
    this.builder.<JvmGenericType>operator_add(_contents, clazz);
    expression.eResource().eSetDeliver(true);
    final InMemoryFileSystemAccess fsa = new InMemoryFileSystemAccess();
    this.generator.doGenerate(expression.eResource(), fsa);
    Map<String, CharSequence> _textFiles = fsa.getTextFiles();
    String _replace = clazz.getIdentifier().replace(".", "/");
    String _plus = (IFileSystemAccess.DEFAULT_OUTPUT + _replace);
    String _plus_1 = (_plus + ".java");
    final String code = _textFiles.get(_plus_1).toString();
    Assert.assertFalse(code.contains("import"));
    Assert.assertTrue(code, code.contains("java.lang.String foo"));
    final Class<?> compiledClass = this.javaCompiler.compileToClass(clazz.getIdentifier(), code);
    this.helper.assertNoErrors(IterableExtensions.<EObject>head(expression.eResource().getContents()));
    Assert.assertEquals(2, ((List<Class<?>>)Conversions.doWrapArray(compiledClass.getDeclaredClasses())).size());
    Assert.assertNotNull(compiledClass.getMethod("foo", IterableExtensions.<Class<?>>head(((Iterable<Class<?>>)Conversions.doWrapArray(compiledClass.getDeclaredClasses()))), IterableExtensions.<Class<?>>last(((Iterable<Class<?>>)Conversions.doWrapArray(compiledClass.getDeclaredClasses())))));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 13
Source File: CacheMethodCompileStrategy.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void apply(ITreeAppendable appendable) {
	JvmOperation cacheMethod = (JvmOperation) logicalContainerProvider.getLogicalContainer(createExtensionInfo.getCreateExpression());
	JvmDeclaredType containerType = cacheMethod.getDeclaringType();
	IResolvedTypes resolvedTypes = typeResolver.resolveTypes(containerType);
	final ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, containerType);
	LightweightTypeReference listType = owner.newReferenceTo(ArrayList.class, new TypeReferenceInitializer<ParameterizedTypeReference>() {
		@Override
		public LightweightTypeReference enhance(ParameterizedTypeReference reference) {
			reference.addTypeArgument(owner.newWildcardTypeReference());
			return reference;
		}
	});
	String cacheVarName = cacheField.getSimpleName();
	String cacheKeyVarName = appendable.declareSyntheticVariable("CacheKey", "_cacheKey");
	appendable.append("final ").append(listType).append(" ").append(cacheKeyVarName)
		.append(" = ").append(CollectionLiterals.class).append(".newArrayList(");
	List<JvmFormalParameter> list = cacheMethod.getParameters();
	for (Iterator<JvmFormalParameter> iterator = list.iterator(); iterator.hasNext();) {
		JvmFormalParameter jvmFormalParameter = iterator.next();
		appendable.append(getVarName(jvmFormalParameter));
		if (iterator.hasNext()) {
			appendable.append(", ");
		}
	}
	appendable.append(");");
	// declare result variable
	LightweightTypeReference returnType = resolvedTypes.getActualType(initializerMethod.getParameters().get(0));
	if (returnType != null) {
		appendable.newLine().append("final ").append(returnType);
	} else {
		appendable.newLine().append("final Object");
	}
	String resultVarName = "_result";
	appendable.append(" ").append(resultVarName).append(";");
	// open synchronize block
	appendable.newLine().append("synchronized (").append(cacheVarName).append(") {");
	appendable.increaseIndentation();
	// if the cache contains the key return the previously created object.
	appendable.newLine().append("if (").append(cacheVarName).append(".containsKey(").append(cacheKeyVarName)
			.append(")) {");
	appendable.increaseIndentation();
	appendable.newLine().append("return ").append(cacheVarName).append(".get(").append(cacheKeyVarName).append(");");
	appendable.decreaseIndentation().newLine().append("}");
	
	// execute the creation
	compiler.toJavaStatement(createExtensionInfo.getCreateExpression(), appendable, true);
	appendable.newLine();
	appendable.append(resultVarName).append(" = ");
	compiler.toJavaExpression(createExtensionInfo.getCreateExpression(), appendable);
	appendable.append(";");

	// store the newly created object in the cache
	appendable.newLine().append(cacheVarName).append(".put(").append(cacheKeyVarName).append(", ");
	LightweightTypeReference fieldType = resolvedTypes.getActualType(cacheField);
	LightweightTypeReference declaredResultType = fieldType.getTypeArguments().get(1);
	boolean castRequired = false;
	if (!declaredResultType.isAssignableFrom(returnType)) {
		castRequired = true;
		appendable.append("(").append(declaredResultType).append(")");
	}
	appendable.append(resultVarName).append(");");

	// close synchronize block
	appendable.decreaseIndentation();
	appendable.newLine().append("}");
	appendable.newLine().append(initializerMethod.getSimpleName()).append("(").append(resultVarName);
	for (JvmFormalParameter parameter : cacheMethod.getParameters()) {
		appendable.append(", ").append(parameter.getName());
	}
	appendable.append(");");
	// return the result
	appendable.newLine().append("return ");
	if (castRequired) {
		appendable.append("(").append(declaredResultType).append(")");
	}
	appendable.append(resultVarName).append(";");
}
 
Example 14
Source File: MissedMethodAddModification.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(EObject element, IModificationContext context) throws Exception {
	final XtendTypeDeclaration container = (XtendTypeDeclaration) element;
	final IXtextDocument document = context.getXtextDocument();
	final SARLQuickfixProvider tools = getTools();

	final JvmDeclaredType declaringType = (JvmDeclaredType) this.associations.getPrimaryJvmElement(container);

	final int insertOffset = tools.getInsertOffset(container);
	final int length = tools.getSpaceSize(document, insertOffset);
	final OptionalParameters options = new OptionalParameters();
	options.isJava = false;
	options.ensureEmptyLinesAround = false;
	options.baseIndentationLevel = 1;
	final ReplacingAppendable appendable = tools.getAppendableFactory().create(document,
			(XtextResource) container.eResource(), insertOffset, length, options);
	// Compute the type parameters' mapping
	final Map<String, JvmTypeReference> typeParameterMap = buildTypeParameterMapping(container);

	for (final JvmOperation operation : tools.getJvmOperationsFromURIs(container, this.operationUris)) {
		if (this.annotationUtils.findAnnotation(operation, SyntheticMember.class.getName()) == null
				&& !isGeneratedOperation(operation)) {

			appendable.newLine().newLine();

			final XtendMethodBuilder builder = this.methodBuilder.get();
			final SarlMethodBuilder sarlBuilder = (builder instanceof SarlMethodBuilder) ? (SarlMethodBuilder) builder : null;

			builder.setContext(declaringType);
			builder.setOwner(declaringType);
			builder.setMethodName(operation.getSimpleName());

			builder.setStaticFlag(false);
			builder.setOverrideFlag(!getTools().isIgnorable(IssueCodes.MISSING_OVERRIDE));
			builder.setAbstractFlag(false);

			builder.setBodyGenerator(null);

			builder.setVisibility(operation.getVisibility());
			builder.setTypeParameters(cloneTypeParameters(operation, declaringType));

			final QualifiedActionName qualifiedActionName = this.actionPrototypeProvider.createQualifiedActionName(
					declaringType,
					operation.getSimpleName());
			final InferredPrototype prototype = this.actionPrototypeProvider.createPrototypeFromJvmModel(
					// TODO More general context?
					this.actionPrototypeProvider.createContext(),
					qualifiedActionName,
					operation.isVarArgs(),
					operation.getParameters());
			final FormalParameterProvider formalParameters = prototype.getFormalParameters();

			int i = 0;
			for (final JvmFormalParameter parameter : operation.getParameters()) {
				final SarlParameterBuilder paramBuilder = (SarlParameterBuilder) builder.newParameterBuilder();
				paramBuilder.setName(parameter.getSimpleName());
				paramBuilder.setType(cloneTypeReference(parameter.getParameterType(), typeParameterMap));
				if (formalParameters.hasFormalParameterDefaultValue(i)) {
					final String defaultValue = formalParameters.getFormalParameterDefaultValueString(i);
					if (defaultValue != null) {
						paramBuilder.setDefaultValue(defaultValue);
					}
				}
				++i;
			}
			builder.setVarArgsFlag(operation.isVarArgs());

			builder.setReturnType(cloneTypeReference(operation.getReturnType(), typeParameterMap));

			builder.setExceptions(cloneTypeReferences(operation.getExceptions(), typeParameterMap));

			if (sarlBuilder != null) {
				final JvmAnnotationReference firedEvents = this.annotationUtils.findAnnotation(operation, FiredEvent.class.getName());
				if (firedEvents != null) {
					final List<JvmTypeReference> events = this.annotationUtils.findTypeValues(firedEvents);
					if (events != null) {
						sarlBuilder.setFires(cloneTypeReferences(events, typeParameterMap));
					}
				}
			}

			builder.build(appendable);
		}
	}
	appendable.newLine().decreaseIndentation().newLine();

	appendable.commitChanges();
}
 
Example 15
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));
		}
	}
}