org.eclipse.xtext.xbase.lib.Functions.Function0 Java Examples

The following examples show how to use org.eclipse.xtext.xbase.lib.Functions.Function0. 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: AbstractExpressionGenerator.java    From sarl with Apache License 2.0 6 votes vote down vote up
private void internalAppendCall(JvmIdentifiableElement calledFeature, List<Object> leftOperand,
		List<Object> receiver, String name, List<XExpression> args,
		Function0<? extends XExpression> beginOfBlock) {
	final ExtraLanguageFeatureNameConverter converter = getFeatureNameConverter(this.context);
	final ConversionResult result = converter.convertFeatureCall(name, calledFeature, leftOperand, receiver, args);
	if (result != null) {
		if (result.isFeatureRenaming()) {
			appendCall(calledFeature, leftOperand, receiver, result.toString(), args, beginOfBlock);
		} else {
			for (final Object obj : result.toComplexConversion()) {
				if (obj instanceof CharSequence) {
					this.codeReceiver.append((CharSequence) obj);
				} else if (obj instanceof JvmType) {
					this.codeReceiver.append((JvmType) obj);
				} else if (obj instanceof LightweightTypeReference) {
					this.codeReceiver.append((LightweightTypeReference) obj);
				} else if (obj instanceof XExpression) {
					AbstractExpressionGenerator.this.generate(
							(XExpression) obj, this.codeReceiver, this.context);
				}
			}
		}
	}
}
 
Example #2
Source File: AbstractExpressionGenerator.java    From sarl with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("checkstyle:npathcomplexity")
private void featureCalltoJavaExpression(XAbstractFeatureCall call, Function0<? extends XExpression> beginOfBlock) {
	final List<Object> leftOperand = new ArrayList<>();
	if (needMultiAssignment(call)) {
		buildLeftOperand(call, leftOperand);
	}
	final List<Object> receiver = new ArrayList<>();
	buildCallReceiver(call, getExtraLanguageKeywordProvider().getThisKeywordLambda(),
			this.referenceNameLambda, receiver);
	final JvmIdentifiableElement feature = call.getFeature();
	List<XExpression> args = null;
	if (feature instanceof JvmExecutable) {
		args = getActualArguments(call);
	}
	final String name = getCallSimpleName(
			call,
			getLogicalContainerProvider(),
			getFeatureNameProvider(),
			getExtraLanguageKeywordProvider().getNullKeywordLambda(),
			getExtraLanguageKeywordProvider().getThisKeywordLambda(),
			getExtraLanguageKeywordProvider().getSuperKeywordLambda(),
			this.referenceNameLambda2);
	internalAppendCall(feature, leftOperand, receiver, name, args, beginOfBlock);
}
 
Example #3
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public synchronized <U extends Object, V extends Object> CompletableFuture<V> runWrite(final Function0<? extends U> nonCancellable, final Function2<? super CancelIndicator, ? super U, ? extends V> request) {
  final CompletableFuture<V> result = new CompletableFuture<V>();
  try {
    result.complete(request.apply(CancelIndicator.NullImpl, nonCancellable.apply()));
  } catch (final Throwable _t) {
    if (_t instanceof Throwable) {
      final Throwable t = (Throwable)_t;
      boolean _isCancelException = this.isCancelException(t);
      if (_isCancelException) {
        result.cancel(true);
      } else {
        result.completeExceptionally(t);
      }
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
  return result;
}
 
Example #4
Source File: RequestManagerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test(timeout = 1000)
public void testRunReadAfterWrite() {
  try {
    final Function0<Object> _function = () -> {
      return null;
    };
    final Function2<CancelIndicator, Object, Integer> _function_1 = (CancelIndicator $0, Object $1) -> {
      return Integer.valueOf(this.sharedState.incrementAndGet());
    };
    this.requestManager.<Object, Integer>runWrite(_function, _function_1);
    final Function1<CancelIndicator, Integer> _function_2 = (CancelIndicator it) -> {
      return Integer.valueOf(this.sharedState.get());
    };
    final CompletableFuture<Integer> future = this.requestManager.<Integer>runRead(_function_2);
    Assert.assertEquals(1, (future.get()).intValue());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #5
Source File: RequestManagerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test(timeout = 1000, expected = ExecutionException.class)
public void testRunWriteCatchException() {
  final Runnable _function = () -> {
    try {
      final Function0<Object> _function_1 = () -> {
        throw new RuntimeException();
      };
      final Function2<CancelIndicator, Object, Object> _function_2 = (CancelIndicator $0, Object $1) -> {
        return null;
      };
      final CompletableFuture<Object> future = this.requestManager.<Object, Object>runWrite(_function_1, _function_2);
      Assert.assertEquals("Foo", future.get());
    } catch (Throwable _e) {
      throw Exceptions.sneakyThrow(_e);
    }
  };
  LoggingTester.captureLogging(Level.ALL, WriteRequest.class, _function);
  Assert.fail("unreachable");
}
 
Example #6
Source File: RequestManagerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test(timeout = 1000)
public void testRunWriteLogExceptionCancellable() {
  final Runnable _function = () -> {
    final Function0<Object> _function_1 = () -> {
      throw new RuntimeException();
    };
    final Function2<CancelIndicator, Object, Object> _function_2 = (CancelIndicator $0, Object $1) -> {
      return null;
    };
    final CompletableFuture<Object> future = this.requestManager.<Object, Object>runWrite(_function_1, _function_2);
    try {
      future.join();
    } catch (final Throwable _t) {
      if (_t instanceof Exception) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  };
  final LoggingTester.LogCapture logResult = LoggingTester.captureLogging(Level.ALL, WriteRequest.class, _function);
  logResult.assertLogEntry("Error during request:");
}
 
Example #7
Source File: RequestManagerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test(timeout = 1000)
public void testRunWriteLogExceptionNonCancellable() {
  final Runnable _function = () -> {
    final Function0<Object> _function_1 = () -> {
      return null;
    };
    final Function2<CancelIndicator, Object, Object> _function_2 = (CancelIndicator $0, Object $1) -> {
      throw new RuntimeException();
    };
    final CompletableFuture<Object> future = this.requestManager.<Object, Object>runWrite(_function_1, _function_2);
    try {
      future.join();
    } catch (final Throwable _t) {
      if (_t instanceof Exception) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  };
  final LoggingTester.LogCapture logResult = LoggingTester.captureLogging(Level.ALL, WriteRequest.class, _function);
  logResult.assertLogEntry("Error during request:");
}
 
Example #8
Source File: AnnotationProcessor.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * runs the given runnable and another thread in parallel, that sets the timeout property on the compilation unit to true
 * when the given amount of milliseconds have passed by.
 */
private Object runWithCancelIndiciator(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Runnable runnable) {
  Object _xblockexpression = null;
  {
    final AtomicBoolean isFinished = new AtomicBoolean(false);
    final Function0<Boolean> _function = () -> {
      return Boolean.valueOf(isFinished.get());
    };
    this.cancellationObserver.monitorUntil(ctx, cancelIndicator, _function);
    Object _xtrycatchfinallyexpression = null;
    try {
      runnable.run();
    } catch (final Throwable _t) {
      if (_t instanceof CancellationException) {
        _xtrycatchfinallyexpression = null;
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    } finally {
      isFinished.set(true);
    }
    _xblockexpression = _xtrycatchfinallyexpression;
  }
  return _xblockexpression;
}
 
Example #9
Source File: DirtyStateEditorValidationTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private void assertNumberOfErrorAnnotations(final XtextEditor editor, final int expectedNumber) {
  final Function0<Boolean> _function = () -> {
    int _size = this.getErrorAnnotations(editor).size();
    return Boolean.valueOf((_size == expectedNumber));
  };
  this.helper.awaitUIUpdate(_function, DirtyStateEditorValidationTest.VALIDATION_TIMEOUT);
  final List<Annotation> errors = this.getErrorAnnotations(editor);
  final Function1<Annotation, String> _function_1 = (Annotation it) -> {
    String _text = it.getText();
    String _plus = (_text + "(");
    boolean _isPersistent = it.isPersistent();
    String _plus_1 = (_plus + Boolean.valueOf(_isPersistent));
    return (_plus_1 + ")");
  };
  Assert.assertEquals(IterableExtensions.join(ListExtensions.<Annotation, String>map(errors, _function_1), ", "), expectedNumber, errors.size());
}
 
Example #10
Source File: OnTheFlyJavaCompiler2.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <RT extends Object> Function0<RT> createFunction(final String expression, final Class<RT> returnType) {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("public class __Generated implements org.eclipse.xtext.xbase.lib.Functions.Function0<");
    String _name = returnType.getName();
    _builder.append(_name);
    _builder.append("> {");
    _builder.newLineIfNotEmpty();
    _builder.append("\t");
    _builder.append("public ");
    String _name_1 = returnType.getName();
    _builder.append(_name_1, "\t");
    _builder.append(" apply() {");
    _builder.newLineIfNotEmpty();
    _builder.append("\t\t");
    _builder.append(expression, "\t\t");
    _builder.newLineIfNotEmpty();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final Class<?> clazz = this.compileToClass("__Generated", _builder.toString());
    Object _newInstance = clazz.getDeclaredConstructor().newInstance();
    return ((Function0<RT>) _newInstance);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #11
Source File: PyExpressionGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected void appendCall(JvmIdentifiableElement calledFeature, List<Object> leftOperand,
		List<Object> receiver, String name,
		List<XExpression> args, Function0<? extends XExpression> beginOfBlock) {
	if (beginOfBlock != null) {
		this.codeReceiver.append("if "); //$NON-NLS-1$
		PyExpressionGenerator.this.generate(beginOfBlock.apply(), this.codeReceiver, this.context);
		this.codeReceiver.append(" != None:"); //$NON-NLS-1$
		this.codeReceiver.increaseIndentation().newLine();
	}
	//
	appendCallPrefix(leftOperand, " = "); //$NON-NLS-1$
	appendCallPrefix(receiver, "."); //$NON-NLS-1$
	if (args != null) {
		this.codeReceiver.append(name);
		this.codeReceiver.append("("); //$NON-NLS-1$
		boolean first = true;
		for (final XExpression arg : args) {
			if (first) {
				first = false;
			} else {
				this.codeReceiver.append(", "); //$NON-NLS-1$
			}
			PyExpressionGenerator.this.generate(arg, this.codeReceiver, this.context);
		}
		this.codeReceiver.append(")"); //$NON-NLS-1$
	} else {
		this.codeReceiver.append(name);
	}
	//
	if (beginOfBlock != null) {
		this.codeReceiver.decreaseIndentation().newLine();
	}
}
 
Example #12
Source File: AbstractExpressionGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Compute the simple name for the called feature.
 *
 * @param featureCall the feature call.
 * @param logicalContainerProvider the provider of logicial container.
 * @param featureNameProvider the provider of feature name.
 * @param nullKeyword the null-equivalent keyword.
 * @param thisKeyword the this-equivalent keyword.
 * @param superKeyword the super-equivalent keyword.
 * @param referenceNameLambda replies the reference name or {@code null} if none.
 * @return the simple name.
 */
public static String getCallSimpleName(XAbstractFeatureCall featureCall,
		ILogicalContainerProvider logicalContainerProvider,
		IdentifiableSimpleNameProvider featureNameProvider,
		Function0<? extends String> nullKeyword,
		Function0<? extends String> thisKeyword,
		Function0<? extends String> superKeyword,
		Function1<? super JvmIdentifiableElement, ? extends String> referenceNameLambda) {
	String name = null;
	final JvmIdentifiableElement calledFeature = featureCall.getFeature();
	if (calledFeature instanceof JvmConstructor) {
		final JvmDeclaredType constructorContainer = ((JvmConstructor) calledFeature).getDeclaringType();
		final JvmIdentifiableElement logicalContainer = logicalContainerProvider.getNearestLogicalContainer(featureCall);
		final JvmDeclaredType contextType = ((JvmMember) logicalContainer).getDeclaringType();
		if (contextType == constructorContainer) {
			name = thisKeyword.apply();
		} else {
			name = superKeyword.apply();
		}
	} else if (calledFeature != null) {
		final String referenceName = referenceNameLambda.apply(calledFeature);
		if (referenceName != null) {
			name = referenceName;
		} else if (calledFeature instanceof JvmOperation) {
			name = featureNameProvider.getSimpleName(calledFeature);
		} else {
			name = featureCall.getConcreteSyntaxFeatureName();
		}
	}
	if (name == null) {
		return nullKeyword.apply();
	}
	return name;
}
 
Example #13
Source File: WriteRequest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public WriteRequest(RequestManager requestManager, Function0<? extends U> nonCancellable,
		Function2<? super CancelIndicator, ? super U, ? extends V> cancellable,
		CompletableFuture<Void> allPreviousRequests) {
	super(requestManager);
	this.nonCancellable = nonCancellable;
	this.cancellable = cancellable;
	this.allPreviousRequests = allPreviousRequests;
}
 
Example #14
Source File: RequestManagerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testRunWrite() {
  final Function0<Object> _function = () -> {
    return null;
  };
  final Function2<CancelIndicator, Object, Integer> _function_1 = (CancelIndicator $0, Object $1) -> {
    return Integer.valueOf(this.sharedState.incrementAndGet());
  };
  this.requestManager.<Object, Integer>runWrite(_function, _function_1).join();
  Assert.assertEquals(1, this.sharedState.get());
}
 
Example #15
Source File: OnTheFlyJavaCompiler2.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <RT extends Object> Function0<RT> createFunction(final String expression, final Class<RT> returnType) {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("public class __Generated implements org.eclipse.xtext.xbase.lib.Functions.Function0<");
    String _name = returnType.getName();
    _builder.append(_name);
    _builder.append("> {");
    _builder.newLineIfNotEmpty();
    _builder.append("\t");
    _builder.append("public ");
    String _name_1 = returnType.getName();
    _builder.append(_name_1, "\t");
    _builder.append(" apply() {");
    _builder.newLineIfNotEmpty();
    _builder.append("\t\t");
    _builder.append(expression, "\t\t");
    _builder.newLineIfNotEmpty();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final Class<?> clazz = this.compileToClass("__Generated", _builder.toString());
    Object _newInstance = clazz.getDeclaredConstructor().newInstance();
    return ((Function0<RT>) _newInstance);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #16
Source File: EvaluationCompilerTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Functions.Function0<Object> compile(String code) {
	String javaCode = compileToJavaCode(code);
	try {
		Function0<Object> function = javaCompiler.createFunction(javaCode, Object.class);
		return function;
	} catch (Exception e) {
		throw new RuntimeException("Java compilation failed. Java code was : \n" + javaCode, e);
	}
}
 
Example #17
Source File: LightweightTypeReferenceSerializerTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testFunctionType1() {
  FunctionTypeReference _newFunctionTypeReference = this.getOwner().newFunctionTypeReference(this.type(Function0.class));
  final Procedure1<FunctionTypeReference> _function = (FunctionTypeReference it) -> {
    it.setReturnType(this.typeRef(String.class));
    it.addTypeArgument(this.typeRef(String.class));
  };
  this.assertInJava(this.assertInXtend(ObjectExtensions.<FunctionTypeReference>operator_doubleArrow(_newFunctionTypeReference, _function), "()=>java.lang.String"), "org.eclipse.xtext.xbase.lib.Functions$Function0<java.lang.String>");
}
 
Example #18
Source File: HttpSessionWrapper.java    From xtext-web with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T> T get(Object key, Function0<? extends T> factory) {
	synchronized (session) {
		T sessionValue = get(key);
		if (sessionValue != null) {
			return sessionValue;
		} else {
			T factoryValue = factory.apply();
			put(key, factoryValue);
			return factoryValue;
		}
	}
}
 
Example #19
Source File: HashMapSession.java    From xtext-web with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T extends Object> T get(Object key, Function0<? extends T> factory) {
	synchronized (this.map) {
		T sessionValue = this.<T>get(key);
		if (sessionValue != null) {
			return sessionValue;
		} else {
			T factoryValue = factory.apply();
			put(key, factoryValue);
			return factoryValue;
		}
	}
}
 
Example #20
Source File: HashMapSession.java    From xtext-web with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T extends Object> T get(Object key, Function0<? extends T> factory) {
	synchronized (this.map) {
		T sessionValue = this.<T>get(key);
		if (sessionValue != null) {
			return sessionValue;
		} else {
			T factoryValue = factory.apply();
			put(key, factoryValue);
			return factoryValue;
		}
	}
}
 
Example #21
Source File: FunctionExtensions.java    From xtext-lib with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Curries a function that takes one argument.
 * 
 * @param function
 *            the original function. May not be <code>null</code>.
 * @param argument
 *            the fixed argument.
 * @return a function that takes no arguments. Never <code>null</code>.
 */
@Pure
public static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) {
	if (function == null)
		throw new NullPointerException("function");
	return new Function0<RESULT>() {
		@Override
		public RESULT apply() {
			return function.apply(argument);
		}
	};
}
 
Example #22
Source File: AnnotationProcessor.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public Future<?> monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0<? extends Boolean> isFinished) {
  Future<?> _xblockexpression = null;
  {
    final Runnable _function = () -> {
      try {
        while ((!(isFinished.apply()).booleanValue())) {
          {
            boolean _isCanceled = cancelIndicator.isCanceled();
            if (_isCanceled) {
              CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit();
              _compilationUnit.setCanceled(true);
              return;
            }
            Thread.sleep(100);
          }
        }
      } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
      }
    };
    final Runnable r = _function;
    Future<?> _xtrycatchfinallyexpression = null;
    try {
      _xtrycatchfinallyexpression = this.pool.submit(r);
    } catch (final Throwable _t) {
      if (_t instanceof RejectedExecutionException) {
        final RejectedExecutionException e = (RejectedExecutionException)_t;
        AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e);
        new Thread(r).start();
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
    _xblockexpression = _xtrycatchfinallyexpression;
  }
  return _xblockexpression;
}
 
Example #23
Source File: PyKeywordProvider.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Override
public Function0<? extends String> getNullKeywordLambda() {
	return () -> NONE_KEYWORD;
}
 
Example #24
Source File: PyKeywordProvider.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Override
public Function0<? extends String> getSuperKeywordLambda() {
	return () -> SUPER_KEYWORD;
}
 
Example #25
Source File: PyKeywordProvider.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Override
public Function0<? extends String> getThisKeywordLambda() {
	return () -> SELF_KEYWORD;
}
 
Example #26
Source File: OnTheFlyJavaCompiler.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <RT> Functions.Function0<RT> createFunction(String expression,
		Class<RT> returnType) {
	return (Function0<RT>) internalCreateFunction(expression, returnType);
}
 
Example #27
Source File: LightweightTypeReferenceSerializerTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testFunctionType() {
  this.assertInJava(this.assertInXtend(this.getOwner().newFunctionTypeReference(this.type(Function0.class)), "()=>void"), "org.eclipse.xtext.xbase.lib.Functions$Function0");
}
 
Example #28
Source File: AbstractExpressionGenerator.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Compute the list of object that serve as the receiver for the given call.
 *
 * @param call the feature call to analyze.
 * @param output the objects that constitute the call's receiver.
 * @param thisKeyword the "this" keyword.
 * @param referenceNameDefinition replies the name of the expression, if defined.
 * @return {@code true} if a receiver was found; otherwise {@code false}.
 */
public static boolean buildCallReceiver(XAbstractFeatureCall call, Function0<? extends String> thisKeyword,
		Function1<? super XExpression, ? extends String> referenceNameDefinition, List<Object> output) {
	if (call.isStatic()) {
		if (call instanceof XMemberFeatureCall) {
			final XMemberFeatureCall memberFeatureCall = (XMemberFeatureCall) call;
			if (memberFeatureCall.isStaticWithDeclaringType()) {
				final XAbstractFeatureCall target = (XAbstractFeatureCall) memberFeatureCall.getMemberCallTarget();
				final JvmType declaringType = (JvmType) target.getFeature();
				output.add(declaringType);
				return true;
			}
		}
		output.add(((JvmFeature) call.getFeature()).getDeclaringType());
		return true;
	}
	final XExpression receiver = call.getActualReceiver();
	if (receiver == null) {
		return false;
	}
	final XExpression implicit = call.getImplicitReceiver();
	if (receiver == implicit) {
		output.add(thisKeyword.apply());
	} else {
		output.add(receiver);
		if (receiver instanceof XAbstractFeatureCall) {
			// some local types have a reference name bound to the empty string
			// which is the reason why we have to check for an empty string as a valid
			// reference name here
			// see AnonymousClassCompilerTest.testCapturedLocalVar_04
			// if it turns out that we have to deal with generics there too, we may
			// have to create a field in the synthesized local class with a unique
			// name that points to 'this'
			if (((XAbstractFeatureCall) receiver).getFeature() instanceof JvmType) {
				final String referenceName = referenceNameDefinition.apply(receiver);
				if (referenceName != null && referenceName.length() == 0) {
					return false;
				}
			}
		}
	}
	return true;
}
 
Example #29
Source File: OnTheFlyJavaCompiler.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <RT> Functions.Function0<RT> createFunction(String expression,
		Class<RT> returnType) {
	return (Function0<RT>) internalCreateFunction(expression, returnType);
}
 
Example #30
Source File: SARLCodeMiningProvider.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Add an annotation when the var/val declaration's type is implicit and inferred by the SARL compiler.
 *
 * @param resource the resource to parse.
 * @param acceptor the code mining acceptor.
 */
@SuppressWarnings({ "checkstyle:npathcomplexity" })
private <T extends EObject> void createImplicitVarValType(XtextResource resource, IAcceptor<? super ICodeMining> acceptor,
		Class<T> elementType,
		Function1<T, JvmTypeReference> getDeclaredTypeLambda,
		Function1<T, String> getInferredTypeLambda,
		Function1<T, XExpression> getExprLambda,
		Function0<Assignment> getAssignmentLambda) {
	final List<T> elements = EcoreUtil2.eAllOfType(resource.getContents().get(0), elementType);

	for (final T element : elements) {
		// inline annotation only for fields with no type
		final JvmTypeReference declaredType = getDeclaredTypeLambda.apply(element);
		final XExpression expr = getExprLambda != null ? getExprLambda.apply(element) : null;
		if (declaredType != null || (getExprLambda != null && expr == null)) {
			continue;
		}
		// get inferred type name from JVM element
		final String inferredType = getInferredTypeLambda.apply(element);
		if (Strings.isEmpty(inferredType)) {
			continue;
		}
		// find document offset for inline annotation
		final ICompositeNode node = NodeModelUtils.findActualNodeFor(element);
		final Assignment elementAssignment = getAssignmentLambda.apply();
		assert elementAssignment != null;
		for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
			final INode child = it.next();
			if (child != node) {
				final EObject grammarElement = child.getGrammarElement();
				if (grammarElement instanceof RuleCall) {
					if (elementAssignment.equals(grammarElement.eContainer())) {
						final String text = this.keywords.getColonKeyword() + " " + inferredType + " "; //$NON-NLS-1$ //$NON-NLS-2$
						final int offset = child.getPreviousSibling().getTotalOffset();
						acceptor.accept(createNewLineContentCodeMining(offset, text));
						break;
					}
				}
			}
		}
	}
}