Java Code Examples for org.eclipse.xtext.resource.IEObjectDescription#getEObjectURI()

The following examples show how to use org.eclipse.xtext.resource.IEObjectDescription#getEObjectURI() . 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: ScopeXpectMethod.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compares scope including resource name and line number.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void scopeWithPosition( //
		@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectation, //
		ICrossEReferenceAndEObject arg1 //
) {
	EObject eobj = arg1.getEObject();
	IScope scope = scopeProvider.getScope(eobj, arg1.getCrossEReference());
	for (IEObjectDescription eo : scope.getAllElements()) {
		eo.getEObjectURI();
	}
	URI uri = eobj == null ? null : eobj.eResource() == null ? null : eobj.eResource().getURI();
	expectation.assertEquals(new ScopeAwareIterable(uri, true, scope),
			new IsInScopeWithOptionalPositionPredicate(converter,
					uri, true, scope));
}
 
Example 2
Source File: ScopeXpectMethod.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compares scope including resource name but not line number.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void scopeWithResource( //
		@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectation, //
		ICrossEReferenceAndEObject arg1 //
) {
	EObject eobj = arg1.getEObject();
	IScope scope = scopeProvider.getScope(eobj, arg1.getCrossEReference());
	for (IEObjectDescription eo : scope.getAllElements()) {
		eo.getEObjectURI();
	}
	URI uri = eobj == null ? null : eobj.eResource() == null ? null : eobj.eResource().getURI();
	expectation.assertEquals(new ScopeAwareIterable(uri, false, scope),
			new IsInScopeWithOptionalPositionPredicate(converter,
					uri, false, scope));
}
 
Example 3
Source File: N4JSClassifierWizardModelValidator.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Interfaces specifier property constraints
 */
protected void validateInterfaces() throws ValidationException {
	// ---------------------------------------
	// Interfaces property constraints
	// ---------------------------------------

	ArrayList<ClassifierReference> interfaces = new ArrayList<>(getModel().getInterfaces());

	for (int i = 0; i < interfaces.size(); i++) {
		ClassifierReference iface = interfaces.get(i);
		if (!isValidInterface(iface)) {
			throw new ValidationException(
					String.format(ErrorMessages.THE_INTERFACE_CANNOT_BE_FOUND, iface.getFullSpecifier())
							.toString());
		} else if (iface.uri == null) {
			IEObjectDescription interfaceDescription = getClassifierObjectDescriptionForFQN(
					iface.getFullSpecifier());
			if (interfaceDescription != null) {
				iface.uri = interfaceDescription.getEObjectURI();
			}
		}
	}

	getModel().setInterfaces(interfaces);
}
 
Example 4
Source File: N4JSClassWizardModelValidator.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Validates the super class property.
 */
protected void validateSuperClass() throws ValidationException {

	ClassifierReference superClassRef = getModel().getSuperClass();

	if (!superClassRef.getFullSpecifier().isEmpty()) {
		if (!isValidClass(superClassRef)) {
			throw new ValidationException(THE_SUPER_CLASS_CANNOT_BE_FOUND);
		} else if (superClassRef.uri == null) {
			IEObjectDescription classDescription = getClassifierObjectDescriptionForFQN(
					superClassRef.getFullSpecifier());
			if (classDescription != null) {
				superClassRef.uri = classDescription.getEObjectURI();
			}
		}
	}

}
 
Example 5
Source File: IteratorJob.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected IStatus run(IProgressMonitor monitor) {
	long startTime = System.currentTimeMillis();
	while (iterator.hasNext()) {
		IEObjectDescription next = iterator.next();
		if (next.getQualifiedName() != null && next.getEObjectURI() != null && next.getEClass() != null) {
			matches.add(next);
			long endTime = System.currentTimeMillis();
			if (matches.size() == dialog.getHeightInChars() || endTime - startTime > TIME_THRESHOLD) {
				if (monitor.isCanceled()) {
					return Status.CANCEL_STATUS;
				}
				dialog.updateMatches(sortedCopy(matches), false);
				startTime = System.currentTimeMillis();
			}
		}
	}
	dialog.updateMatches(sortedCopy(matches), true);
	return Status.OK_STATUS;
}
 
Example 6
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 7
Source File: AbstractScopingTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the scope of the given reference for the given context contains only the expected objects.
 * In addition, checks that the reference of the given context references at least one of the expected
 * objects. If the reference has multiplicity > 1, then every reference must reference at least
 * one of the expected objects.
 *
 * @param context
 *          {@link EObject} from which the given objects shall be referenced, must not be {@code null}
 * @param reference
 *          the structural feature of {@code context} for which the scope should be asserted, must not be {@code null} and part of the context element
 * @param expectedObjects
 *          the objects expected in the scope, must not be {@code null}
 */
protected void assertScopedObjects(final EObject context, final EReference reference, final Collection<? extends EObject> expectedObjects) {
  Assert.isNotNull(context, PARAMETER_CONTEXT);
  Assert.isNotNull(reference, PARAMETER_REFERENCE);
  Assert.isNotNull(expectedObjects, PARAMETER_EXPECTED_OBJECTS);
  Assert.isTrue(context.eClass().getEAllReferences().contains(reference), String.format("Contract for argument '%s' failed: Parameter is not within specified range (Expected: %s, Actual: %s).", PARAMETER_CONTEXT, "The context object must contain the given reference.", "Reference not contained by the context object!"));
  Set<URI> expectedUriSet = Sets.newHashSet();
  for (EObject object : expectedObjects) {
    expectedUriSet.add(EcoreUtil.getURI(object));
  }
  IScope scope = getScopeProvider().getScope(context, reference);
  Iterable<IEObjectDescription> allScopedElements = scope.getAllElements();
  Set<URI> scopedUriSet = Sets.newHashSet();
  for (IEObjectDescription description : allScopedElements) {
    URI uri = description.getEObjectURI();
    scopedUriSet.add(uri);
  }
  if (!expectedUriSet.equals(scopedUriSet)) {
    fail("The scope must exactly consist of the expected URIs. Missing " + Sets.difference(expectedUriSet, scopedUriSet) + " extra "
        + Sets.difference(scopedUriSet, expectedUriSet));
  }
  // test that link resolving worked
  boolean elementResolved;
  if (reference.isMany()) {
    @SuppressWarnings("unchecked")
    EList<EObject> objects = (EList<EObject>) context.eGet(reference, true);
    elementResolved = !objects.isEmpty(); // NOPMD
    for (Iterator<EObject> objectIter = objects.iterator(); objectIter.hasNext() && elementResolved;) {
      EObject eObject = EcoreUtil.resolve(objectIter.next(), context);
      elementResolved = expectedUriSet.contains(EcoreUtil.getURI(eObject));
    }
  } else {
    EObject resolvedObject = (EObject) context.eGet(reference, true);
    elementResolved = expectedUriSet.contains(EcoreUtil.getURI(resolvedObject));
  }
  assertTrue("Linking must have resolved one of the expected objects.", elementResolved);
}
 
Example 8
Source File: DefaultResourceDescription.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected URI findExportedContainerURI(EObject referenceOwner,
		Map<EObject, IEObjectDescription> eObject2exportedEObjects) {
	EObject currentContainer = referenceOwner;
	while (currentContainer != null) {
		IEObjectDescription currentContainerEObjectDescription = eObject2exportedEObjects.get(currentContainer);
		if (currentContainerEObjectDescription != null) {
			return currentContainerEObjectDescription.getEObjectURI();
		}
		currentContainer = currentContainer.eContainer();
	}
	return null;
}
 
Example 9
Source File: WorkingCopyOwnerProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public WorkingCopyOwner getWorkingCopyOwner(final IJavaProject javaProject, final ResourceSet resourceSet) {
	return new WorkingCopyOwner() {
		@Override
		public String findSource(String typeName, String packageName) {
			if (packageName.startsWith("java"))
				return super.findSource(typeName, packageName);
			QualifiedName qn = toQualifiedName(packageName, typeName);
			final IResourceDescriptions descriptions = descriptionsProvider.getResourceDescriptions(resourceSet);
			Iterator<IEObjectDescription> exportedObjects = descriptions.getExportedObjects(TypesPackage.Literals.JVM_DECLARED_TYPE, qn, false).iterator();
			while (exportedObjects.hasNext()) {
				IEObjectDescription candidate = exportedObjects.next();
				URI uri = candidate.getEObjectURI();
				if (uri.isPlatformResource() && URI.decode(uri.segment(1)).equals(javaProject.getElementName())) {
					IResourceDescription resourceDescription = descriptions.getResourceDescription(uri.trimFragment());
					return getSource(typeName, packageName, candidate, resourceSet, resourceDescription);
				}
			}
			return super.findSource(typeName, packageName);
		}
		
		
		/**
		 * not implemented because we don't have a proper index for Java package names and the very rare cases in which this would
		 * cause trouble are not worth the general degrade in performance.
		 */
		@Override public boolean isPackage(String[] pkg) {
			return super.isPackage(pkg);
		}
	};
}
 
Example 10
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 11
Source File: EcoreRefactoringParticipant.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private URI findPlatformResourceURI(QualifiedName name, EClass type) {
	for (IResourceDescription resourceDescription : resourceDescriptions.getAllResourceDescriptions()) {
		if (Strings.equal("ecore", resourceDescription.getURI().fileExtension())) {
			for (IEObjectDescription eObjectDescription : resourceDescription.getExportedObjectsByType(type)) {
				if (name.equals(eObjectDescription.getQualifiedName())) {
					return eObjectDescription.getEObjectURI();
				}
			}
		}
	}
	return null;
}
 
Example 12
Source File: JavaResourceDescriptionManager.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IResourceDescription getResourceDescription(Resource resource) {
	if (resource instanceof JavaResource) {
		JavaResource javaResource = (JavaResource) resource;
		boolean initialized = javaResource.isInitialized() || javaResource.isInitializing();
		try {
			if (!initialized) {
				javaResource.eSetDeliver(false);
				javaResource.installStubs();
			}
			DefaultResourceDescription result = new DefaultResourceDescription(resource, descriptionStrategy,
					cache);
			if (!initialized) {
				for (IEObjectDescription d : result.getExportedObjects()) {
					d.getEObjectURI();
				}
			}
			return result;
		} finally {
			if (!initialized) {
				javaResource.discardDerivedState();
				javaResource.eSetDeliver(true);
			}
		}
	}
	throw new IllegalArgumentException("Can only handle JavaResources");
}
 
Example 13
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 14
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 15
Source File: UserDataAwareScope.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private IEObjectDescription resolve(IEObjectDescription original) {
	if (original instanceof ResolvedDescription) {
		return original;
	}
	if (original != null && original.getEObjectOrProxy().eIsProxy()
			&& EcoreUtil2.isAssignableFrom(type, original.getEClass())) {
		final URI objectURI = original.getEObjectURI();
		final URI resourceURI = objectURI.trimFragment();
		Resource resource = resourceSet.getResource(resourceURI, false);
		if (resource != null && resource.isLoaded()) {
			return original;
		}
		final boolean mustLoadFromSource = canLoadFromDescriptionHelper.mustLoadFromSource(resourceURI,
				resourceSet);
		resource = resourceSet.getResource(resourceURI, mustLoadFromSource);
		if (resource != null && resource.isLoaded()) {
			return original;
		}
		if (mustLoadFromSource) {
			// error case: forced loading failed
			// --> still avoid loading from index; instead simply return 'original' as in other error cases
			return original;
		}
		if (resource == null) {
			resource = canLoadFromDescriptionHelper.createResource(resourceSet, resourceURI);
		}
		if (resource instanceof N4JSResource) {
			if (resource.getContents().isEmpty()) {
				N4JSResource casted = (N4JSResource) resource;
				IResourceDescription resourceDescription = container.getResourceDescription(resourceURI);
				if (resourceDescription != null) {
					if (casted.isLoaded()) {
						// LiveShadowingResourceDescriptions (part of Xtext's rename refactoring)
						// will load that stuff on #getResourceDescription
						return original;
					}
					try {
						if (!casted.loadFromDescription(resourceDescription)) {
							return original;
						}
					} catch (Exception e) {
						casted.unload();
						return original;
					}
				} else {
					return original;
				}
			}
			// resolveProxy is implemented recursively thus we have to avoid
			// that here by decorating the
			// description and return the resolved instance instead
			EObject resolved = resolveObject(objectURI, resource);
			if (resolved == null) {
				return original;
			}
			return new ResolvedDescription(resolved, original);
		}
	}
	return original;
}
 
Example 16
Source File: FingerprintResourceDescription.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
private static IEObjectDescription createLightDescription(final IEObjectDescription original) {
  String fingerprint = original.getUserData(IFingerprintComputer.OBJECT_FINGERPRINT);
  return new LightEObjectDescription(original.getEObjectURI(), fingerprint);
}
 
Example 17
Source File: EObjectDescriptionToNameWithPositionMapper.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a string with name and position of the described object. The position is specified by line number (if
 * possible, otherwise the uri fragment of the proxy is used). If the object is a {@link SyntaxRelatedTElement}, a
 * "T" is used as a prefix of the line number.
 *
 * The following examples shows different mappings, depending on the described object:
 * <table>
 * <tr>
 * <th>Mapping</th>
 * <th>Described Object</th>
 * </tr>
 * <tr>
 * <td><code>bar - 42</code></td>
 * <td>Some element "bar", located in same resource on line 42</td>
 * </tr>
 * <tr>
 * <td><code>foo - T23</code></td>
 * <td>A type "foo" (or other syntax related element, a function is a type) which syntax related element (from which
 * the type is build) is located in same file on line 23</td>
 * </tr>
 * <tr>
 * <td><code>Infinity - global.n4ts:3</code></td>
 * <td>An element "Infinity", located in another resource "global.n4ts" on line 3.</td>
 * </tr>
 * <tr>
 * <td><code>decodeURI - global.n4ts:11</code></td>
 * <td>An element "decodeURI", located in another resource "global.n4ts" on line 11. Although the element may be a
 * type, there is no syntax related element because "n4ts" directly describes types.</td>
 * </tr>
 * </table>
 *
 * @param currentURI
 *            the current resource's URI, if described object is in same resource, resource name is omitted
 * @param desc
 *            the object descriptor
 */
public static String descriptionToNameWithPosition(URI currentURI, boolean withLineNumber,
		IEObjectDescription desc) {
	String name = desc.getName().toString();

	EObject eobj = desc.getEObjectOrProxy();

	if (eobj == null) {
		return "No EObject or proxy for " + name + " at URI " + desc.getEObjectURI();
	}

	String location = "";

	if (eobj instanceof SyntaxRelatedTElement) {
		EObject syntaxElement = ((SyntaxRelatedTElement) eobj).getAstElement();
		if (syntaxElement != null) {
			location += "T";
			eobj = syntaxElement;
		}
	}

	Resource eobjRes = eobj.eResource();
	URI uri = eobjRes == null ? null : eobjRes.getURI();
	if (uri != currentURI && uri != null) {
		location = uri.lastSegment();
		if (eobj.eIsProxy() || withLineNumber) {
			location += ":";
		}
	}
	if (eobj.eIsProxy()) {
		URI proxyUri = desc.getEObjectURI();
		location += "proxy:" + simpleURIString(proxyUri);
	} else if (withLineNumber) {
		INode node = NodeModelUtils.findActualNodeFor(eobj);
		if (node == null) {
			location += "no node:" + simpleURIString(desc.getEObjectURI());
		} else {
			location += node.getStartLine();
		}
	}

	return name + SEPARATOR + location;
}