org.eclipse.xtext.xbase.XClosure Java Examples

The following examples show how to use org.eclipse.xtext.xbase.XClosure. 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: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean bracesAreAddedByOuterStructure(XExpression expression) {
	EObject container = expression.eContainer();
	if (container instanceof XTryCatchFinallyExpression 
			|| container instanceof XIfExpression
			|| container instanceof XClosure
			|| container instanceof XSynchronizedExpression) {
		return true;
	}
	if (container instanceof XBlockExpression) {
		XBlockExpression blockExpression = (XBlockExpression) container;
		EList<XExpression> expressions = blockExpression.getExpressions();
		if (expressions.size() == 1 && expressions.get(0) == expression) {
			return bracesAreAddedByOuterStructure(blockExpression);
		}
	}
	if (!(container instanceof XExpression)) {
		return true;
	}
	return false;
}
 
Example #2
Source File: SerializerTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSerialize_01() throws Exception {
	Resource resource = newResource("'foo' as String");
	XCastedExpression casted = (XCastedExpression) resource.getContents().get(0);
	
	XbaseFactory factory = XbaseFactory.eINSTANCE;
	XClosure closure = factory.createXClosure();
	XStringLiteral stringLiteral = factory.createXStringLiteral();
	stringLiteral.setValue("value");
	XBlockExpression blockExpression = factory.createXBlockExpression();
	blockExpression.getExpressions().add(stringLiteral);
	closure.setExpression(blockExpression);
	closure.setExplicitSyntax(true);
	XInstanceOfExpression instanceOfExpression = factory.createXInstanceOfExpression();
	instanceOfExpression.setExpression(closure);
	instanceOfExpression.setType(EcoreUtil.copy(casted.getType()));
	resource.getContents().clear();
	resource.getContents().add(instanceOfExpression);
	ISerializer serializer = get(ISerializer.class);
	String string = serializer.serialize(instanceOfExpression);
	assertEquals("[|\"value\"] instanceof String", string);
	
	XInstanceOfExpression parsedExpression = parseHelper.parse(string);
	assertTrue(EcoreUtil.equals(instanceOfExpression, parsedExpression));
}
 
Example #3
Source File: XtendReentrantTypeResolver.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private EObject getNearestClosureOrTypeDeclaration(EObject object, IResolvedTypes resolvedTypes) {
	EObject candidate = object;
	while(candidate != null) {
		if (candidate instanceof XClosure) {
			return candidate;
		}
		if (candidate instanceof XConstructorCall) {
			// skip anonymous class constructors themselves
			if (candidate.eContainingFeature() == XtendPackage.Literals.ANONYMOUS_CLASS__CONSTRUCTOR_CALL) {
				candidate = candidate.eContainer();
			}
		} else if (candidate instanceof XtendTypeDeclaration) {
			return candidate;
		}
		if (candidate instanceof RichString) {
			LightweightTypeReference type = resolvedTypes.getActualType((RichString)candidate);
			if (type != null && type.isType(StringConcatenationClient.class)) {
				return candidate;
			}
		}
		candidate = candidate.eContainer();
	}
	return null;
}
 
Example #4
Source File: XtendCompiler.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected boolean needSyntheticSelfVariable(XClosure closure, LightweightTypeReference typeRef) {
	JvmType jvmType = typeRef.getType();
	TreeIterator<EObject> closureIterator = closure.eAllContents();
	while (closureIterator.hasNext()) {
		EObject obj1 = closureIterator.next();
		if (obj1 instanceof XClosure) {
			closureIterator.prune();
		} else if (obj1 instanceof XtendTypeDeclaration) {
			TreeIterator<EObject> typeIterator = obj1.eAllContents();
			while (typeIterator.hasNext()) {
				EObject obj2 = typeIterator.next();
				if (obj2 instanceof XClosure) {
					typeIterator.prune();
				} else if (obj2 instanceof XFeatureCall && isReferenceToSelf((XFeatureCall) obj2, jvmType)) {
					return true;
				}
			}
			closureIterator.prune();
		}
	}
	return false;
}
 
Example #5
Source File: ReorderedVarArgFeatureCallArgumentsTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test_01() {
  final IFeatureCallArguments arguments = this.toArgumentsWithoutReceiver("String s, int i", "[], 1");
  Assert.assertEquals(2, arguments.getArgumentCount());
  Assert.assertTrue(arguments.hasUnprocessedArguments());
  final IFeatureCallArgumentSlot firstSlot = arguments.getNextUnprocessedArgumentSlot();
  Assert.assertTrue(firstSlot.isVarArg());
  Assert.assertFalse(firstSlot.isSuperfluous());
  XExpression _argumentExpression = firstSlot.getArgumentExpression();
  Assert.assertTrue((_argumentExpression instanceof XNumberLiteral));
  Assert.assertEquals("int", firstSlot.getDeclaredType().getSimpleName());
  Assert.assertFalse(arguments.isProcessed(0));
  firstSlot.markProcessed();
  Assert.assertTrue(arguments.isProcessed(0));
  Assert.assertTrue(arguments.hasUnprocessedArguments());
  final IFeatureCallArgumentSlot secondSlot = arguments.getNextUnprocessedArgumentSlot();
  Assert.assertFalse(secondSlot.isVarArg());
  Assert.assertFalse(secondSlot.isSuperfluous());
  XExpression _argumentExpression_1 = secondSlot.getArgumentExpression();
  Assert.assertTrue((_argumentExpression_1 instanceof XClosure));
  Assert.assertEquals("String", secondSlot.getDeclaredType().getSimpleName());
  Assert.assertFalse(arguments.isProcessed(1));
  secondSlot.markProcessed();
  Assert.assertTrue(arguments.isProcessed(1));
  Assert.assertFalse(arguments.hasUnprocessedArguments());
}
 
Example #6
Source File: SARLReentrantTypeResolver.java    From sarl with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("all")
private EObject getNearestClosureOrTypeDeclaration(EObject object, IResolvedTypes resolvedTypes) {
	// Overriding for proper lambda expression.
	EObject candidate = object;
	while(candidate != null) {
		if (candidate instanceof XClosure) {
			return candidate;
		}
		if (candidate instanceof XConstructorCall) {
			// skip anonymous class constructors themselves
			if (candidate.eContainingFeature() == XtendPackage.Literals.ANONYMOUS_CLASS__CONSTRUCTOR_CALL) {
				candidate = candidate.eContainer();
			}
		} else if (candidate instanceof XtendTypeDeclaration) {
			return candidate;
		}
		if (candidate instanceof RichString) {
			LightweightTypeReference type = resolvedTypes.getActualType((RichString)candidate);
			if (type != null && type.isType(StringConcatenationClient.class)) {
				return candidate;
			}
		}
		candidate = candidate.eContainer();
	}
	return null;
}
 
Example #7
Source File: LinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug400807() throws Exception {
	XtendFile file = file(
			"package testPackage\n" +
			"import bug400807.Bug400807\n" +
			"class C {\n" +
			"	def Bug400807 m() {\n" +
			"		[ string ]\n" +
			"	}\n" + 
			"}\n"); 
	XtendClass c = (XtendClass) file.getXtendTypes().get(0);
	XtendFunction m = (XtendFunction) c.getMembers().get(0);
	XBlockExpression body = (XBlockExpression) m.getExpression();
	XClosure lambda = (XClosure) body.getExpressions().get(0);
	XBlockExpression innerBody = (XBlockExpression) lambda.getExpression();
	XAbstractFeatureCall string = (XAbstractFeatureCall) innerBody.getExpressions().get(0);
	assertEquals("bug400807.Bug400807Param.getString()", string.getFeature().getIdentifier());
}
 
Example #8
Source File: XbaseFormatter2.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * checks whether the given lambda should be formatted as a block.
 * That includes newlines after and before the brackets, and a fresh line for each expression.
 */
protected boolean isMultilineLambda(final XClosure closure) {
  final ILeafNode closingBracket = this._nodeModelAccess.nodeForKeyword(closure, "]");
  HiddenLeafs _hiddenLeafsBefore = null;
  if (closingBracket!=null) {
    _hiddenLeafsBefore=this._hiddenLeafAccess.getHiddenLeafsBefore(closingBracket);
  }
  boolean _tripleNotEquals = (_hiddenLeafsBefore != null);
  if (_tripleNotEquals) {
    int _newLines = this._hiddenLeafAccess.getHiddenLeafsBefore(closingBracket).getNewLines();
    return (_newLines > 0);
  }
  boolean _switchResult = false;
  XExpression _expression = closure.getExpression();
  final XExpression block = _expression;
  boolean _matched = false;
  if (block instanceof XBlockExpression) {
    _matched=true;
    _switchResult = ((((XBlockExpression)block).getExpressions().size() > 1) && this.isEachExpressionInOwnLine(((XBlockExpression)block).getExpressions()));
  }
  if (!_matched) {
    _switchResult = false;
  }
  return _switchResult;
}
 
Example #9
Source File: LinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug345433_02() throws Exception {
	String classAsString = 
		"import static extension org.eclipse.xtext.GrammarUtil.*\n" +
		"class Foo {" +
		"	org.eclipse.xtext.Grammar grammar\n" +
		"	def function1() {\n" + 
		"		grammar.containedRuleCalls.filter(e0 | " +
		"			!e0.isAssigned() && !e0.isEObjectRuleCall()" +
		"		).map(e1 | e1.rule)\n" + 
		"	}\n" +
		"}";
	XtendClass clazz = clazz(classAsString);
	IResourceValidator validator = ((XtextResource) clazz.eResource()).getResourceServiceProvider().getResourceValidator();
	List<Issue> issues = validator.validate(clazz.eResource(), CheckMode.ALL, CancelIndicator.NullImpl);
	assertTrue("Resource contained errors : " + issues.toString(), issues.isEmpty());
	XtendFunction function = (XtendFunction) clazz.getMembers().get(1);
	XExpression body = function.getExpression();
	LightweightTypeReference bodyType = getType(body);
	assertEquals("java.lang.Iterable<org.eclipse.xtext.AbstractRule>", bodyType.getIdentifier());
	XBlockExpression block = (XBlockExpression) body;
	XMemberFeatureCall featureCall = (XMemberFeatureCall) block.getExpressions().get(0);
	XClosure closure = (XClosure) featureCall.getMemberCallArguments().get(0);
	JvmFormalParameter e1 = closure.getFormalParameters().get(0);
	assertEquals("e1", e1.getSimpleName());
	assertEquals("org.eclipse.xtext.RuleCall", getType(e1).getIdentifier());
}
 
Example #10
Source File: XbaseFormatter2.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Iterable<XExpression> explicitParams(final List<XExpression> params) {
  Iterable<XExpression> _xblockexpression = null;
  {
    final XClosure builder = this.builder(params);
    Iterable<XExpression> _xifexpression = null;
    if ((builder != null)) {
      int _size = params.size();
      int _minus = (_size - 1);
      _xifexpression = IterableExtensions.<XExpression>take(params, _minus);
    } else {
      _xifexpression = params;
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #11
Source File: XbaseFormatter2.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected XClosure builder(final List<XExpression> params) {
  XClosure _xifexpression = null;
  XExpression _last = IterableExtensions.<XExpression>last(params);
  boolean _tripleNotEquals = (_last != null);
  if (_tripleNotEquals) {
    XClosure _xblockexpression = null;
    {
      INode _nodeForEObject = this._nodeModelAccess.nodeForEObject(IterableExtensions.<XExpression>last(params));
      final EObject grammarElement = ((ICompositeNode) _nodeForEObject).getFirstChild().getGrammarElement();
      XClosure _xifexpression_1 = null;
      if (((Objects.equal(grammarElement, this._xbaseGrammarAccess.getXMemberFeatureCallAccess().getMemberCallArgumentsXClosureParserRuleCall_1_1_4_0()) || 
        Objects.equal(grammarElement, this._xbaseGrammarAccess.getXFeatureCallAccess().getFeatureCallArgumentsXClosureParserRuleCall_4_0())) || 
        Objects.equal(grammarElement, this._xbaseGrammarAccess.getXConstructorCallAccess().getArgumentsXClosureParserRuleCall_5_0()))) {
        XExpression _last_1 = IterableExtensions.<XExpression>last(params);
        _xifexpression_1 = ((XClosure) _last_1);
      }
      _xblockexpression = _xifexpression_1;
    }
    _xifexpression = _xblockexpression;
  }
  return _xifexpression;
}
 
Example #12
Source File: XbaseFormatter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Iterable<XExpression> explicitParams(final List<XExpression> params) {
  Iterable<XExpression> _xblockexpression = null;
  {
    final XClosure builder = this.builder(params);
    Iterable<XExpression> _xifexpression = null;
    if ((builder != null)) {
      int _size = params.size();
      int _minus = (_size - 1);
      _xifexpression = IterableExtensions.<XExpression>take(params, _minus);
    } else {
      _xifexpression = params;
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #13
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns false if the argument expression is a lambda and the expected type
 * of the argument is not a function type or {@link Object}.
 * Returns true in all other cases.
 * 
 * This serves as a shortcut to rule out decision path's where a method is overloaded
 * and one of the overloads accepts a function type but the other doesn't. In those cases
 * it is not necessary to compute the type of the lamdba expression twice.
 * 
 * An example for this pattern is {@link IterableExtensions#filter(Iterable, Class)} vs
 * {@link IterableExtensions#filter(Iterable, org.eclipse.xtext.xbase.lib.Functions.Function1)}.
 */
protected boolean isPossibleFunctionType(int idx) {
	if (idx < arguments.getArgumentCount()) {
		XExpression argument = arguments.getArgument(idx);
		if (argument instanceof XClosure) {
			XClosure closure = (XClosure) argument;
			LightweightTypeReference declaredType = arguments.getDeclaredTypeForLambda(idx);
			if (declaredType != null && !declaredType.isType(Object.class)) {
				CommonTypeComputationServices services = getState().getReferenceOwner().getServices();
				JvmOperation operation = services.getFunctionTypes().findImplementingOperation(declaredType);
				if (operation == null) {
					return false;
				}
				if (closure.isExplicitSyntax() && closure.getDeclaredFormalParameters().size() != operation.getParameters().size()) {
					return false;
				}
			}
		}
	}
	return true;
}
 
Example #14
Source File: XbaseSemanticSequencer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isXShortClosure(List<?> values, EReference reference, INodesForEObjectProvider nodes) {
	if (values.isEmpty() || values.size() > 2 || !(values.get(0) instanceof XClosure))
		return false;
	XClosure closure = (XClosure) values.get(0);
	if (!closure.isExplicitSyntax())
		return false;
	INode node = nodes.getNodeForMultiValue(reference, 0, 0, closure);
	if (node != null) {
		if (node.getGrammarElement() instanceof RuleCall)
			return ((RuleCall) node.getGrammarElement()).getRule() == grammarAccess.getXShortClosureRule();
		if (node.getGrammarElement() instanceof Action)
			return node.getGrammarElement() == grammarAccess.getXShortClosureAccess().getXClosureAction_0_0_0();
		return false;
	}
	return true;
}
 
Example #15
Source File: XbaseSemanticSequencer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isBuilderSyntax(List<?> values, EReference reference, INodesForEObjectProvider nodes) {
	if (values.isEmpty())
		return false;
	int lastIndex = values.size() - 1;
	Object lastValue = values.get(lastIndex);
	if (!(lastValue instanceof XClosure))
		return false;
	INode node = nodes.getNodeForMultiValue(reference, lastIndex, lastIndex, values.get(lastIndex));
	if (node != null) {
		if (node.getGrammarElement() instanceof RuleCall)
			return ((RuleCall) node.getGrammarElement()).getRule() == grammarAccess.getXClosureRule();
		if (node.getGrammarElement() instanceof Action) 
			return node.getGrammarElement() == grammarAccess.getXClosureAccess().getXClosureAction_0_0_0();
		return false;
	}
	return true;
}
 
Example #16
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean canCompileToJavaLambda(XClosure closure, LightweightTypeReference typeRef, JvmOperation operation) {
	if (!typeRef.isInterfaceType())
		return false;
	
	if (!operation.getTypeParameters().isEmpty())
		return false;
	
	TreeIterator<EObject> iterator = closure.eAllContents();
	JvmType jvmType = typeRef.getType();
	while (iterator.hasNext()) {
		EObject obj = iterator.next();
		if (obj instanceof XClosure) {
			iterator.prune();
		} else if (obj instanceof XFeatureCall && isReferenceToSelf((XFeatureCall) obj, jvmType)) {
			return false;
		}
	}
	return true;
}
 
Example #17
Source File: ReorderedFeatureCallArgumentsTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test_01() {
  final IFeatureCallArguments arguments = this.toArgumentsWithoutReceiver("String s, int i", "[], 1");
  Assert.assertEquals(2, arguments.getArgumentCount());
  Assert.assertTrue(arguments.hasUnprocessedArguments());
  final IFeatureCallArgumentSlot firstSlot = arguments.getNextUnprocessedArgumentSlot();
  Assert.assertFalse(firstSlot.isVarArg());
  Assert.assertFalse(firstSlot.isSuperfluous());
  XExpression _argumentExpression = firstSlot.getArgumentExpression();
  Assert.assertTrue((_argumentExpression instanceof XNumberLiteral));
  Assert.assertEquals("int", firstSlot.getDeclaredType().getSimpleName());
  Assert.assertFalse(arguments.isProcessed(0));
  firstSlot.markProcessed();
  Assert.assertTrue(arguments.isProcessed(0));
  Assert.assertTrue(arguments.hasUnprocessedArguments());
  final IFeatureCallArgumentSlot secondSlot = arguments.getNextUnprocessedArgumentSlot();
  Assert.assertFalse(secondSlot.isVarArg());
  Assert.assertFalse(secondSlot.isSuperfluous());
  XExpression _argumentExpression_1 = secondSlot.getArgumentExpression();
  Assert.assertTrue((_argumentExpression_1 instanceof XClosure));
  Assert.assertEquals("String", secondSlot.getDeclaredType().getSimpleName());
  Assert.assertFalse(arguments.isProcessed(1));
  secondSlot.markProcessed();
  Assert.assertTrue(arguments.isProcessed(1));
  Assert.assertFalse(arguments.hasUnprocessedArguments());
}
 
Example #18
Source File: SARLValidator.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Check if the closure parameters have a valid name.
 *
 * @param closure the closure to test.
 * @see SARLFeatureNameValidator
 */
@Check(CheckType.NORMAL)
public void checkParameterName(XClosure closure) {
	int index = 0;
	for (final JvmFormalParameter param : closure.getDeclaredFormalParameters()) {
		final QualifiedName name = Utils.getQualifiedName(param);
		if (isReallyDisallowedName(name)) {
			error(MessageFormat.format(
					Messages.SARLValidator_41,
					param.getName(), Messages.SARLValidator_14),
					closure,
					XbasePackage.Literals.XCLOSURE__DECLARED_FORMAL_PARAMETERS,
					index,
					VARIABLE_NAME_DISALLOWED);
		} else if (this.grammarAccess.getOccurrenceKeyword().equals(param.getName())) {
			error(MessageFormat.format(
					Messages.SARLValidator_101,
					this.grammarAccess.getOccurrenceKeyword(), Messages.SARLValidator_14),
					closure,
					XbasePackage.Literals.XCLOSURE__DECLARED_FORMAL_PARAMETERS,
					index,
					VARIABLE_NAME_DISALLOWED);
		}
		++index;
	}
}
 
Example #19
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testShortClosure_1() throws Exception {
	XFeatureCall featureCall = (XFeatureCall) expression("foo(a,b|a+b)");
	assertEquals(1, featureCall.getExplicitArguments().size());
	assertTrue(featureCall.getExplicitArguments().get(0) instanceof XClosure);
	XClosure closure = (XClosure) featureCall.getExplicitArguments().get(0);
	assertEquals(2, closure.getFormalParameters().size());
}
 
Example #20
Source File: XbaseTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testClosure_04() throws Exception {
	XBlockExpression block = (XBlockExpression) expression(
			"{\n" + 
			"  var java.util.List<? super String> list = null;\n" + 
			"  list.map(e|e == null)\n" +
			"}");
	XMemberFeatureCall featureCall = (XMemberFeatureCall) block.getExpressions().get(1);
	XClosure closure = (XClosure) featureCall.getMemberCallArguments().get(0);
	LightweightTypeReference typeRef = getType(closure);
	assertEquals("(java.lang.Object)=>boolean", toString(typeRef));
}
 
Example #21
Source File: ParameterContextInformationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected XExpression getContainerCall(EObject element) {
	if (element == null || element instanceof XClosure)
		return null;
	else if (element instanceof XConstructorCall || element instanceof XFeatureCall
			|| element instanceof XMemberFeatureCall)
		return (XExpression) element;
	else 
		return getContainerCall(element.eContainer());
}
 
Example #22
Source File: LinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testFeatureScope_3() throws Exception {
	XtendFile file = file ("import java.lang.String class X { def String foo(String foo) {[String foo|foo]}}");
	XtendClass xClass = ((XtendClass) file.getXtendTypes().get(0));
	XtendFunction func  = (XtendFunction) xClass.getMembers().get(0);
	XClosure closure = (XClosure) ((XBlockExpression)func.getExpression()).getExpressions().get(0);
	XAbstractFeatureCall featureCall1 = (XAbstractFeatureCall) (((XBlockExpression)closure.getExpression()).getExpressions().get(0));
	assertEquals(closure.getFormalParameters().get(0), featureCall1.getFeature());
}
 
Example #23
Source File: SarlCompiler.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected ITreeAppendable toAnonymousClass(XClosure closure, ITreeAppendable appendable, LightweightTypeReference type,
		JvmOperation operation) {
	// This function is implemented in order to generate static inner class when the closure
	// cannot be represented neither by a Java 8 lambda nor a not-static inner class.
	// It solves the issues related to the serialization and deserialization of the closures.
	if (canBeNotStaticAnonymousClass(closure, type, operation)
			|| Strings.isEmpty(getVarName(type, appendable))) {
		return super.toAnonymousClass(closure, appendable, type, operation);
	}
	return toSerializableAnonymousClass(closure, appendable, type, operation);
}
 
Example #24
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object _doEvaluate(XClosure closure, IEvaluationContext context, CancelIndicator indicator) {
	Class<?> functionIntf = null;
	switch (closure.getFormalParameters().size()) {
		case 0:
			functionIntf = getClass(Functions.Function0.class);
			break;
		case 1:
			functionIntf = getClass(Functions.Function1.class);
			break;
		case 2:
			functionIntf = getClass(Functions.Function2.class);
			break;
		case 3:
			functionIntf = getClass(Functions.Function3.class);
			break;
		case 4:
			functionIntf = getClass(Functions.Function4.class);
			break;
		case 5:
			functionIntf = getClass(Functions.Function5.class);
			break;
		case 6:
			functionIntf = getClass(Functions.Function6.class);
			break;
		default:
			throw new IllegalStateException("Closures with more then 6 parameters are not supported.");
	}
	ClosureInvocationHandler invocationHandler = new ClosureInvocationHandler(closure, context, this, indicator);
	Object proxy = Proxy.newProxyInstance(classLoader, new Class<?>[] { functionIntf }, invocationHandler);
	return proxy;
}
 
Example #25
Source File: PyExpressionGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Generate the given object.
 *
 * @param closure the closure.
 * @param it the target for the generated content.
 * @param context the context.
 * @return the closure.
 */
@SuppressWarnings("static-method")
protected XExpression _generate(XClosure closure, IAppendable it, IExtraLanguageGeneratorContext context) {
	if (it.hasName(closure)) {
		appendReturnIfExpectedReturnedExpression(it, context);
		it.append(it.getName(closure)).append("()"); //$NON-NLS-1$
	}
	return closure;
}
 
Example #26
Source File: SarlCompiler.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected void _toJavaStatement(XClosure closure, ITreeAppendable appendable, boolean isReferenced) {
	// This function is implemented in order to generate static inner class when the closure
	// cannot be represented neither by a Java 8 lambda nor a not-static inner class.
	// It solves the issues related to the serialization and deserialization of the closures.
	final LightweightTypeReference type = getLightweightType(closure);
	final JvmOperation operation = findImplementingOperation(type);
	if (!canCompileToJavaLambda(closure, type, operation) && !canBeNotStaticAnonymousClass(closure, type, operation)) {
		toSerializableAnonymousClassProxyDefinition(closure, appendable, type, operation);
	}
	super._toJavaStatement(closure, appendable, isReferenced);
}
 
Example #27
Source File: AbstractXbaseLinkingTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testShadowing_7() throws Exception {
	XBlockExpression bop = (XBlockExpression) expression(
			"{" +
			"	val size = 23;" +
			"	[String size| [String x|size]];" +
			"}");
	XClosure closure = (XClosure)bop.getExpressions().get(1);
	assertSame(closure.getFormalParameters().get(0), ((XFeatureCall)((XBlockExpression)((XClosure)((XBlockExpression)closure.getExpression()).getExpressions().get(0)).getExpression()).getExpressions().get(0)).getFeature());
}
 
Example #28
Source File: AbstractXbaseLinkingTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testRecursiveClosure() throws Exception {
	XBlockExpression block = (XBlockExpression) expression("{ val (int)=>int fun = [ fun.apply(it) ] }");
	XVariableDeclaration variable = (XVariableDeclaration) block.getExpressions().get(0);
	XClosure closure = (XClosure) variable.getRight();
	XBlockExpression body = (XBlockExpression) closure.getExpression();
	XMemberFeatureCall member = (XMemberFeatureCall) body.getExpressions().get(0);
	XFeatureCall recursive = (XFeatureCall) member.getMemberCallTarget();
	assertSame(variable, recursive.getFeature());
}
 
Example #29
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testClosure_5() throws Exception {
	XClosure closure = (XClosure) expression("[(String) => String mapper|mapper('something')]");
	assertTrue(((XBlockExpression)closure.getExpression()).getExpressions().get(0) instanceof XFeatureCall);
	JvmFormalParameter formalParameter = closure.getFormalParameters().get(0);
	assertEquals("mapper", formalParameter.getName());
	assertTrue(formalParameter.getParameterType() instanceof XFunctionTypeRef);
}
 
Example #30
Source File: Oven.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void fireproof(String input) throws Exception {
	try {
		EObject file = parseHelper.parse(input);
		IResolvedTypes resolvedTypes = typeResolver.resolveTypes(file);
		Assert.assertNotNull(resolvedTypes);
		if (file != null) {
			TreeIterator<EObject> allContents = file.eAllContents();
			while (allContents.hasNext()) {
				EObject content = allContents.next();
				if (content instanceof XAbstractFeatureCall) {
					assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
					XAbstractFeatureCall abstractFeatureCall = (XAbstractFeatureCall) content;
					if (abstractFeatureCall.getImplicitReceiver() != null) {
						assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitReceiver(),
								resolvedTypes);
					}
					if (abstractFeatureCall.getImplicitFirstArgument() != null) {
						assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitFirstArgument(),
								resolvedTypes);
					}
				} else if (content instanceof XClosure) {
					assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
					for (JvmFormalParameter it : ((XClosure) content).getImplicitFormalParameters()) {
						assertIdentifiableTypeIsResolved(it, resolvedTypes);
					}
				} else if (content instanceof XExpression) {
					assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
				} else if (content instanceof JvmIdentifiableElement) {
					assertIdentifiableTypeIsResolved(((JvmIdentifiableElement) content), resolvedTypes);
				}
			}
		}
	} catch (Throwable e) {
		ComparisonFailure error = new ComparisonFailure(e.getMessage(), input, "");
		error.setStackTrace(e.getStackTrace());
		throw error;
	}
}