org.eclipse.xtext.common.types.JvmAnnotationReference Java Examples

The following examples show how to use org.eclipse.xtext.common.types.JvmAnnotationReference. 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: SourceBasedJdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testClassAnnotationValue_08() throws Exception {
	IJavaProject project = projectProvider.getJavaProject(null);
	String typeName = EmptyAbstractClass.class.getName();
	IFile javaFile = (IFile) project.getProject().findMember(new Path("src/" + typeName.replace('.', '/') + ".java"));
	assertNotNull(javaFile);
	String content = Files.readStreamIntoString(javaFile.getContents());
	try {
		String newContent = content.replace(
				"public abstract ", 
				"@TestAnnotation( classArray = { String.class, DoesNotExist.class, String.class } ) public abstract ");
		javaFile.setContents(new StringInputStream(newContent), IResource.NONE, new NullProgressMonitor());
		
		JvmDeclaredType type = (JvmDeclaredType) getTypeProvider().findTypeByName(typeName);
		List<JvmAnnotationReference> annotations = type.getAnnotations();
		assertEquals(1, annotations.size());
		JvmAnnotationReference annotation = annotations.get(0);
		assertEquals(1, annotation.getExplicitValues().size());
		JvmAnnotationValue value = annotation.getExplicitValues().get(0);
		assertTrue(value instanceof JvmTypeAnnotationValue);
		List<JvmTypeReference> typeLiterals = ((JvmTypeAnnotationValue) value).getValues();
		assertEquals(2, typeLiterals.size());
	} finally {
		javaFile.setContents(new StringInputStream(content), IResource.NONE, new NullProgressMonitor());
	}
}
 
Example #2
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private JvmAnnotationValue createAnnotationAnnotationValue(Object value) {
	JvmAnnotationAnnotationValue annotationValue = TypesFactory.eINSTANCE.createJvmAnnotationAnnotationValue();
	if (value != null) {
		InternalEList<JvmAnnotationReference> values = (InternalEList<JvmAnnotationReference>)annotationValue.getValues();
		if (value instanceof Object[]) {
			for (Object element : (Object[])value) {
				if (element instanceof IAnnotationBinding) {
					values.addUnique(createAnnotationReference((IAnnotationBinding)element));
				}
			}
		} else if (value instanceof IAnnotationBinding) {
			values.addUnique(createAnnotationReference((IAnnotationBinding)value));
		}
	}
	return annotationValue;
}
 
Example #3
Source File: LogicalContainerAwareReentrantTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void computeAnnotationTypes(ResolvedTypes resolvedTypes, IFeatureScopeSession featureScopeSession, List<JvmAnnotationReference> annotations) {
	for(JvmAnnotationReference annotation: annotations) {
		EObject sourceElement = getSourceElement(annotation);
		if (sourceElement != annotation) {
			computeTypes(resolvedTypes, featureScopeSession, sourceElement);
		} else {
			for(JvmAnnotationValue value: annotation.getExplicitValues()) {
				if (value instanceof JvmCustomAnnotationValue) {
					JvmCustomAnnotationValue custom = (JvmCustomAnnotationValue) value;
					for(Object object: custom.getValues()) {
						if (object instanceof XExpression) {
							AnnotationValueTypeComputationState state = new AnnotationValueTypeComputationState(resolvedTypes, featureScopeSession, value, (XExpression) object);
							state.computeTypes();
						}
					}
				} else if (value instanceof JvmAnnotationAnnotationValue) {
					computeAnnotationTypes(resolvedTypes, featureScopeSession, ((JvmAnnotationAnnotationValue) value).getValues());
				}
			}
		}
	}
}
 
Example #4
Source File: XtendJvmModelInferrer.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void transform(XtendEnumLiteral literal, JvmEnumerationType container) {
	if (literal.getName() == null)
		return;
	JvmEnumerationLiteral jvmLiteral = typesFactory.createJvmEnumerationLiteral();
	associator.associatePrimary(literal, jvmLiteral);
	jvmLiteral.setSimpleName(literal.getName());
	jvmLiteral.setVisibility(JvmVisibility.PUBLIC);
	jvmLiteral.setStatic(true);
	jvmLiteral.setFinal(true);
	jvmTypesBuilder.copyDocumentationTo(literal, jvmLiteral);
	for (XAnnotation anno : literal.getAnnotations()) {
		if (!annotationTranslationFilter.apply(anno))
			continue;
		JvmAnnotationReference annotationReference = jvmTypesBuilder.getJvmAnnotationReference(anno);
		if(annotationReference != null)
			jvmLiteral.getAnnotations().add(annotationReference);
	}
	container.getMembers().add(jvmLiteral);
}
 
Example #5
Source File: JvmAnnotationReferencePrinter.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected String _internalToString(JvmAnnotationReference reference) {
	StringBuilder buffer = new StringBuilder();
	buffer.append("@");
	buffer.append(createLinkWithLabel(XtextElementLinks.XTEXTDOC_SCHEME, EcoreUtil.getURI(reference.getAnnotation()), reference.getAnnotation().getSimpleName()));

	List<JvmAnnotationValue> explicitValues = reference.getExplicitValues();
	boolean needsExplicitProperties = explicitValues.size() > 1 //
			|| (!explicitValues.isEmpty() && explicitValues.get(0).getOperation() != null //
					&& !"value".equals(explicitValues.get(0).getOperation().getSimpleName()));

	if (!explicitValues.isEmpty()) {
		buffer.append("(");
		buffer.append(explicitValues.stream().map(explicitValue -> {
			StringBuilder builder = new StringBuilder();
			if (needsExplicitProperties) {
				Iterable<JvmOperation> declaredOperations = reference.getAnnotation().getDeclaredOperations();
				builder.append(createLinkToOperation(explicitValue.getOperation(), declaredOperations));
				builder.append("=");
			}
			builder.append(internalToString(explicitValue));
			return builder.toString();
		}).collect(Collectors.joining(", ")));
		buffer.append(")");
	}
	return buffer.toString();
}
 
Example #6
Source File: JvmAnnotationTargetImpl.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public AnnotationReference addAnnotation(final AnnotationReference annotationReference) {
  AnnotationReference _xblockexpression = null;
  {
    this.checkMutable();
    Preconditions.checkArgument((annotationReference != null), "annotationReference cannot be null");
    AnnotationReference _xifexpression = null;
    if ((annotationReference instanceof JvmAnnotationReferenceImpl)) {
      AnnotationReference _xblockexpression_1 = null;
      {
        final JvmAnnotationReference jvmAnnotationReference = EcoreUtil2.<JvmAnnotationReference>cloneWithProxies(((JvmAnnotationReferenceImpl)annotationReference).getDelegate());
        EList<JvmAnnotationReference> _annotations = this.getDelegate().getAnnotations();
        _annotations.add(jvmAnnotationReference);
        _xblockexpression_1 = this.getCompilationUnit().toAnnotationReference(jvmAnnotationReference);
      }
      _xifexpression = _xblockexpression_1;
    } else {
      StringConcatenation _builder = new StringConcatenation();
      _builder.append(annotationReference);
      _builder.append(" is not annotation reference");
      throw new IllegalArgumentException(_builder.toString());
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #7
Source File: AbstractTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDefaultAnnotationAnnotationValue_02() throws Exception {
	JvmAnnotationAnnotationValue value = (JvmAnnotationAnnotationValue) getDefaultAnnotationValue(
			"annotationArrayValue");
	assertEquals(2, value.getValues().size());
	JvmAnnotationReference reference1 = value.getValues().get(0);
	assertEquals(TestAnnotationWithDefaults.NestedAnnotation.class.getName(),
			reference1.getAnnotation().getIdentifier());
	JvmAnnotationValue nestedAnnotationValue1 = reference1.getValues().get(0);
	assertTrue(nestedAnnotationValue1 instanceof JvmStringAnnotationValue);
	assertEquals("AnotherString", ((JvmStringAnnotationValue) nestedAnnotationValue1).getValues().get(0));
	JvmAnnotationReference reference2 = value.getValues().get(1);
	assertEquals(TestAnnotationWithDefaults.NestedAnnotation.class.getName(),
			reference2.getAnnotation().getIdentifier());
	JvmAnnotationValue nestedAnnotationValue2 = reference2.getValues().get(0);
	assertTrue(nestedAnnotationValue2 instanceof JvmStringAnnotationValue);
	assertEquals("MyString", ((JvmStringAnnotationValue) nestedAnnotationValue2).getValues().get(0));
}
 
Example #8
Source File: AbstractTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDefaultAnnotationAnnotationValueByReference() throws Exception {
	String typeName = Bug334943Client.class.getName();
	JvmDeclaredType client = (JvmDeclaredType) getTypeProvider().findTypeByName(typeName);
	JvmOperation operation = Iterables.get(client.getDeclaredOperations(), 0);
	List<JvmAnnotationReference> annotations = operation.getAnnotations();
	assertEquals(1, annotations.size());
	JvmAnnotationReference annotation = annotations.get(0);
	for (JvmAnnotationValue value : annotation.getValues()) {
		if ("enumValue".equals(value.getValueName())) {
			JvmEnumAnnotationValue enumValue = (JvmEnumAnnotationValue) value;
			assertEquals(1, enumValue.getValues().size());
			assertEquals("FirstValue", enumValue.getValues().get(0).getSimpleName());
		}
	}
}
 
Example #9
Source File: JvmTypesBuilder.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates and returns an annotation reference of the given annotation type's name and the given value.
 * 
 * @param sourceElement
 *            the source element to associate the created element with.
 * @param annotationTypeName
 *            the type name of the created annotation.
 * @param value
 *            the value of the annotation reference. Can be <code>null</code> if the reference doesn't have any value.
 *            
 * @return a result representing an annotation reference to the given annotation type, <code>null<code> if 
 * 		sourceElement or annotationType are <code>null</code>.
 * 
 * @deprecated use {@link JvmAnnotationReferenceBuilder#annotationRef(String, String...)} instead
 */
//TODO Move up the code used in Xtend's CompilationUnitImpl so we can reuse it here.
/* @Nullable */ 
@Deprecated
public JvmAnnotationReference toAnnotation(/* @Nullable */ EObject sourceElement, /* @Nullable */ String annotationTypeName, /* @Nullable */ Object value) {
	JvmAnnotationReference result = typesFactory.createJvmAnnotationReference();
	JvmType jvmType = references.findDeclaredType(annotationTypeName, sourceElement);
	if (jvmType == null) {
		throw new IllegalArgumentException("The type "+annotationTypeName +" is not on the classpath.");
	}
	if (!(jvmType instanceof JvmAnnotationType)) {
		throw new IllegalArgumentException("The given class " + annotationTypeName + " is not an annotation type.");
	}
	result.setAnnotation((JvmAnnotationType) jvmType);
	if (value != null) {
		if (value instanceof String) {
			JvmStringAnnotationValue annotationValue = typesFactory.createJvmStringAnnotationValue();
			annotationValue.getValues().add((String) value);
			result.getExplicitValues().add(annotationValue);
		}
	}
	return result;
}
 
Example #10
Source File: AnnotationReferenceProviderImpl.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public AnnotationReference newAnnotationReference(final String annotationTypeName, final Procedure1<AnnotationReferenceBuildContext> initializer) {
  AnnotationReference _xblockexpression = null;
  {
    this.compilationUnit.checkCanceled();
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("annotationTypeName cannot be null");
    Preconditions.checkArgument((annotationTypeName != null), _builder);
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("initializer cannot be null");
    Preconditions.checkArgument((initializer != null), _builder_1);
    final JvmAnnotationReference jvmAnnotationReference = this.createJvmAnnotationReference(this.compilationUnit.getTypeReferences().findDeclaredType(annotationTypeName, this.compilationUnit.getXtendFile()));
    if ((jvmAnnotationReference == null)) {
      return null;
    }
    AnnotationReferenceBuildContextImpl _annotationReferenceBuildContextImpl = new AnnotationReferenceBuildContextImpl();
    final Procedure1<AnnotationReferenceBuildContextImpl> _function = (AnnotationReferenceBuildContextImpl it) -> {
      it.setDelegate(jvmAnnotationReference);
      it.setCompilationUnit(this.compilationUnit);
    };
    final AnnotationReferenceBuildContextImpl buildContext = ObjectExtensions.<AnnotationReferenceBuildContextImpl>operator_doubleArrow(_annotationReferenceBuildContextImpl, _function);
    initializer.apply(buildContext);
    _xblockexpression = this.compilationUnit.toAnnotationReference(jvmAnnotationReference);
  }
  return _xblockexpression;
}
 
Example #11
Source File: SARLAnnotationUtil.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Extract the type values of the given annotation, if they exist.
 *
 * @param reference the reference to the annotation.
 * @return the values of the annotation, never {@code null}.
 */
@SuppressWarnings("static-method")
public List<JvmTypeReference> findTypeValues(JvmAnnotationReference reference) {
	assert reference != null;
	final List<JvmTypeReference> values = new ArrayList<>();
	for (final JvmAnnotationValue value : reference.getValues()) {
		if (value instanceof JvmTypeAnnotationValue) {
			for (final JvmTypeReference strValue : ((JvmTypeAnnotationValue) value).getValues()) {
				if (strValue != null) {
					values.add(strValue);
				}
			}
		}
	}
	return values;
}
 
Example #12
Source File: MemberFromSuperImplementor.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void initializeExecutableBuilder(final AbstractExecutableBuilder builder, final JvmDeclaredType overrider, final IResolvedExecutable overridden) {
  final JvmExecutable executable = overridden.getDeclaration();
  builder.setContext(overrider);
  builder.setVisibility(overridden.getDeclaration().getVisibility());
  final Procedure2<LightweightTypeReference, Integer> _function = (LightweightTypeReference it, Integer index) -> {
    final JvmFormalParameter declaredParameter = executable.getParameters().get((index).intValue());
    final AbstractParameterBuilder parameterBuilder = builder.newParameterBuilder();
    parameterBuilder.setName(declaredParameter.getSimpleName());
    parameterBuilder.setType(it);
    JvmAnnotationReference _findAnnotation = this.annotationLookup.findAnnotation(declaredParameter, Extension.class);
    boolean _tripleNotEquals = (_findAnnotation != null);
    parameterBuilder.setExtensionFlag(_tripleNotEquals);
  };
  IterableExtensions.<LightweightTypeReference>forEach(overridden.getResolvedParameterTypes(), _function);
  builder.setVarArgsFlag(executable.isVarArgs());
  builder.setExceptions(overridden.getResolvedExceptions());
}
 
Example #13
Source File: XtendHoverDocumentationProviderTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void bug380551_TestLinkToNativeJavaType() {
  try {
    Assume.assumeFalse(AbstractXtendUITestCase.isJava11OrLater());
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package testpackage");
    _builder.newLine();
    _builder.append("import javax.annotation.Resource");
    _builder.newLine();
    _builder.append("@Resource");
    _builder.newLine();
    _builder.append("class Foo {");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtendFile xtendFile = this.parseHelper.parse(_builder, this.getResourceSet());
    final XtendClass clazz = IterableExtensions.<XtendClass>head(Iterables.<XtendClass>filter(xtendFile.getXtendTypes(), XtendClass.class));
    JvmGenericType _inferredType = this.jvmModelAssociations.getInferredType(clazz);
    final JvmAnnotationTarget target = ((JvmAnnotationTarget) _inferredType);
    Assert.assertNotNull(this.hoverProvider.getHoverInfo(IterableExtensions.<JvmAnnotationReference>head(target.getAnnotations()).getAnnotation()));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #14
Source File: SARLJvmModelInferrer.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Copy the annotations, except the ones given as parameters.
 *
 * @param annotations the annotations to copy.
 * @param target the target.
 * @param exceptions the annotations to skip.
 */
@SuppressWarnings("static-method")
protected void translateAnnotationsTo(List<JvmAnnotationReference> annotations, JvmAnnotationTarget target,
		Class<?>... exceptions) {
	final Set<String> excepts = new HashSet<>();
	for (final Class<?> type : exceptions) {
		excepts.add(type.getName());
	}
	final List<JvmAnnotationReference> addition = new ArrayList<>();
	for (final JvmAnnotationReference annotation : Iterables.filter(annotations, an -> {
		if (!ANNOTATION_TRANSLATION_FILTER.apply(an)) {
			return false;
		}
		return !excepts.contains(an.getAnnotation().getIdentifier());
	})) {
		addition.add(annotation);
	}
	target.getAnnotations().addAll(addition);
}
 
Example #15
Source File: ReflectionTypeFactory.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected JvmFormalParameter createFormalParameter(Type parameterType, String paramName,
		JvmMember container, GenericDeclaration member, Annotation[] annotations) {
	JvmFormalParameter result = TypesFactory.eINSTANCE.createJvmFormalParameter();
	result.setName(paramName);
	if (isLocal(parameterType, member)) {
		result.setParameterType(createLocalTypeReference(parameterType, (JvmTypeParameterDeclarator) container,
				member));
	} else {
		result.setParameterType(createTypeReference(parameterType));
	}
	if (annotations.length != 0) {
		InternalEList<JvmAnnotationReference> annotationsReferences = (InternalEList<JvmAnnotationReference>)result.getAnnotations();
		for (Annotation annotation : annotations) {
			annotationsReferences.addUnique(createAnnotationReference(annotation));
		}
	}
	return result;
}
 
Example #16
Source File: SARLAnnotationUtil.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Extract the boolean values of the given annotation, if they exist.
 *
 * @param reference the reference to the annotation.
 * @return the values of the annotation, never {@code null}.
 * @since 0.6
 */
@SuppressWarnings("static-method")
public List<Boolean> findBooleanValues(JvmAnnotationReference reference) {
	assert reference != null;
	final List<Boolean> values = new ArrayList<>();
	for (final JvmAnnotationValue value : reference.getValues()) {
		if (value instanceof JvmBooleanAnnotationValue) {
			for (final Boolean boolValue : ((JvmBooleanAnnotationValue) value).getValues()) {
				if (boolValue != null) {
					values.add(boolValue);
				}
			}
		}
	}
	return values;
}
 
Example #17
Source File: JvmTypesBuilderTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testIntegerAnnotation() {
  try {
    final XAnnotationsFactory f = XAnnotationsFactory.eINSTANCE;
    final XExpression e = this.expression("\'Foo\'");
    final XAnnotation anno = f.createXAnnotation();
    JvmType _findDeclaredType = this.references.findDeclaredType(TestAnnotation3.class, e);
    final JvmAnnotationType annotatiomType = ((JvmAnnotationType) _findDeclaredType);
    anno.setAnnotationType(annotatiomType);
    final XAnnotationElementValuePair pair = f.createXAnnotationElementValuePair();
    pair.setElement(IterableExtensions.<JvmOperation>head(annotatiomType.getDeclaredOperations()));
    pair.setValue(this.expression("10"));
    EList<XAnnotationElementValuePair> _elementValuePairs = anno.getElementValuePairs();
    this._jvmTypesBuilder.<XAnnotationElementValuePair>operator_add(_elementValuePairs, pair);
    final JvmGenericType type = this.typesFactory.createJvmGenericType();
    this._jvmTypesBuilder.addAnnotation(type, anno);
    Assert.assertEquals(anno.getAnnotationType(), IterableExtensions.<JvmAnnotationReference>head(type.getAnnotations()).getAnnotation());
    Assert.assertEquals(1, IterableExtensions.<JvmAnnotationReference>head(type.getAnnotations()).getValues().size());
    JvmAnnotationValue _head = IterableExtensions.<JvmAnnotationValue>head(IterableExtensions.<JvmAnnotationReference>head(type.getAnnotations()).getValues());
    final JvmCustomAnnotationValue value = ((JvmCustomAnnotationValue) _head);
    EObject _head_1 = IterableExtensions.<EObject>head(value.getValues());
    Assert.assertTrue((_head_1 instanceof XNumberLiteral));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #18
Source File: XAnnotationUtil.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public Set<ElementType> getAnnotationTargets(JvmAnnotationType annotation) {
	EList<JvmAnnotationReference> annotations = annotation.getAnnotations();
	for (JvmAnnotationReference annoRef : annotations) {
		if (Target.class.getName().equals(annoRef.getAnnotation().getIdentifier())) {
			EList<JvmAnnotationValue> values = annoRef.getValues();
			JvmAnnotationValue value = values.isEmpty() ? null : values.get(0);
			if (value instanceof JvmEnumAnnotationValue) {
				Set<ElementType> result = newHashSet();
				for (JvmEnumerationLiteral elementType : ((JvmEnumAnnotationValue) value).getValues()) {
					final String simpleName = elementType.getSimpleName();
					result.add(ElementType.valueOf(simpleName));
				}
				return result;
			}
		}
	}
	return emptySet();
}
 
Example #19
Source File: SARLJvmModelInferrer.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Create an annotation with classes as values.
 *
 * @param type the type of the annotation.
 * @param values the values.
 * @return the reference to the JVM annotation.
 */
private JvmAnnotationReference annotationClassRef(Class<? extends Annotation> type,
		List<? extends JvmTypeReference> values) {
	try {
		final JvmAnnotationReference annot = this._annotationTypesBuilder.annotationRef(type);
		final JvmTypeAnnotationValue annotationValue = this.services.getTypesFactory().createJvmTypeAnnotationValue();
		for (final JvmTypeReference value : values) {
			annotationValue.getValues().add(this.typeBuilder.cloneWithProxies(value));
		}
		annot.getExplicitValues().add(annotationValue);
		return annot;
	} catch (IllegalArgumentException exception) {
		// ignore
	}
	return null;
}
 
Example #20
Source File: FeatureCallCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void featureCalltoJavaExpression(final XAbstractFeatureCall call, ITreeAppendable b, boolean isExpressionContext) {
	if (call instanceof XAssignment) {
		assignmentToJavaExpression((XAssignment) call, b, isExpressionContext);
	} else {
		if (needMultiAssignment(call)) {
			appendLeftOperand(call, b, isExpressionContext).append(" = ");
		}
		final JvmAnnotationReference annotationRef = this.expressionHelper.findInlineAnnotation(call);
		if (annotationRef == null || !isConstantExpression(annotationRef)) {
			boolean hasReceiver = appendReceiver(call, b, isExpressionContext);
			if (hasReceiver) {
				b.append(".");
				b = appendTypeArguments(call, b);
			}
		}
		appendFeatureCall(call, b);
	}
}
 
Example #21
Source File: JvmTypesBuilderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testEmptyAnnotation() {
  try {
    final XAnnotationsFactory f = XAnnotationsFactory.eINSTANCE;
    final XExpression e = this.expression("\'Foo\'");
    final XAnnotation anno = f.createXAnnotation();
    JvmType _findDeclaredType = this.references.findDeclaredType(Inject.class, e);
    anno.setAnnotationType(((JvmAnnotationType) _findDeclaredType));
    final JvmGenericType type = this.typesFactory.createJvmGenericType();
    this._jvmTypesBuilder.addAnnotations(type, Collections.<XAnnotation>unmodifiableList(CollectionLiterals.<XAnnotation>newArrayList(anno)));
    Assert.assertEquals(anno.getAnnotationType(), IterableExtensions.<JvmAnnotationReference>head(type.getAnnotations()).getAnnotation());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #22
Source File: AbstractTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testAnnotatedParameter_06() throws Exception {
	String typeName = TestAnnotation.Annotated.class.getName();
	JvmAnnotationType annotationType = (JvmAnnotationType) getTypeProvider()
			.findTypeByName(TestAnnotation.NestedAnnotation.class.getName());
	JvmDeclaredType type = (JvmDeclaredType) getTypeProvider().findTypeByName(typeName);
	JvmOperation method = getMethodFromType(type, TestAnnotation.Annotated.class,
			"method(java.lang.String,java.lang.String,java.lang.String)");
	JvmAnnotationTarget target = method.getParameters().get(2);
	assertEquals(1, target.getAnnotations().size());
	JvmAnnotationReference annotationReference = target.getAnnotations().get(0);
	assertSame(annotationType, annotationReference.getAnnotation());
}
 
Example #23
Source File: CompilationUnitImpl.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public AnnotationReference toAnnotationReference(final JvmAnnotationReference delegate) {
  final Function1<JvmAnnotationReference, JvmAnnotationReferenceImpl> _function = (JvmAnnotationReference it) -> {
    JvmAnnotationReferenceImpl _jvmAnnotationReferenceImpl = new JvmAnnotationReferenceImpl();
    final Procedure1<JvmAnnotationReferenceImpl> _function_1 = (JvmAnnotationReferenceImpl it_1) -> {
      it_1.setDelegate(delegate);
      it_1.setCompilationUnit(this);
    };
    return ObjectExtensions.<JvmAnnotationReferenceImpl>operator_doubleArrow(_jvmAnnotationReferenceImpl, _function_1);
  };
  return this.<JvmAnnotationReference, JvmAnnotationReferenceImpl>getOrCreate(delegate, _function);
}
 
Example #24
Source File: AbstractTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testAnnotationWithStringDefault_02() throws Exception {
	String typeName = AnnotatedInterfaceWithStringDefault.class.getName();
	JvmDeclaredType type = (JvmDeclaredType) getTypeProvider().findTypeByName(typeName);
	List<JvmAnnotationReference> annotations = type.getAnnotations();
	assertEquals(1, annotations.size());
	JvmAnnotationReference annotationReference = annotations.get(0);
	assertEquals(TestAnnotationWithStringDefault.class.getName(),
			annotationReference.getAnnotation().getIdentifier());
	checkDefaultAnnotationValuesAnnotatedExternalClass(annotationReference);
}
 
Example #25
Source File: JvmAnnotationReferencePrinterTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
private void assertPrinted(final String expected, final String xtendCode) {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append(xtendCode);
    _builder.append(" class Foo {}");
    _builder.newLineIfNotEmpty();
    final XtendFile file = this.parseHelper.parse(_builder, this.resourceSetProvider.get(this.testHelper.getProject()));
    final JvmAnnotationReference annoVal = IterableExtensions.<JvmAnnotationReference>head(IterableExtensions.<JvmGenericType>head(Iterables.<JvmGenericType>filter(file.eResource().getContents(), JvmGenericType.class)).getAnnotations());
    Assert.assertEquals(expected, this.printer.toHtmlString(annoVal));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #26
Source File: AnnotationLookup.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public JvmAnnotationReference removeAnnotation(/* @NonNull */ JvmAnnotationTarget annotationTarget, /* @NonNull */ Class<? extends Annotation> type) {
	JvmAnnotationReference result = findAnnotation(annotationTarget, type);
	if (result != null) {
		annotationTarget.getAnnotations().remove(result);
		return result;
	}
	return null;
}
 
Example #27
Source File: AbstractTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private void doTestAnnotation_01(JvmAnnotationTarget target) {
	JvmAnnotationType annotationType = (JvmAnnotationType) getTypeProvider()
			.findTypeByName(TestAnnotation.class.getName());
	assertEquals(1, target.getAnnotations().size());
	JvmAnnotationReference annotationReference = target.getAnnotations().get(0);
	assertSame(annotationType, annotationReference.getAnnotation());
	if (isDefaultValueSupported())
		assertEquals(14, annotationReference.getExplicitValues().size());
	assertEquals(15, annotationReference.getValues().size());
}
 
Example #28
Source File: ReflectionTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected JvmTypeAnnotationValue getClassArrayAnnotationValue(JvmAnnotationReference annotationReference) {
	for(JvmAnnotationValue candidate: annotationReference.getExplicitValues()) {
		if (candidate instanceof JvmTypeAnnotationValue && candidate.getValueName().equals("classArray")) {
			return (JvmTypeAnnotationValue) candidate;
		}
	}
	fail("Cannot find annotation value 'classArray'");
	return null;
}
 
Example #29
Source File: XtendHighlightingCalculator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void highlightAnnotation(XAnnotation annotation, IHighlightedPositionAcceptor acceptor) {
	JvmType annotationType = annotation.getAnnotationType();
	if (annotationType instanceof JvmAnnotationTarget) {
		for(JvmAnnotationReference annotationReference: ((JvmAnnotationTarget) annotationType).getAnnotations()) {
			JvmAnnotationType otherAnnotation = annotationReference.getAnnotation();
			if (otherAnnotation != null && !otherAnnotation.eIsProxy() && Active.class.getName().equals(otherAnnotation.getIdentifier())) {
				highlightAnnotation(annotation, acceptor, ACTIVE_ANNOTATION);
				return;
			}
		}
	}
	super.highlightAnnotation(annotation, acceptor);
}
 
Example #30
Source File: JvmAnnotationReferencePrinter.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return the HTML representation for the passed {@code reference}
 * @throws NullPointerException
 *             if the {@code reference} is {@code null}
 */
public String toHtmlString(JvmAnnotationReference reference) {
	Preconditions.checkNotNull(reference);

	try {
		return internalToString(reference);
	} catch (RuntimeException e) {
		LOG.error(e.getMessage(), e);
		return reference.getAnnotation() != null ? reference.getAnnotation().getSimpleName() : null;
	}
}