Java Code Examples for org.eclipse.xtext.resource.EObjectDescription#create()

The following examples show how to use org.eclipse.xtext.resource.EObjectDescription#create() . 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: ImportScopeTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testRelativeImports_01() throws Exception {
	final IEObjectDescription desc1 = EObjectDescription.create(QualifiedName.create("com","foo","bar"), EcorePackage.Literals.EANNOTATION);
	final IEObjectDescription desc2 = EObjectDescription.create(QualifiedName.create("de","foo"), EcorePackage.Literals.EATTRIBUTE);
	IScope outer = new SimpleScope(newArrayList(desc1,desc2), false);
	ImportNormalizer n1 = new ImportNormalizer(QualifiedName.create("com"), true, false);
	ImportNormalizer n2 = new ImportNormalizer(QualifiedName.create("de"), true, false);
	outer = new TestableImportScope(newArrayList(n1,n2), outer, new ScopeBasedSelectable(outer), EcorePackage.Literals.EOBJECT, false);
	
	n1 = new ImportNormalizer(QualifiedName.create("foo"), true, false);
	n2 = new ImportNormalizer(QualifiedName.create("foo"), false, false);
	TestableImportScope scope = new TestableImportScope(newArrayList(n1,n2), outer, new ScopeBasedSelectable(outer), EcorePackage.Literals.EOBJECT, false);
	
	final Iterable<IEObjectDescription> elements = scope.getAllElements();
	Iterator<IEObjectDescription> iterator = elements.iterator();
	assertEquals("bar", iterator.next().getName().toString());
	assertEquals("foo", iterator.next().getName().toString());
	assertEquals("foo.bar", iterator.next().getName().toString());
	assertSame(desc1,iterator.next());
	assertSame(desc2,iterator.next());
	assertFalse(iterator.hasNext());
}
 
Example 2
Source File: NestedTypeLiteralScope.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected List<IEObjectDescription> getLocalElementsByName(QualifiedName name) {
	XAbstractFeatureCall featureCall = getFeatureCall();
	if (featureCall.isExplicitOperationCallOrBuilderSyntax())
		return Collections.emptyList();
	if (rawEnclosingType instanceof JvmDeclaredType && name.getSegmentCount() == 1) {
		String singleSegment = name.getFirstSegment();
		List<String> lookup = Collections.singletonList(singleSegment);
		if (singleSegment.indexOf('$') != -1) {
			lookup = Strings.split(singleSegment, '$');
		}
		JvmType result = findNestedType((JvmDeclaredType)rawEnclosingType, lookup.iterator());
		if (result != null) {
			IEObjectDescription description = EObjectDescription.create(name, result);
			return Collections.<IEObjectDescription>singletonList(new TypeLiteralDescription(description, enclosingType, isVisible(result)));
		}
	}
	return Collections.emptyList();
}
 
Example 3
Source File: SerializerScopeProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected IScope doGetTypeScope(XMemberFeatureCall call, JvmType type) {
	if (call.isPackageFragment()) {
		if (type instanceof JvmDeclaredType) {
			int segmentIndex = countSegments(call);
			String packageName = ((JvmDeclaredType) type).getPackageName();
			List<String> splitted = Strings.split(packageName, '.');
			String segment = splitted.get(segmentIndex);
			return new SingletonScope(EObjectDescription.create(segment, type), IScope.NULLSCOPE);
		}
		return IScope.NULLSCOPE;
	} else {
		if (type instanceof JvmDeclaredType && ((JvmDeclaredType) type).getDeclaringType() == null) {
			return new SingletonScope(EObjectDescription.create(type.getSimpleName(), type), IScope.NULLSCOPE);
		} else {
			XAbstractFeatureCall target = (XAbstractFeatureCall) call.getMemberCallTarget();
			if (target.isPackageFragment()) {
				String qualifiedName = type.getQualifiedName();
				int dot = qualifiedName.lastIndexOf('.');
				String simpleName = qualifiedName.substring(dot + 1);
				return new SingletonScope(EObjectDescription.create(simpleName, type), IScope.NULLSCOPE);
			} else {
				return new SingletonScope(EObjectDescription.create(type.getSimpleName(), type), IScope.NULLSCOPE);	
			}
		}
	}
}
 
Example 4
Source File: EcoreResourceDescriptionStrategy.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean createEObjectDescriptions(IQualifiedNameProvider qualifiedNameProvider, boolean isNsURI,
		EObject eObject, IAcceptor<IEObjectDescription> acceptor) {
	try {
		QualifiedName qualifiedName = qualifiedNameProvider.getFullyQualifiedName(eObject);
		if (qualifiedName != null) {
			Map<String, String> userData = Maps.newHashMapWithExpectedSize(1);
			userData.put(NS_URI_INDEX_ENTRY, Boolean.toString(isNsURI));
			IEObjectDescription description = EObjectDescription.create(qualifiedName, eObject, userData);
			acceptor.accept(description);
			return true;
		}
	} catch (Exception exc) {
		LOG.error(exc.getMessage(), exc);
	}
	return false;
}
 
Example 5
Source File: UnionMemberScope.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected IEObjectDescription getCheckedDescription(String name, TMember member) {
	IEObjectDescription description = EObjectDescription.create(member.getName(), member);

	QualifiedName qn = QualifiedName.create(name);
	for (IScope currSubScope : subScopes) {
		IEObjectDescription subDescription = currSubScope.getSingleElement(qn);

		boolean descrWithError = subDescription == null
				|| IEObjectDescriptionWithError.isErrorDescription(subDescription);
		if (descrWithError) {
			return createComposedMemberDescriptionWithErrors(description);
		}
	}

	return description;
}
 
Example 6
Source File: KnownTypesScope.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected IEObjectDescription doGetSingleElement(QualifiedName name, String firstSegment, int dollarIndex) {
	int index = -1;
	JvmType result = null;
	for(int i = 0; i < types.size(); i++) {
		JvmType type = types.get(i);
		JvmType exactMatch = getExactMatch(type, index, name);
		if (exactMatch != null)
			return EObjectDescription.create(name, exactMatch);
		if (isMatch(i, type, firstSegment, name)) {
			JvmType resolved = getUnambiguousResult(result, index, type, i, name);
			if (resolved == null) {
				return null;
			}
			if (resolved != result) {
				result = resolved;
				index = i;
			}
		}
	}
	return toDescription(name, result, dollarIndex, index);
}
 
Example 7
Source File: SerializerScopeProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected IScope getExecutableScope(XAbstractFeatureCall call, JvmIdentifiableElement feature) {
	final String simpleName = feature.getSimpleName();
	QualifiedName name = QualifiedName.create(simpleName);
	if (call.isOperation()) {
		QualifiedName operator = getOperator(call, name);
		if (operator == null) {
			return IScope.NULLSCOPE;
		}
		return new SingletonScope(EObjectDescription.create(operator, feature), IScope.NULLSCOPE);
	}
	if (call instanceof XAssignment) {
		return getAccessorScope(simpleName, name, feature);
	}
	if (call.isExplicitOperationCallOrBuilderSyntax() || ((JvmExecutable) feature).getParameters().size() > 1
			|| (!call.isExtension() && ((JvmExecutable) feature).getParameters().size() == 1)) {
		return new SingletonScope(EObjectDescription.create(name, feature), IScope.NULLSCOPE);
	}

	return getAccessorScope(simpleName, name, feature);
}
 
Example 8
Source File: N4JSEObjectDescription.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Static factory method for {@link N4JSEObjectDescription}.
 *
 * Falls back to {@link EObjectDescription#create} if the given element is not versionable.
 */
public static IEObjectDescription create(QualifiedName qualifiedName, EObject element,
		Map<String, String> userData) {
	if (VersionableUtils.isTVersionable(element)) {
		return new N4JSEObjectDescription(qualifiedName, (TVersionable) element, userData);
	} else {
		return EObjectDescription.create(qualifiedName, element, userData);
	}
}
 
Example 9
Source File: AbstractScopeTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	resource = new ResourceImpl(URI.createURI("uri"));
	annotationA = EcoreFactory.eINSTANCE.createEAnnotation();
	annotationB = EcoreFactory.eINSTANCE.createEAnnotation();
	resource.getContents().add(annotationA);
	resource.getContents().add(annotationB);
	descriptionA = EObjectDescription.create("a", annotationA);
	descriptionA_aliased = EObjectDescription.create("aliasedA", annotationA);
	descriptionB = EObjectDescription.create("b", annotationB);
	descriptionB_as_A = EObjectDescription.create("a", annotationB);
}
 
Example 10
Source File: FeatureScopeSessionWithLocalElements.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IEObjectDescription getLocalElement(QualifiedName name) {
	JvmIdentifiableElement result = map.get(name);
	if (result != null)
		return EObjectDescription.create(name, result);
	return super.getLocalElement(name);
}
 
Example 11
Source File: ScopeTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testShadowing() throws Exception {
	IEObjectDescription a = EObjectDescription.create(QualifiedName.create("foo"),
			EcorePackage.Literals.EANNOTATION);
	IEObjectDescription b = EObjectDescription
			.create(QualifiedName.create("foo"), EcorePackage.Literals.EATTRIBUTE);
	IEObjectDescription c = EObjectDescription.create(QualifiedName.create("foo"), EcorePackage.Literals.EBYTE);
	SimpleScope outer = new SimpleScope(singleton(a), false);
	SimpleScope middle = new SimpleScope(outer, singleton(b));
	SimpleScope inner = new SimpleScope(middle, singleton(c));
	assertNull(inner.getSingleElement(EcorePackage.Literals.EANNOTATION));
}
 
Example 12
Source File: SerializerScopeProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected IScope getThisOrSuperScope(XAbstractFeatureCall call, JvmType thisOrSuper) {
	QualifiedName name = THIS;
	JvmIdentifiableElement logicalContainer = logicalContainerProvider.getNearestLogicalContainer(call);
	if (logicalContainer instanceof JvmMember) {
		JvmDeclaredType thisType = ((JvmMember) logicalContainer).getDeclaringType();
		if (thisType != thisOrSuper) {
			name = SUPER;
		}
	}
	return new SingletonScope(EObjectDescription.create(name, thisOrSuper), IScope.NULLSCOPE);
}
 
Example 13
Source File: NamesAreUniqueValidationHelperTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testErrorMessage_02() {
	EClass eClass = createEClass();
	eClass.setName("EClassName");
	IEObjectDescription description = EObjectDescription.create(QualifiedName.create(eClass.getName()), eClass);
	String errorMessage = helper.getDuplicateNameErrorMessage(description, EcorePackage.Literals.ECLASS, EcorePackage.Literals.ENAMED_ELEMENT__NAME);
	assertEquals("Duplicate EClass 'EClassName'", errorMessage);
}
 
Example 14
Source File: GlobalDescriptionLabelProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testEObjectDescription() throws Exception {
	XtextResourceSet resourceSet = new XtextResourceSet();
	Resource resource = resourceSet.createResource(URI.createPlatformResourceURI("test/test.ecore", true));
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	resource.getContents().add(ePackage);
	IEObjectDescription eObjectDescription = EObjectDescription.create("test", ePackage);
	assertEquals("test - EPackage", globalDescriptionLabelProvider.getText(eObjectDescription));
	assertNotNull(globalDescriptionLabelProvider.getImage(eObjectDescription));
}
 
Example 15
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void createClassifierProposals(AbstractMetamodelDeclaration declaration, EObject model,
		ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
	String alias = declaration.getAlias();
	QualifiedName prefix = (!Strings.isEmpty(alias)) ? QualifiedName.create(getValueConverter().toString(alias,
			grammarAccess.getValidIDRule().getName())) : null;
	boolean createDatatypeProposals = !(model instanceof AbstractElement)
			&& modelOrContainerIs(model, AbstractRule.class);
	boolean createEnumProposals = !(model instanceof AbstractElement) && modelOrContainerIs(model, EnumRule.class);
	boolean createClassProposals = modelOrContainerIs(model, ParserRule.class, CrossReference.class, Action.class);
	Function<IEObjectDescription, ICompletionProposal> factory = new DefaultProposalCreator(context, null, classifierQualifiedNameConverter);
	for (EClassifier classifier : declaration.getEPackage().getEClassifiers()) {
		if (classifier instanceof EDataType && createDatatypeProposals || classifier instanceof EEnum
				&& createEnumProposals || classifier instanceof EClass && createClassProposals) {
			String classifierName = getValueConverter().toString(classifier.getName(), grammarAccess.getValidIDRule().getName());
			QualifiedName proposalQualifiedName = (prefix != null) ? prefix.append(classifierName) : QualifiedName
					.create(classifierName);
			IEObjectDescription description = EObjectDescription.create(proposalQualifiedName, classifier);
			ConfigurableCompletionProposal proposal = (ConfigurableCompletionProposal) factory.apply(description);
			if (proposal != null) {
				if (prefix != null)
					proposal.setDisplayString(classifier.getName() + " - " + alias);
				proposal.setPriority(proposal.getPriority() * 2);
			}
			acceptor.accept(proposal);
		}
	}
}
 
Example 16
Source File: ImportScopeTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testGetAllWithDuplicates() throws Exception {
	final IEObjectDescription desc1 = EObjectDescription.create(QualifiedName.create("com","foo","bar"), EcorePackage.Literals.EANNOTATION);
	final IEObjectDescription desc2 = EObjectDescription.create(QualifiedName.create("com","foo","bar"), EcorePackage.Literals.EATTRIBUTE);
	SimpleScope outer = new SimpleScope(newArrayList(desc1,desc2), false);
	ImportNormalizer n1 = new ImportNormalizer(QualifiedName.create("com"), true, false);
	TestableImportScope scope = new TestableImportScope(newArrayList(n1), outer, new ScopeBasedSelectable(outer), EcorePackage.Literals.EOBJECT, false);
	assertEquals(4,size(scope.getAllElements()));
}
 
Example 17
Source File: N4JSResourceDescriptionStrategy.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create EObjectDescriptions for variables for which N4JSQualifiedNameProvider provides a FQN; variables with a FQN
 * of <code>null</code> (currently all non-exported variables) will be ignored.
 */
private void internalCreateEObjectDescription(TVariable variable, IAcceptor<IEObjectDescription> acceptor) {
	QualifiedName qualifiedName = qualifiedNameProvider.getFullyQualifiedName(variable);
	if (qualifiedName != null) { // e.g. non-exported variables will return null for FQN
		Map<String, String> userData = new HashMap<>();
		addAccessModifierUserData(userData, variable.getTypeAccessModifier());
		addConstUserData(userData, variable);

		IEObjectDescription eod = EObjectDescription.create(qualifiedName, variable, userData);
		acceptor.accept(eod);
	}
}
 
Example 18
Source File: AbstractKnownTypesScope.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected IEObjectDescription toDescription(QualifiedName name, JvmType result, int dollarIndex, int index) {
	return EObjectDescription.create(name, result);
}
 
Example 19
Source File: JdtBasedSimpleTypeScope.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Iterable<IEObjectDescription> internalGetAllElements() {
	IJavaProject javaProject = getTypeProvider().getJavaProject();
	if (javaProject == null)
		return Collections.emptyList();
	final List<IEObjectDescription> allScopedElements = Lists.newArrayListWithExpectedSize(25000);
	try {
		IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
		for(Class<?> clazz: Primitives.ALL_PRIMITIVE_TYPES) {
			IEObjectDescription primitive = createScopedElement(clazz.getName());
			if (primitive != null)
				allScopedElements.add(primitive);
		}
		TypeNameRequestor nameMatchRequestor = new TypeNameRequestor() {
			@Override
			public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
					char[][] enclosingTypeNames, String path) {
				StringBuilder fqName = new StringBuilder(packageName.length + simpleTypeName.length + 1);
				if (packageName.length != 0) {
					fqName.append(packageName);
					fqName.append('.');
				}
				for(char[] enclosingType: enclosingTypeNames) {
					fqName.append(enclosingType);
					fqName.append('.');
				}
				fqName.append(simpleTypeName);
				String fullyQualifiedName = fqName.toString();
				InternalEObject proxy = createProxy(fullyQualifiedName);
				Map<String, String> userData = null;
				if (enclosingTypeNames.length == 0) {
					userData = ImmutableMap.of("flags", String.valueOf(modifiers));
				} else {
					userData = ImmutableMap.of("flags", String.valueOf(modifiers), "inner", "true");
				}
				IEObjectDescription eObjectDescription = EObjectDescription.create(getQualifiedNameConverter().toQualifiedName(fullyQualifiedName), proxy, userData);
				if (eObjectDescription != null)
					allScopedElements.add(eObjectDescription);
			}
		};
		collectContents(searchScope, nameMatchRequestor);
	}
	catch (JavaModelException e) {
		// ignore
	}
	return allScopedElements;
}
 
Example 20
Source File: AbstractMemberScope.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected IEObjectDescription getSingleLocalElementByName(QualifiedName name) {
	if (name.getSegmentCount() != 1) {
		return null;
	}
	final String nameAsString = name.getFirstSegment();

	// both read/write required
	if (ExpressionExtensions.isBothReadFromAndWrittenTo(context)) {
		TMember reader = findMember(nameAsString, false, staticAccess);
		TMember writer = findMember(nameAsString, true, staticAccess);
		if (null == reader && null == writer) {
			// will be caught as error "Could not resolve reference"
			return null;
		}
		if (null == reader) {
			return new UnsatisfiedRWAccessDescription(EObjectDescription.create(writer.getName(), writer), true);
		}
		if (null == writer) {
			return new UnsatisfiedRWAccessDescription(EObjectDescription.create(reader.getName(), reader), false);
		}
		// pick arbitrarily the setter
		return createSingleElementDescription(writer);
	}

	// either read or write requirement that moreover is satisfied
	final boolean accessForWriteOperation = ExpressionExtensions.isLeftHandSide(context);
	TMember existingMember = findMember(nameAsString, accessForWriteOperation, staticAccess);
	if (existingMember != null) {
		return createSingleElementDescription(existingMember);
	}

	// wrong read/write
	existingMember = findMember(nameAsString, !accessForWriteOperation, staticAccess);
	if (existingMember != null) {

		// allowed special case: writing in the ctor to a final field that lacks init value
		final boolean isAssOfFinalInCtor = N4JSASTUtils
				.isSemiLegalAssignmentToFinalFieldInCtor(context.eContainer(), existingMember);
		final boolean isLegalAssOfFinalInCtor = isAssOfFinalInCtor && !((TField) existingMember).isHasExpression();
		if (isLegalAssOfFinalInCtor) {
			return createSingleElementDescription(existingMember);
		}

		// allowed special case: accessing a setter for read operation in context of structural field init typing
		if (structFieldInitMode && !accessForWriteOperation && existingMember instanceof TSetter) {
			return createSingleElementDescription(existingMember);
		}

		// allowed special case: wrong read/write in a mode other than N4JS
		if (jsVariantHelper.allowWrongReadWrite(context)) { // cf. sec. 13.1
			return createSingleElementDescription(existingMember);
		}

		return new WrongWriteAccessDescription(
				EObjectDescription.create(existingMember.getName(), existingMember),
				accessForWriteOperation, isAssOfFinalInCtor);
	}

	// wrong static / non-static
	existingMember = findMember(nameAsString, accessForWriteOperation, !staticAccess);
	if (existingMember == null) {
		// if both read/write access and static access are wrong, we want to
		// complain (only) about "wrong static access" -> so include this case here
		existingMember = findMember(nameAsString, !accessForWriteOperation, !staticAccess);
	}
	if (existingMember != null && !isDynamicType) {
		return new WrongStaticAccessDescription(
				EObjectDescription.create(existingMember.getName(), existingMember),
				staticAccess);
	}

	return null;
}