Java Code Examples for org.eclipse.xtext.scoping.IScope#getSingleElement()

The following examples show how to use org.eclipse.xtext.scoping.IScope#getSingleElement() . 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: TestLanguageReferenceUpdater.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void updateReference(ITextRegionDiffBuilder rewriter, IUpdatableReference ref) {
	if (rewriter.isModified(ref.getReferenceRegion())) {
		return;
	}
	IScope scope = scopeProvider.getScope(ref.getSourceEObject(), ref.getEReference());
	ISemanticRegion region = ref.getReferenceRegion();
	QualifiedName oldName = nameConverter.toQualifiedName(region.getText());
	IEObjectDescription oldDesc = scope.getSingleElement(oldName);
	if (oldDesc != null && oldDesc.getEObjectOrProxy() == ref.getTargetEObject()) {
		return;
	}
	String newName = findValidName(ref, scope);
	if (newName != null) {
		if (oldName.getSegmentCount() > 1) {
			newName = oldName.skipLast(1).append(newName).toString();
		}
		rewriter.replace(region, newName);
	}
}
 
Example 2
Source File: ReferenceUpdater.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void updateReference(ITextRegionDiffBuilder rewriter, IUpdatableReference upd) {
	IUpdatableReference updatable = upd;
	if (rewriter.isModified(updatable.getReferenceRegion())) {
		return;
	}
	IScope scope = scopeProvider.getScope(updatable.getSourceEObject(), updatable.getEReference());
	ISemanticRegion region = updatable.getReferenceRegion();
	QualifiedName oldName = nameConverter.toQualifiedName(region.getText());
	IEObjectDescription oldDesc = scope.getSingleElement(oldName);
	if (oldDesc != null && oldDesc.getEObjectOrProxy() == updatable.getTargetEObject()) {
		return;
	}
	String newName = findValidName(updatable, scope);
	if (newName != null) {
		rewriter.replace(region, newName);
	}
}
 
Example 3
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkJavaDocRefs(XtendMember member){
	if(isIgnored(IssueCodes.JAVA_DOC_LINKING_DIAGNOSTIC))
		return;
	List<INode> documentationNodes = ((IEObjectDocumentationProviderExtension) documentationProvider).getDocumentationNodes(member);
	for(INode node : documentationNodes){
		for(ReplaceRegion region : javaDocTypeReferenceProvider.computeTypeRefRegions(node)){
			String typeRefString = region.getText();
			if(typeRefString != null && typeRefString.length() > 0){
				IScope scope = scopeProvider.getScope(member, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
				IEObjectDescription candidate = scope.getSingleElement(qualifiedNameConverter.toQualifiedName(typeRefString));
				if(candidate == null){
					Severity severity = getIssueSeverities(getContext(), getCurrentObject()).getSeverity(IssueCodes.JAVA_DOC_LINKING_DIAGNOSTIC);
					if (severity != null)
						getChain().add(createDiagnostic(severity, "javaDoc: " + typeRefString + " cannot be resolved to a type", member, region.getOffset(), region.getLength(), IssueCodes.JAVA_DOC_LINKING_DIAGNOSTIC));
				}
			}
		}
	}
}
 
Example 4
Source File: TypeLiteralScope.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();
	QualifiedName fqn = parentSegments.append(name);
	IScope typeScope = getSession().getScope(getFeatureCall(), TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE, resolvedTypes);
	IEObjectDescription typeDescription = typeScope.getSingleElement(fqn);
	if (typeDescription != null) {
		EObject type = typeDescription.getEObjectOrProxy();
		if (type instanceof JvmType)
			return Collections.<IEObjectDescription>singletonList(new TypeLiteralDescription(
					new AliasedEObjectDescription(name, typeDescription), isVisible((JvmType) type)));
	}
	return Collections.emptyList();
}
 
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: IntersectionMemberScope.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);
	boolean allDescrWithError = true;
	for (IScope currSubScope : subScopes) {
		IEObjectDescription subDescription = currSubScope.getSingleElement(qn);
		boolean descrWithError = subDescription == null
				|| IEObjectDescriptionWithError.isErrorDescription(subDescription);
		allDescrWithError &= descrWithError;
	}
	if (allDescrWithError) {
		return createComposedMemberDescriptionWithErrors(description);
	}

	return description;
}
 
Example 7
Source File: CompositeScope.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IEObjectDescription getSingleElement(EObject object) {
	IEObjectDescription result = null;
	for (IScope currScope : childScopes) {
		final IEObjectDescription currResult = currScope.getSingleElement(object);
		if (currResult != null) {
			if (!(IEObjectDescriptionWithError.isErrorDescription(currResult))) {
				return currResult; // no error, use scope order as precedence (first one wins) and return
			}
			if (result == null) {
				result = currResult; // with error, maybe we find something w/o error in following scope, do not
										// return yet
			}
		}
	}
	return result; // return null or (first) description with error
}
 
Example 8
Source File: CompositeScope.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IEObjectDescription getSingleElement(QualifiedName name) {
	IEObjectDescription result = null;
	for (IScope currScope : childScopes) {
		final IEObjectDescription currResult = currScope.getSingleElement(name);
		if (currResult != null) {
			if (!(IEObjectDescriptionWithError.isErrorDescription(currResult))) {
				return currResult; // no error, use scope order as precedence (first one wins) and return
			}
			if (result == null) {
				result = currResult; // with error, maybe we find something w/o error in following scope, do not
										// return yet
			}
		}
	}
	return result; // return null or (first) description with error
}
 
Example 9
Source File: ComposedMemberScope.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Searches for a member of the given name and for the given access in the sub-scope with index 'subScopeIdx'.
 */
private TMember findMemberInSubScope(IScope subScope, String name) {
	final IEObjectDescription currElem = subScope.getSingleElement(QualifiedName.create(name));
	if (currElem != null) {
		final EObject objOrProxy = currElem.getEObjectOrProxy();
		if (objOrProxy != null && !objOrProxy.eIsProxy() && objOrProxy instanceof TMember) {
			final TMember currM = (TMember) objOrProxy;
			return currM;
		}
	}
	return null;
}
 
Example 10
Source File: ImportsCollector.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private void addJavaDocReferences(final INode documentationNode, final ITextRegion selectedRegion, final ImportsAcceptor acceptor) {
  List<ReplaceRegion> _computeTypeRefRegions = this.javaDocTypeReferenceProvider.computeTypeRefRegions(documentationNode);
  for (final ReplaceRegion docTypeReference : _computeTypeRefRegions) {
    {
      int _offset = docTypeReference.getOffset();
      int _length = docTypeReference.getLength();
      final TextRegion referenceRange = new TextRegion(_offset, _length);
      boolean _contains = selectedRegion.contains(referenceRange);
      if (_contains) {
        String docTypeText = docTypeReference.getText();
        final EObject element = NodeModelUtils.findActualSemanticObjectFor(documentationNode);
        IScope scope = this.scopeProvider.getScope(element, 
          TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
        IEObjectDescription singleElement = scope.getSingleElement(QualifiedName.create(docTypeText));
        JvmType referencedType = null;
        if ((singleElement != null)) {
          EObject _eObjectOrProxy = singleElement.getEObjectOrProxy();
          referencedType = ((JvmType) _eObjectOrProxy);
        }
        if (((referencedType instanceof JvmDeclaredType) && (!referencedType.eIsProxy()))) {
          JvmDeclaredType casted = ((JvmDeclaredType) referencedType);
          boolean _equals = casted.getQualifiedName().equals(docTypeText);
          boolean _not = (!_equals);
          if (_not) {
            acceptor.acceptTypeImport(casted);
          }
        }
      }
    }
  }
}
 
Example 11
Source File: JvmModelReferenceUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Preserves the syntax of method calls if the target is refactored.
 * 
 * @since 2.4
 */
@Override
protected RefTextEvaluator getRefTextEvaluator(final EObject referringElement, URI referringResourceURI,
		final EReference reference, int indexInList, EObject newTargetElement) {
	final ReferenceSyntax oldReferenceSyntax = getReferenceSyntax(referringElement, reference, indexInList);
	if (oldReferenceSyntax == null)
		return super.getRefTextEvaluator(referringElement, referringResourceURI, reference, indexInList,
				newTargetElement);
	return new RefTextEvaluator() {

		@Override
		public boolean isValid(IEObjectDescription newTarget) {
			IScope scope = linkingScopeProvider.getScope(referringElement, reference);
			IEObjectDescription element = scope.getSingleElement(newTarget.getName());
			// TODO here we need to simulate linking with the new name instead of the old name
			if(element instanceof IIdentifiableElementDescription) {
				IIdentifiableElementDescription casted = (IIdentifiableElementDescription) element;
				if(!casted.isVisible() || !casted.isValidStaticState())
					return false;
			}
			return element != null 
						&& element.getEObjectURI() != null 
						&& element.getEObjectURI().equals(newTarget.getEObjectURI());
		}

		@Override
		public boolean isBetterThan(String newText, String currentText) {
			ReferenceSyntax newSyntax = getReferenceSyntax(newText);
			ReferenceSyntax currentSyntax = getReferenceSyntax(currentText);
			// prefer the one with the same syntax as before
			if (newSyntax == oldReferenceSyntax && currentSyntax != oldReferenceSyntax)
				return true;
			else if (newSyntax != oldReferenceSyntax && currentSyntax == oldReferenceSyntax)
				return false;
			else
				// in doubt shorter is better
				return newText.length() < currentText.length();
		}
	};
}
 
Example 12
Source File: ConstantExpressionsInterpreter.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected JvmType findTypeByName(final EObject context, final String qualifiedName) {
  final IScope scope = this.scopeProvider.getScope(context, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
  final QualifiedName qn = this.qualifiedNameConverter.toQualifiedName(qualifiedName);
  IEObjectDescription _singleElement = scope.getSingleElement(qn);
  EObject _eObjectOrProxy = null;
  if (_singleElement!=null) {
    _eObjectOrProxy=_singleElement.getEObjectOrProxy();
  }
  return ((JvmType) _eObjectOrProxy);
}
 
Example 13
Source File: XbaseReferenceUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean canLinkJvmType(EObject referringElement, JvmType type) {
	if (type == null) {
		return false;
	}
	QualifiedName qualifiedName = qualifiedNameProvider.getFullyQualifiedName(type);
	if (qualifiedName == null) {
		return false;
	}
	IScope scope = getLinkingScopeProvider().getScope(referringElement, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
	return scope.getSingleElement(qualifiedName) != null;
}
 
Example 14
Source File: XbaseReferenceUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * constructor calls and type references are import aware, but only type reference can be disambiguated by using
 * #getSingleElement
 */
protected boolean isReferencedByQualifiedName(EObject referringElement, JvmType newTargetType, QualifiedName importRelativeName) {
	IScope scope = getLinkingScopeProvider().getScope(referringElement, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
	IEObjectDescription singleElement = scope.getSingleElement(importRelativeName);
	if (singleElement == null) {
		return false;
	}
	EObject resolvedSingleElement = EcoreUtil.resolve(singleElement.getEObjectOrProxy(), referringElement);
	return resolvedSingleElement != EcoreUtil2.getContainerOfType(newTargetType, JvmDeclaredType.class);
}
 
Example 15
Source File: DefaultLinkingService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return the first element returned from the injected {@link IScopeProvider} which matches the text of the passed
 *         {@link INode node}
 */
@Override
public List<EObject> getLinkedObjects(EObject context, EReference ref, INode node) throws IllegalNodeException {
	final EClass requiredType = ref.getEReferenceType();
	if (requiredType == null) {
		return Collections.<EObject>emptyList();
	}
	final String crossRefString = getCrossRefNodeAsString(node);
	if (crossRefString == null || crossRefString.equals("")) {
		return Collections.<EObject>emptyList();
	}
	if (logger.isDebugEnabled()) {
		logger.debug("before getLinkedObjects: node: '" + crossRefString + "'");
	}
	final IScope scope = getScope(context, ref);
	if (scope == null) {
		throw new AssertionError(
				"Scope provider " + scopeProvider.getClass().getName() + " must not return null for context "
						+ context + ", reference " + ref + "! Consider to return IScope.NULLSCOPE instead.");
	}
	final QualifiedName qualifiedLinkName = qualifiedNameConverter.toQualifiedName(crossRefString);
	final IEObjectDescription eObjectDescription = scope.getSingleElement(qualifiedLinkName);
	if (logger.isDebugEnabled()) {
		logger.debug("after getLinkedObjects: node: '" + crossRefString + "' result: " + eObjectDescription);
	}
	if (eObjectDescription == null) {
		return Collections.emptyList();
	}
	final EObject result = eObjectDescription.getEObjectOrProxy();
	return Collections.singletonList(result);
}
 
Example 16
Source File: CrossReferenceSerializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected String getUnconvertedLinkText(EObject object, EReference reference, EObject context) {
	IScope scope = scopeProvider.getScope(context, reference);
	if (scope == null)
		return null;
	IEObjectDescription eObjectDescription = scope.getSingleElement(object);
	if (eObjectDescription != null) {
		return qualifiedNameConverter.toString(eObjectDescription.getName());
	}
	return null;
}
 
Example 17
Source File: SpecInfosByName.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private RepoRelativePath computeRRP(FullMemberReference ref, TMember testMember) {
	IScope scope = globalScopeProvider.getScope(testMember.eResource(),
			N4JSPackage.Literals.IMPORT_DECLARATION__MODULE);
	QualifiedName qn = QualifiedName.create(ref.getModuleName().split("/"));
	IEObjectDescription eod = scope.getSingleElement(qn);
	if (eod != null) {
		FileURI uri = new FileURI(eod.getEObjectURI());
		RepoRelativePath rrp = RepoRelativePath.compute(uri, n4jsCore);
		return rrp;
	} else {
		issueAcceptor.addWarning("Cannot resolve testee " + ref, testMember);
		return null;
	}

}
 
Example 18
Source File: MultiLineJavaDocTypeReferenceProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected IEObjectDescription getElementFromScope(IScope scope, INode node, ITextRegion region, String text) {
	return scope.getSingleElement(qualifiedNameConverter.toQualifiedName(text));
}
 
Example 19
Source File: XbaseHoverDocumentationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected void handleLink(List<?> fragments) {
	if (fragments == null || fragments.isEmpty()) {
		return;
	}
	URI elementURI = null;
	String firstFragment = fragments.get(0).toString();
	int hashIndex = firstFragment.indexOf("#");
	if (hashIndex != -1) {
		JvmDeclaredType resolvedDeclarator = getResolvedDeclarator(firstFragment.substring(0, hashIndex));
		if (resolvedDeclarator != null && !resolvedDeclarator.eIsProxy()) {
			String signature = firstFragment.substring(hashIndex + 1);
			int indexOfOpenBracket = signature.indexOf("(");
			int indexOfClosingBracket = signature.indexOf(")");
			String simpleNameOfFeature = indexOfOpenBracket != -1 ? signature.substring(0, indexOfOpenBracket)
					: signature;
			Iterable<JvmConstructor> constructorCandidates = new ArrayList<JvmConstructor>();
			if (resolvedDeclarator.getSimpleName().equals(simpleNameOfFeature)) {
				constructorCandidates = resolvedDeclarator.getDeclaredConstructors();
			}
			Iterable<JvmFeature> possibleCandidates = Iterables.concat(
				resolvedDeclarator.findAllFeaturesByName(simpleNameOfFeature),
				constructorCandidates
			);
			List<String> parameterNames = null;
			if (indexOfOpenBracket != -1 && indexOfClosingBracket != -1) {
				parameterNames = Strings.split(signature.substring(indexOfOpenBracket + 1, indexOfClosingBracket),
						",");
			}
			Iterator<JvmFeature> featureIterator = possibleCandidates.iterator();
			while (elementURI == null && featureIterator.hasNext()) {
				JvmFeature feature = featureIterator.next();
				boolean valid = false;
				if (feature instanceof JvmField) {
					valid = true;
				} else if (feature instanceof JvmExecutable) {
					JvmExecutable executable = (JvmExecutable) feature;
					EList<JvmFormalParameter> parameters = executable.getParameters();
					if (parameterNames == null) {
						valid = true;
					} else if (parameters.size() == parameterNames.size()) {
						valid = true;
						for (int i = 0; (i < parameterNames.size() && valid); i++) {
							URI parameterTypeURI = EcoreUtil.getURI(parameters.get(i).getParameterType().getType());
							IEObjectDescription expectedParameter = scopeProvider.getScope(context,
									new HoverReference(TypesPackage.Literals.JVM_TYPE)).getSingleElement(
									qualifiedNameConverter.toQualifiedName(parameterNames.get(i)));
							if (expectedParameter == null
									|| !expectedParameter.getEObjectURI().equals(parameterTypeURI)) {
								valid = false;
							}
						}
					}
				}
				if (valid)
					elementURI = EcoreUtil.getURI(feature);
			}
		}
	} else {
		IScope scope = scopeProvider.getScope(context, new HoverReference(TypesPackage.Literals.JVM_TYPE));
		IEObjectDescription singleElement = scope.getSingleElement(qualifiedNameConverter
				.toQualifiedName(firstFragment));
		if (singleElement != null)
			elementURI = singleElement.getEObjectURI();
	}
	String label = "";
	if (fragments.size() > 1) {
		for (int i = 1; i < fragments.size(); i++) {
			String portentialLabel = fragments.get(i).toString();
			if (portentialLabel.trim().length() > 0)
				label += portentialLabel;
		}
	}
	if (label.length() == 0)
		label = firstFragment;
	if (elementURI == null)
		buffer.append(label);
	else {
		buffer.append(createLinkWithLabel(XtextElementLinks.XTEXTDOC_SCHEME, elementURI, label));
	}
}
 
Example 20
Source File: LinkingService.java    From dsl-devkit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Gets an {@link IEObjectDescription} that best matches a given context, reference, and qualified name.
 * <p>
 * The concept of a "best match" is "in the eye of the beholder", that is, the context and reference. The default case is the first element returned from the
 * scope for the given context and reference that matches the given qualified name.
 * </p>
 *
 * @param context
 *          the context of the {@code reference}, must not be {@code null}
 * @param reference
 *          the reference for which the result element should be suitable, must not be {@code null}
 * @param qualifiedLinkName
 *          the name that the result element should match, must not be {@code null}
 * @return an IEObjectDescription that best matches {@code qualifiedLinkName} in {@code scope} given the {@code context} and {@code reference},
 *         may by {@code null}
 */
protected IEObjectDescription getSingleElement(final EObject context, final EReference reference, final QualifiedName qualifiedLinkName) {
  IEObjectDescription desc = null;
  IScope scope = getScope(context, reference);
  if (scope instanceof WrappingTypedScope) {
    desc = ((WrappingTypedScope) scope).getSingleElement(qualifiedLinkName, reference);
  } else {
    desc = scope.getSingleElement(qualifiedLinkName);
  }
  return desc;
}