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

The following examples show how to use org.eclipse.xtext.scoping.IScope#getElements() . 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: ContainerTypesHelper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private List<Type> getPolyfillTypesFromScope(QualifiedName fqn) {

			IScope contextScope = polyfillScopeAccess.getRecordingPolyfillScope(contextResource);
			List<Type> types = new ArrayList<>();

			// contextScope.getElements(fqn) returns all polyfills, since shadowing is handled differently
			// for them!
			for (IEObjectDescription descr : contextScope.getElements(fqn)) {
				Type polyfillType = (Type) descr.getEObjectOrProxy();
				if (polyfillType.eIsProxy()) {
					// TODO review: this seems odd... is this a test setup problem (since we do not use the
					// index
					// there and load the resource separately)?
					polyfillType = (Type) EcoreUtil.resolve(polyfillType, contextResource);
					if (polyfillType.eIsProxy()) {
						throw new IllegalStateException("unexpected proxy");
					}
				}
				types.add(polyfillType);
			}
			// }

			return types;
		}
 
Example 2
Source File: URINormalizationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testGetElementByClasspathURIEObject() throws Exception {
	with(ImportUriTestLanguageStandaloneSetup.class);
	Main main = (Main) getModel("import 'classpath:/org/eclipse/xtext/linking/05.importuritestlanguage'\n"
			+ "type Bar extends Foo");
	Type bar = main.getTypes().get(0);
	Type foo = bar.getExtends();
	assertNotNull(foo);
	assertFalse(foo.eIsProxy());
	// we don't put contextual classpath:/ uris into the index thus
	// they are partially normalized
	if (Platform.isRunning()) {
		assertEquals("bundleresource", EcoreUtil.getURI(foo).scheme());
	} else {
		assertEquals("file", EcoreUtil.getURI(foo).scheme());
	}
	IScopeProvider scopeProvider = get(IScopeProvider.class);
	IScope scope = scopeProvider.getScope(bar, ImportedURIPackage.Literals.TYPE__EXTENDS);
	Iterable<IEObjectDescription> elements = scope.getElements(foo);
	assertEquals(1, size(elements));
	assertEquals(EcoreUtil2.getPlatformResourceOrNormalizedURI(foo), elements.iterator().next().getEObjectURI());
}
 
Example 3
Source File: ScopeProviderAccess.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns a bunch of descriptions most of which are actually {@link IIdentifiableElementDescription describing identifiables}. 
 * The provided iterable is never empty but it may contain a single {@link ErrorDescription error description}.
 * 
 * @return the available descriptions.
 */
public Iterable<IEObjectDescription> getCandidateDescriptions(XExpression expression, EReference reference, /* @Nullable */ EObject toBeLinked,
		IFeatureScopeSession session, IResolvedTypes types) throws IllegalNodeException {
	if (toBeLinked == null) {
		return Collections.emptyList();
	}
	if (!toBeLinked.eIsProxy()) {
		throw new IllegalStateException(expression + " was already linked to " + toBeLinked);
	}
	URI uri = EcoreUtil.getURI(toBeLinked);
	String fragment = uri.fragment();
	if (encoder.isCrossLinkFragment(expression.eResource(), fragment)) {
		INode node = encoder.getNode(expression, fragment);
		final EClass requiredType = reference.getEReferenceType();
		if (requiredType == null)
			return Collections.emptyList();

		final String crossRefString = linkingHelper.getCrossRefNodeAsString(node, true);
		if (crossRefString != null && !crossRefString.equals("")) {
			QualifiedName qualifiedLinkName = qualifiedNameConverter.toQualifiedName(crossRefString);
			if (!qualifiedLinkName.isEmpty()) {
				final IScope scope = session.getScope(expression, reference, types);
				Iterable<IEObjectDescription> descriptions = scope.getElements(qualifiedLinkName);
				if (Iterables.isEmpty(descriptions)) {
					INode errorNode = getErrorNode(expression, node);
					if (errorNode != node) {
						qualifiedLinkName = getErrorName(errorNode);
					}
					return Collections.<IEObjectDescription>singletonList(new ErrorDescription(getErrorNode(expression, node), qualifiedLinkName));
				}
				return descriptions;
			} else {
				return Collections.<IEObjectDescription>singletonList(new ErrorDescription(null /* followUp problem */));
			}
		}
		return Collections.emptyList();
	} else {
		throw new IllegalStateException(expression + " uses unsupported uri fragment " + uri);
	}
}
 
Example 4
Source File: RefactoringCrossReferenceSerializer.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public String getCrossRefText(EObject owner, CrossReference crossref, EObject target,
		RefTextEvaluator refTextEvaluator, ITextRegion linkTextRegion, StatusWrapper status) {
	try {
		final EReference ref = GrammarUtil.getReference(crossref, owner.eClass());
		final IScope scope = scopeProvider.getScope(owner, ref);
		if (scope == null) {
			throw new IllegalStateException("Could not create scope for the given cross reference.");
		}
		String ruleName = linkingHelper.getRuleNameFrom(crossref);

		Iterable<IEObjectDescription> descriptionsForCrossRef = scope.getElements(target);
		String bestRefText = null;
		List<String> badNames = new ArrayList<String>();
		for (IEObjectDescription desc : descriptionsForCrossRef) {
			try {
				String unconvertedRefText = qualifiedNameConverter.toString(desc.getName());
				String convertedRefText = valueConverter.toString(unconvertedRefText, ruleName);
				if (refTextEvaluator.isValid(desc) && (bestRefText == null || refTextEvaluator.isBetterThan(convertedRefText, bestRefText)))
					bestRefText = convertedRefText;
			} catch (ValueConverterException e) {
				// this is a problem only if we don't find any matching value
				badNames.add(desc.getName().toString());
			}
		}
		if (bestRefText == null && !badNames.isEmpty()) {
			status.add(WARNING,
					"Misconfigured language: New reference text has invalid syntax. Following names are in the scope: " + IterableExtensions.join(badNames, ", "), owner, linkTextRegion);
		}
		return bestRefText;

	} catch (Exception exc) {
		log.error(exc.getMessage(), exc);
		status.add(ERROR, exc.getMessage(), owner, linkTextRegion);
		return null;
	}
}
 
Example 5
Source File: CrossReferenceSerializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String serializeCrossRef(EObject semanticObject, CrossReference crossref, EObject target, INode node,
		Acceptor errors) {
	if ((target == null || target.eIsProxy()) && node != null)
		return tokenUtil.serializeNode(node);

	final EReference ref = GrammarUtil.getReference(crossref, semanticObject.eClass());
	final IScope scope = scopeProvider.getScope(semanticObject, ref);
	if (scope == null) {
		if (errors != null)
			errors.accept(diagnostics.getNoScopeFoundDiagnostic(semanticObject, crossref, target));
		return null;
	}
	
	if (target != null && target.eIsProxy()) {
		target = handleProxy(target, semanticObject, ref);
	}

	if (target != null && node != null) {
		String text = linkingHelper.getCrossRefNodeAsString(node, true);
		QualifiedName qn = qualifiedNameConverter.toQualifiedName(text);
		URI targetURI = EcoreUtil2.getPlatformResourceOrNormalizedURI(target);
		for (IEObjectDescription desc : scope.getElements(qn)) {
			if (targetURI.equals(desc.getEObjectURI()))
				return tokenUtil.serializeNode(node);
		}
	}

	return getCrossReferenceNameFromScope(semanticObject, crossref, target, scope, errors);
}
 
Example 6
Source File: CrossReferenceSerializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected String getCrossReferenceNameFromScope(EObject semanticObject, CrossReference crossref, EObject target,
		final IScope scope, Acceptor errors) {
	String ruleName = linkingHelper.getRuleNameFrom(crossref);
	boolean foundOne = false;
	List<ISerializationDiagnostic> recordedErrors = null;
	for (IEObjectDescription desc : scope.getElements(target)) {
		foundOne = true;
		String unconverted = qualifiedNameConverter.toString(desc.getName());
		try {
			return valueConverter.toString(unconverted, ruleName);
		} catch (ValueConverterException e) {
			if (errors != null) {
				if (recordedErrors == null)
					recordedErrors = Lists.newArrayList();
				recordedErrors.add(diagnostics.getValueConversionExceptionDiagnostic(semanticObject, crossref,
						unconverted, e));
			}
		}
	}
	if (errors != null) {
		if (recordedErrors != null)
			for (ISerializationDiagnostic diag : recordedErrors)
				errors.accept(diag);
		if (!foundOne)
			errors.accept(diagnostics.getNoEObjectDescriptionFoundDiagnostic(semanticObject, crossref, target,
					scope));
	}
	return null;
}
 
Example 7
Source File: ReferenceUpdater.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected String findValidName(IUpdatableReference updatable, IScope scope) {
	Iterable<IEObjectDescription> elements = scope.getElements(updatable.getTargetEObject());
	String ruleName = linkingHelper.getRuleNameFrom(updatable.getCrossReference());
	for (IEObjectDescription desc : elements) {
		try {
			String unconverted = nameConverter.toString(desc.getName());
			String string = valueConverter.toString(unconverted, ruleName);
			return string;
		} catch (ValueConverterException e) {
			// do nothing
		}
	}
	return null;
}
 
Example 8
Source File: AbstractScopingTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check if scope expected is found in context provided.
 *
 * @param context
 *          element from which an element shall be referenced
 * @param reference
 *          to be used to filter the elements
 * @param expectedName
 *          name of scope element to look for
 * @param expectedUri
 *          of source referenced
 */
private void assertScope(final EObject context, final EReference reference, final QualifiedName expectedName, final URI expectedUri) {
  IScope scope = getScopeProvider().getScope(context, reference);
  Iterable<IEObjectDescription> descriptions = scope.getElements(expectedName);
  assertFalse("Description missing for: " + expectedName, Iterables.isEmpty(descriptions));
  URI currentUri = null;
  for (IEObjectDescription desc : descriptions) {
    currentUri = desc.getEObjectURI();
    if (currentUri.equals(expectedUri)) {
      return;
    }
  }
  assertEquals("Scope URI is not equal to expected URI", expectedUri, currentUri);
}
 
Example 9
Source File: OperationOverloadingLinkingService.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public List<EObject> getLinkedOperation(ArgumentExpression context, EReference ref, INode node) {
	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();
	}
	final IScope scope = getScope(context, ref);
	final QualifiedName qualifiedLinkName = qualifiedNameConverter.toQualifiedName(crossRefString);
	// Adoption to super class implementation here to return multi elements
	final Iterable<IEObjectDescription> eObjectDescription = scope.getElements(qualifiedLinkName);
	int size = Iterables.size(eObjectDescription);
	if (size == 0)
		return Collections.emptyList();
	if (size == 1)
		return Collections.singletonList(Iterables.getFirst(eObjectDescription, null).getEObjectOrProxy());
	// Two operation with same name found here
	List<IEObjectDescription> candidates = new ArrayList<>();
	for (IEObjectDescription currentDescription : eObjectDescription) {
		if (currentDescription.getEClass().isSuperTypeOf(TypesPackage.Literals.OPERATION)) {
			candidates.add(currentDescription);
		}
	}
	Optional<Operation> operation = operationsLinker.linkOperation(candidates, context);
	if (operation.isPresent()) {
		return Collections.singletonList(operation.get());
	}
	//Link to first operation to get parameter errors instead of linking errors
	return Collections.singletonList(Iterables.getFirst(eObjectDescription, null).getEObjectOrProxy());
}
 
Example 10
Source File: XbaseSemanticSequencer.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Constraint:
 *     (
 *         (leftOperand=XAdditiveExpression_XBinaryOperation_1_0_0_0 feature=[JvmIdentifiableElement|OpAdd] rightOperand=XMultiplicativeExpression) | 
 *         (leftOperand=XMultiplicativeExpression_XBinaryOperation_1_0_0_0 feature=[JvmIdentifiableElement|OpMulti] rightOperand=XUnaryOperation) | 
 *         (leftOperand=XOtherOperatorExpression_XBinaryOperation_1_0_0_0 feature=[JvmIdentifiableElement|OpOther] rightOperand=XAdditiveExpression) | 
 *         (leftOperand=XRelationalExpression_XBinaryOperation_1_1_0_0_0 feature=[JvmIdentifiableElement|OpCompare] rightOperand=XOtherOperatorExpression) | 
 *         (leftOperand=XEqualityExpression_XBinaryOperation_1_0_0_0 feature=[JvmIdentifiableElement|OpEquality] rightOperand=XRelationalExpression) | 
 *         (leftOperand=XAndExpression_XBinaryOperation_1_0_0_0 feature=[JvmIdentifiableElement|OpAnd] rightOperand=XEqualityExpression) | 
 *         (leftOperand=XOrExpression_XBinaryOperation_1_0_0_0 feature=[JvmIdentifiableElement|OpOr] rightOperand=XAndExpression) | 
 *         (leftOperand=XAssignment_XBinaryOperation_1_1_0_0_0 feature=[JvmIdentifiableElement|OpMultiAssign] rightOperand=XAssignment)
 *     )
 */
@Override
protected void sequence_XAdditiveExpression_XAndExpression_XAssignment_XEqualityExpression_XMultiplicativeExpression_XOrExpression_XOtherOperatorExpression_XRelationalExpression(ISerializationContext context, XBinaryOperation operation) {
	INodesForEObjectProvider nodes = createNodeProvider(operation);
	SequenceFeeder acceptor = createSequencerFeeder(context, operation, nodes);
	XAdditiveExpressionElements opAdd = grammarAccess.getXAdditiveExpressionAccess();
	XMultiplicativeExpressionElements opMulti = grammarAccess.getXMultiplicativeExpressionAccess();
	XOtherOperatorExpressionElements opOther = grammarAccess.getXOtherOperatorExpressionAccess();
	XRelationalExpressionElements opCompare = grammarAccess.getXRelationalExpressionAccess();
	XEqualityExpressionElements opEquality = grammarAccess.getXEqualityExpressionAccess();
	XAndExpressionElements opAnd = grammarAccess.getXAndExpressionAccess();
	XOrExpressionElements opOr = grammarAccess.getXOrExpressionAccess();
	XAssignmentElements opMultiAssign = grammarAccess.getXAssignmentAccess();
	
	JvmIdentifiableElement feature = operation.getFeature();
	Set<String> operatorNames = Sets.newHashSet();
	if (feature.eIsProxy()) {
		List<INode> ops = NodeModelUtils.findNodesForFeature(operation, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
		for (INode o : ops)
			operatorNames.add(NodeModelUtils.getTokenText(o));
	} else {
		IScope scope = scopeProvider.getScope(operation, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
		for (IEObjectDescription desc : scope.getElements(feature))
			operatorNames.add(qualifiedNameConverter.toString(desc.getName()));
	}
	ICompositeNode featureNode = (ICompositeNode) nodes.getNodeForSingelValue(XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, operation.getFeature());
	String featureToken;
	
	if((featureToken = getValidOperator(operation, opAdd.getFeatureJvmIdentifiableElementOpAddParserRuleCall_1_0_0_1_0_1(), operatorNames, featureNode)) != null) {
		acceptor.accept(opAdd.getXBinaryOperationLeftOperandAction_1_0_0_0(), operation.getLeftOperand());
		acceptor.accept(opAdd.getFeatureJvmIdentifiableElementOpAddParserRuleCall_1_0_0_1_0_1(), operation.getFeature(), featureToken, featureNode);
		acceptor.accept(opAdd.getRightOperandXMultiplicativeExpressionParserRuleCall_1_1_0(), operation.getRightOperand());
	} else if((featureToken = getValidOperator(operation, opMulti.getFeatureJvmIdentifiableElementOpMultiParserRuleCall_1_0_0_1_0_1(), operatorNames, featureNode)) != null) {
		acceptor.accept(opMulti.getXBinaryOperationLeftOperandAction_1_0_0_0(), operation.getLeftOperand());
		acceptor.accept(opMulti.getFeatureJvmIdentifiableElementOpMultiParserRuleCall_1_0_0_1_0_1(), operation.getFeature(), featureToken, featureNode);
		acceptor.accept(opMulti.getRightOperandXUnaryOperationParserRuleCall_1_1_0(), operation.getRightOperand());
	} else if((featureToken = getValidOperator(operation, opOther.getFeatureJvmIdentifiableElementOpOtherParserRuleCall_1_0_0_1_0_1(), operatorNames, featureNode)) != null) {
		acceptor.accept(opOther.getXBinaryOperationLeftOperandAction_1_0_0_0(), operation.getLeftOperand());
		acceptor.accept(opOther.getFeatureJvmIdentifiableElementOpOtherParserRuleCall_1_0_0_1_0_1(), operation.getFeature(), featureToken, featureNode);
		acceptor.accept(opOther.getRightOperandXAdditiveExpressionParserRuleCall_1_1_0(), operation.getRightOperand());
	} else if((featureToken = getValidOperator(operation, opCompare.getFeatureJvmIdentifiableElementOpCompareParserRuleCall_1_1_0_0_1_0_1(), operatorNames, featureNode)) != null) {
		acceptor.accept(opCompare.getXBinaryOperationLeftOperandAction_1_1_0_0_0(), operation.getLeftOperand());
		acceptor.accept(opCompare.getFeatureJvmIdentifiableElementOpCompareParserRuleCall_1_1_0_0_1_0_1(), operation.getFeature(), featureToken, featureNode);
		acceptor.accept(opCompare.getRightOperandXOtherOperatorExpressionParserRuleCall_1_1_1_0(), operation.getRightOperand());
	} else if((featureToken = getValidOperator(operation, opEquality.getFeatureJvmIdentifiableElementOpEqualityParserRuleCall_1_0_0_1_0_1(), operatorNames, featureNode)) != null) {
		acceptor.accept(opEquality.getXBinaryOperationLeftOperandAction_1_0_0_0(), operation.getLeftOperand());
		acceptor.accept(opEquality.getFeatureJvmIdentifiableElementOpEqualityParserRuleCall_1_0_0_1_0_1(), operation.getFeature(), featureToken, featureNode);
		acceptor.accept(opEquality.getRightOperandXRelationalExpressionParserRuleCall_1_1_0(), operation.getRightOperand());
	} else if((featureToken = getValidOperator(operation, opAnd.getFeatureJvmIdentifiableElementOpAndParserRuleCall_1_0_0_1_0_1(), operatorNames, featureNode)) != null) {
		acceptor.accept(opAnd.getXBinaryOperationLeftOperandAction_1_0_0_0(), operation.getLeftOperand());
		acceptor.accept(opAnd.getFeatureJvmIdentifiableElementOpAndParserRuleCall_1_0_0_1_0_1(), operation.getFeature(), featureToken, featureNode);
		acceptor.accept(opAnd.getRightOperandXEqualityExpressionParserRuleCall_1_1_0(), operation.getRightOperand());
	} else if((featureToken = getValidOperator(operation, opOr.getFeatureJvmIdentifiableElementOpOrParserRuleCall_1_0_0_1_0_1(), operatorNames, featureNode)) != null) {
		acceptor.accept(opOr.getXBinaryOperationLeftOperandAction_1_0_0_0(), operation.getLeftOperand());
		acceptor.accept(opOr.getFeatureJvmIdentifiableElementOpOrParserRuleCall_1_0_0_1_0_1(), operation.getFeature(), featureToken, featureNode);
		acceptor.accept(opOr.getRightOperandXAndExpressionParserRuleCall_1_1_0(), operation.getRightOperand());
	} else if((featureToken = getValidOperator(operation, opMultiAssign.getFeatureJvmIdentifiableElementOpMultiAssignParserRuleCall_1_1_0_0_1_0_1(), operatorNames, featureNode)) != null) {
		acceptor.accept(opMultiAssign.getXBinaryOperationLeftOperandAction_1_1_0_0_0(), operation.getLeftOperand());
		acceptor.accept(opMultiAssign.getFeatureJvmIdentifiableElementOpMultiAssignParserRuleCall_1_1_0_0_1_0_1(), operation.getFeature(), featureToken, featureNode);
		acceptor.accept(opMultiAssign.getRightOperandXAssignmentParserRuleCall_1_1_1_0(), operation.getRightOperand());
	} else if (errorAcceptor != null) {
		errorAcceptor.accept(new SerializationDiagnostic(OPERATOR_NOT_SUPPORTED, operation, context, grammarAccess.getGrammar(), "Operator "+operatorNames+" is not supported."));
	} 
	acceptor.finish();
}
 
Example 11
Source File: ParameterContextInformationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void getContextInformation(ContentAssistContext context, IContextInformationAcceptor acceptor) {
	XExpression containerCall = getContainerCall(eObjectAtOffsetHelper.resolveContainedElementAt(context.getResource(), context.getOffset()));
	LightweightTypeReferenceFactory factory = proposalProvider.getTypeConverter(context.getResource());
	if (containerCall != null) {
		ICompositeNode containerCallNode = NodeModelUtils.findActualNodeFor(containerCall);
		ITextRegion containerCallRegion = containerCallNode.getTextRegion();
		if(containerCallRegion.getOffset() > context.getOffset()
				|| containerCallRegion.getOffset() + containerCallRegion.getLength() < context.getOffset()) 
			return;
		JvmIdentifiableElement calledFeature = getCalledFeature(containerCall);
		if (calledFeature instanceof JvmExecutable) {
			if(getParameterListOffset(containerCall) > context.getOffset()) 
				return;
			ParameterData parameterData = new ParameterData();
			IScope scope = getScope(containerCall);
			QualifiedName qualifiedName = QualifiedName.create(getCalledFeatureName(containerCall));
			boolean candidatesFound = false;
			for (IEObjectDescription element : scope.getElements(qualifiedName)) {
				if (element instanceof IIdentifiableElementDescription) {
					IIdentifiableElementDescription featureDescription = (IIdentifiableElementDescription) element;
					JvmIdentifiableElement featureCandidate = featureDescription.getElementOrProxy();
					if (featureCandidate instanceof JvmExecutable) {
						JvmExecutable executable = (JvmExecutable) featureCandidate;
						if(!executable.getParameters().isEmpty()) {
							StyledString styledString = new StyledString();
							proposalProvider.appendParameters(styledString, executable,
									featureDescription.getNumberOfIrrelevantParameters(), factory);
							parameterData.addOverloaded(styledString.toString(), executable.isVarArgs());
							candidatesFound = true;
						}
					}
				}
			}
			if (candidatesFound) {
				StyledString displayString = proposalProvider.getStyledDisplayString((JvmExecutable) calledFeature, true, 0, 
						qualifiedNameConverter.toString(qualifiedNameProvider.getFullyQualifiedName(calledFeature)), 
						calledFeature.getSimpleName(), factory);
				ParameterContextInformation parameterContextInformation = new ParameterContextInformation(
						parameterData, displayString.toString(), getParameterListOffset(containerCall), context.getOffset());
				acceptor.accept(parameterContextInformation);
			}
		}
	}
}