org.eclipse.xtext.util.Tuples Java Examples

The following examples show how to use org.eclipse.xtext.util.Tuples. 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: ProcessResult.java    From n4js with Eclipse Public License 1.0 8 votes vote down vote up
/** @return a list of pairs where the first entry is a name and the second is a property. */
List<Pair<String, String>> getProperties() {
	List<Pair<String, String>> props = new ArrayList<>();
	props.add(Tuples.pair("workingDir", workingDir));
	props.add(Tuples.pair("command", command));
	props.add(Tuples.pair("exit code", (exitCode == NO_EXIT_CODE ? "-" : String.valueOf(exitCode))));
	props.add(Tuples.pair("duration", (duration == NO_DURATION ? "-" : duration + "ms")));
	props.add(Tuples.pair("exception", exception == null ? "" : exception.toString()));

	props.add(Tuples.pair("std out", ""));
	if (stdOut != null && !stdOut.isBlank()) {
		props.add(Tuples.pair(null, ">>>>\n" + stdOut + "\n<<<<"));
	}
	props.add(Tuples.pair("err out", ""));
	if (errOut != null && !errOut.isBlank()) {
		props.add(Tuples.pair(null, ">>>>\n" + errOut + "\n<<<<"));
	}

	return props;
}
 
Example #2
Source File: AbstractElementFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public List<Pair<Keyword, Keyword>> findKeywordPairs(String leftKw, String rightKw) {
	ArrayList<Pair<Keyword, Keyword>> pairs = new ArrayList<Pair<Keyword, Keyword>>();
	for (AbstractRule ar : getRules())
		if (ar instanceof ParserRule && !GrammarUtil.isDatatypeRule((ParserRule) ar)) {
			Stack<Keyword> openings = new Stack<Keyword>();
			TreeIterator<EObject> i = ar.eAllContents();
			while (i.hasNext()) {
				EObject o = i.next();
				if (o instanceof Keyword) {
					Keyword k = (Keyword) o;
					if (leftKw.equals(k.getValue()))
						openings.push(k);
					else if (rightKw.equals(k.getValue())) {
						if (openings.size() > 0)
							pairs.add(Tuples.create(openings.pop(), k));
					}
				}
			}
		}
	return pairs;
}
 
Example #3
Source File: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToProjectProperty(NameValuePair nvpDependency) {
	String projectName = nvpDependency.getName();
	SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));
	if (pdu != null) {
		List<INode> node = NodeModelUtils.findNodesForFeature(nvpDependency,
				JSONPackage.Literals.NAME_VALUE_PAIR__NAME);

		if (!node.isEmpty()) {
			INode nameNode = node.get(0);
			Region region = new Region(nameNode.getOffset() + 1, nameNode.getLength() - 2);

			return Tuples.pair(pdu, region);
		}
	}

	return null;
}
 
Example #4
Source File: ExternalProjectLoader.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** @return load project and description from given URI. Returns null if not available. */
public Pair<N4JSExternalProject, ProjectDescription> load(final FileURI rootLocation) {
	try {
		ProjectDescription projectDescription = packageManager.loadProjectDescriptionFromProjectRoot(rootLocation);

		if (null != projectDescription) {
			File projectRoot = URIUtils.toFile(rootLocation.toURI());
			ExternalProject p = new ExternalProject(projectRoot, NATURE_ID, BUILDER_ID);
			IN4JSProject pp = new N4JSEclipseProject(p, rootLocation, model);
			N4JSExternalProject ppp = new N4JSExternalProject(projectRoot, pp);

			return Tuples.create(ppp, projectDescription);
		}
	} catch (N4JSBrokenProjectException e) {
		LOGGER.error("Failed to obtain project description for external library.");
	}
	return null;
}
 
Example #5
Source File: FormattableDocument.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void addReplacer(ITextReplacer replacer) {
	if (!this.getRegion().contains(replacer.getRegion())) {
		String frameTitle = getClass().getSimpleName();
		ITextSegment frameRegion = getRegion();
		String replacerTitle = replacer.getClass().getSimpleName();
		ITextSegment replacerRegion = replacer.getRegion();
		RegionsOutsideFrameException exception = new RegionsOutsideFrameException(frameTitle, frameRegion,
				Tuples.create(replacerTitle, replacerRegion));
		getRequest().getExceptionHandler().accept(exception);
		return;
	}
	try {
		getReplacers().add(replacer, getFormatter().createTextReplacerMerger());
	} catch (ConflictingRegionsException e) {
		getRequest().getExceptionHandler().accept(e);
	}
}
 
Example #6
Source File: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToMain(JSONStringLiteral mainModuleJsonLiteral) {
	String mainPath = mainModuleJsonLiteral.getValue();
	if (!Strings.isNullOrEmpty(mainPath)) {
		URI packageJsonLoc = mainModuleJsonLiteral.eResource().getURI();
		IN4JSProject project = model.findProject(packageJsonLoc).orNull();
		INode node = NodeModelUtils.getNode(mainModuleJsonLiteral);

		if (project != null && node != null) {
			Region region = new Region(node.getOffset() + 1, node.getLength() - 2);
			SafeURI<?> mainResolvedPath = project.getLocation().resolve(mainPath);
			if (mainResolvedPath.exists()) {
				return Tuples.pair(mainResolvedPath, region);
			}
		}
	}

	return null;
}
 
Example #7
Source File: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToMainModule(JSONStringLiteral mainModuleJsonLiteral) {
	String mainModule = mainModuleJsonLiteral.getValue();
	if (!Strings.isNullOrEmpty(mainModule)) {
		URI packageJsonLoc = mainModuleJsonLiteral.eResource().getURI();
		IN4JSProject project = model.findProject(packageJsonLoc).orNull();
		INode node = NodeModelUtils.getNode(mainModuleJsonLiteral);

		if (project != null && node != null) {
			Region region = new Region(node.getOffset() + 1, node.getLength() - 2);

			for (IN4JSSourceContainer sc : project.getSourceContainers()) {
				QualifiedName qualifiedName = QualifiedName.create(mainModule);
				SafeURI<?> mainModuleURI = sc.findArtifact(qualifiedName,
						Optional.of(N4JSGlobals.N4JS_FILE_EXTENSION));
				if (mainModuleURI == null) {
					mainModuleURI = sc.findArtifact(qualifiedName, Optional.of(N4JSGlobals.N4JSX_FILE_EXTENSION));
				}
				if (mainModuleURI != null) {
					return Tuples.pair(mainModuleURI, region);
				}
			}
		}
	}

	return null;
}
 
Example #8
Source File: ParallelResourceLoader.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Load the {@link Resource} with the given {@link URI} and publish the load result.
 *
 * @param uri
 *          the {@link URI} of the {@link Resource} to be loaded
 */
protected void loadResource(final URI uri) {
  Throwable exception = null;
  Resource resource = null;
  currentlyProcessedUris.add(uri);

  if (parallelLoadingSupported(uri)) {
    try {
      resource = doLoadResource(uri);
      // CHECKSTYLE:OFF
    } catch (Throwable t) {
      // CHECKSTYLE:ON
      exception = t;
    }
  }

  currentlyProcessedUris.remove(uri);
  publishLoadResult(Tuples.create(uri, resource, exception));
}
 
Example #9
Source File: EcoreQualifiedNameProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
	return cache.get(Tuples.pair(obj, getCacheKey()), obj.eResource(), new Provider<QualifiedName>() {

		@Override
		public QualifiedName get() {
			EObject temp = obj;
			String name = nameDispatcher.invoke(temp);
			if (Strings.isEmpty(name))
				return null;
			QualifiedName qualifiedName = QualifiedName.create(name);
			if(!isRecurseParent(obj))
				return qualifiedName;
			QualifiedName parentsQualifiedName = getFullyQualifiedName(obj.eContainer());
			if (parentsQualifiedName == null)
				return null;
			else 
				return parentsQualifiedName.append(qualifiedName);
		}

	});
}
 
Example #10
Source File: SerializerTester.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected List<Pair<EObject, ICompositeNode>> detachNodeModel(EObject eObject) {
	EcoreUtil.resolveAll(eObject);
	List<Pair<EObject, ICompositeNode>> result = Lists.newArrayList();
	Iterator<Object> iterator = EcoreUtil.getAllContents(eObject.eResource(), false);
	while (iterator.hasNext()) {
		EObject object = (EObject) iterator.next();
		Iterator<Adapter> adapters = object.eAdapters().iterator();
		while (adapters.hasNext()) {
			Adapter adapter = adapters.next();
			if (adapter instanceof ICompositeNode) {
				adapters.remove();
				result.add(Tuples.create(object, (ICompositeNode) adapter));
				break;
			}
		}
	}
	return result;
}
 
Example #11
Source File: Storage2UriMapperImpl.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private Iterable<Pair<IStorage, IProject>> getStorages(/* @NonNull */ URI uri, IFile file) {
	if (file == null || !file.isAccessible()) {
		Iterable<Pair<IStorage, IProject>> result = contribution.getStorages(uri);
		if (result == null || !result.iterator().hasNext()) {
			 // Handle files external to the workspace. But check contribution first to be backwards compatible.
			if (uri.isFile()) {
				Path filePath = new Path(uri.toFileString());
				IFileStore fileStore = EFS.getLocalFileSystem().getStore(filePath);
				IFileInfo fileInfo = fileStore.fetchInfo();
				if (fileInfo.exists() && !fileInfo.isDirectory()) {
					return Collections.singletonList(
							Tuples.<IStorage, IProject> create(new FileStoreStorage(fileStore, fileInfo, filePath), (IProject) null));
				}
			}
		}
		return result;
	}
	return Collections.singleton(Tuples.<IStorage, IProject> create(file, file.getProject()));
}
 
Example #12
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected Pair<EObject, EObject> internalGetSelectedAstElements(EObject eObject, ITextRegion currentSelection) {
	ITextRegion textRegion = getTextRegion(eObject);
	while (textRegion.getOffset() == currentSelection.getOffset()) {
		EObject container = eObject.eContainer();
		if (container != null) {
			for (EObject obj : container.eContents()) {
				ITextRegion region = getTextRegion(obj);
				if (getEndOffset(region) == getEndOffset(currentSelection)) {
					Pair<EObject, EObject> parentMatch = internalGetSelectedAstElements(eObject.eContainer(), currentSelection);
					if (parentMatch != null)
						return parentMatch;
					return Tuples.create(eObject, obj);
				}
			}
		} else {
			if (textRegion.equals(currentSelection))
				return Tuples.create(eObject, eObject);
			return null;
		}
		eObject = container;
		textRegion = getTextRegion(eObject);
	}
	return null;
}
 
Example #13
Source File: DefaultFoldingStructureProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.17
 */
protected Collection<FoldedPosition> filterFoldedPositions(Collection<FoldedPosition> foldedPositions) {
	Map<Pair<Integer, Integer>, FoldedPosition> acceptedPositions = new HashMap<>();
	
	for (FoldedPosition foldedPosition : foldedPositions) {
		int startLineNumber = getLineNumber(foldedPosition.getOffset());
		int endLineNumber = getLineNumber(foldedPosition.getOffset() + foldedPosition.getLength());
		Pair<Integer, Integer> startAndEndLineNumbers = Tuples.create(startLineNumber, endLineNumber);
		
		if (!acceptedPositions.containsKey(startAndEndLineNumbers)) {
			acceptedPositions.put(startAndEndLineNumbers, foldedPosition);
		} else {
			// if the folded position has already been accepted, keep the one with the smaller region
			FoldedPosition alreadyAcceptedPosition = acceptedPositions.get(startAndEndLineNumbers);
			if(foldedPosition.getLength() < alreadyAcceptedPosition.getLength()) {
				acceptedPositions.put(startAndEndLineNumbers, foldedPosition);
			}
		}
	}
	
	return acceptedPositions.values();
}
 
Example #14
Source File: SerializerTester.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected List<Pair<EObject, ICompositeNode>> detachNodeModel(EObject eObject) {
	EcoreUtil.resolveAll(eObject);
	List<Pair<EObject, ICompositeNode>> result = Lists.newArrayList();
	Iterator<Object> iterator = EcoreUtil.getAllContents(eObject.eResource(), false);
	while (iterator.hasNext()) {
		EObject object = (EObject) iterator.next();
		Iterator<Adapter> adapters = object.eAdapters().iterator();
		while (adapters.hasNext()) {
			Adapter adapter = adapters.next();
			if (adapter instanceof ICompositeNode) {
				adapters.remove();
				result.add(Tuples.create(object, (ICompositeNode) adapter));
				break;
			}
		}
	}
	return result;
}
 
Example #15
Source File: ParallelResourceLoader.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void run() {
	Throwable exception = null;
	Resource resource = null;

	// load resource
	try {
		ResourceSet localResourceSet = resourceSetProvider.get();
		resource = loadResource(uri, localResourceSet, parent);
		localResourceSet.getResources().clear();
	} catch (Throwable t) {
		exception = t;
	}

	// push resource to the queue, wait if queue is full
	try {
		resourceQueue.put(Tuples.create(uri, resource, exception));
	} catch (InterruptedException e) {
		Thread.currentThread().interrupt();
	}
}
 
Example #16
Source File: NfaToProduction.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected <T> Pair<Integer, StateAlias<T>> findSplitState(StateAlias<T> state, Integer depth,
		Set<StateAlias<T>> visited) {
	if (!visited.add(state))
		return null;
	Pair<Integer, StateAlias<T>> result;
	if (state.getOutgoing().size() > 0 && state.getIncoming().size() > 0
			&& state.getOutgoing().size() + state.getIncoming().size() > 2)
		result = Tuples.create(depth, state);
	else
		result = null;
	for (StateAlias<T> out : state.getOutgoing()) {
		Pair<Integer, StateAlias<T>> cand = findSplitState(out, depth + 1, visited);
		if (cand != null && (result == null || isPreferredSplitState(cand, result)))
			result = cand;
	}
	return result;
}
 
Example #17
Source File: DotEObjectHover.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Out of the box, Xtext supports hovers only for identifying features of
 * model artifacts, i.e. the name of an object or crosslinks to other
 * objects (see locationInFileProvider.getSignificantTextRegion). That's why
 * this customization is needed to be able to also hover on the current dot
 * attribute values.
 */
@Override
protected Pair<EObject, IRegion> getXtextElementAt(XtextResource resource,
		int offset) {

	Pair<EObject, IRegion> result = super.getXtextElementAt(resource,
			offset);

	if (result == null) {
		EObject o = eObjectAtOffsetHelper.resolveElementAt(resource,
				offset);
		if (o != null) {
			// use fullTextRegion instead of the significantTtextRegion
			ITextRegion region = locationInFileProvider
					.getFullTextRegion(o);
			final IRegion region2 = new Region(region.getOffset(),
					region.getLength());
			if (TextUtilities.overlaps(region2, new Region(offset, 0)))
				return Tuples.create(o, region2);
		}
	}
	return result;
}
 
Example #18
Source File: AcfContentAssistProcessorTestBuilder.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Internally compute completion proposals.
 *
 * @param cursorPosition
 *          the position of the cursor in the {@link IXtextDocument}
 * @param xtextDocument
 *          the {@link IXtextDocument}
 * @return a pair of {@link ICompletionProposal}[] and {@link BadLocationException}. If the tail argument is not {@code null}, an exception occurred in the UI
 *         thread.
 */
private Pair<ICompletionProposal[], BadLocationException> internalComputeCompletionProposals(final int cursorPosition, final IXtextDocument xtextDocument) {
  XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
  Shell shell = new Shell();
  try {
    ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration);
    IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer);
    String contentType = xtextDocument.getContentType(cursorPosition);
    IContentAssistProcessor processor = contentAssistant.getContentAssistProcessor(contentType);
    if (processor != null) {
      return Tuples.create(processor.computeCompletionProposals(sourceViewer, cursorPosition), null);
    }
    return Tuples.create(new ICompletionProposal[0], null);
  } catch (BadLocationException e) {
    return Tuples.create(new ICompletionProposal[0], e);
  } finally {
    shell.dispose();
  }
}
 
Example #19
Source File: IReferableElementsUnloader.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void unloadRoot(EObject root) {
	// Content adapters should be removed the same way as they are added: top-down. 
	// Fragments are recursive, so we need them to be calculated before proxifying the container.
	// OTOH, some model elements resolve their children when being proxified (e.g. EPackageImpl).
	// => first calculate all fragments, then proxify elements starting form root.
	List<Pair<EObject, URI>> elementsToUnload = newArrayList();
	elementsToUnload.add(Tuples.create(root, EcoreUtil.getURI(root)));
	root.eAdapters().clear();
	for (Iterator<EObject> i = EcoreUtil.getAllProperContents(root, false); i.hasNext();) {
		EObject element = i.next();
		elementsToUnload.add(Tuples.create(element, EcoreUtil.getURI(element)));
		element.eAdapters().clear();
	}
	for (Pair<EObject,URI> elementToUnload : elementsToUnload) {
		((InternalEObject) elementToUnload.getFirst()).eSetProxyURI(elementToUnload.getSecond());
	}
}
 
Example #20
Source File: EcoreQualifiedNameProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
	return cache.get(Tuples.pair(obj, getCacheKey()), obj.eResource(), new Provider<QualifiedName>() {

		@Override
		public QualifiedName get() {
			EObject temp = obj;
			String name = nameDispatcher.invoke(temp);
			if (Strings.isEmpty(name))
				return null;
			QualifiedName qualifiedName = QualifiedName.create(name);
			if(!isRecurseParent(obj))
				return qualifiedName;
			QualifiedName parentsQualifiedName = getFullyQualifiedName(obj.eContainer());
			if (parentsQualifiedName == null)
				return null;
			else 
				return parentsQualifiedName.append(qualifiedName);
		}

	});
}
 
Example #21
Source File: SimpleLocalScopeProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IScope getScope(final EObject context, final EReference reference) {
	ISelectable resourceContent = cache.get(Tuples.pair(SimpleLocalScopeProvider.class.getName(), reference), 
			context.eResource(), new Provider<ISelectable>() {
		@Override
		public ISelectable get() {
			return getAllDescriptions(context.eResource());
		}
	});
	IScope globalScope = getGlobalScope(context.eResource(), reference);
	return createScope(globalScope, resourceContent, reference.getEReferenceType(), isIgnoreCase(reference));
}
 
Example #22
Source File: OnTheFlyJavaCompiler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <RT, T1, T2> Functions.Function2<T1, T2, RT> createFunction(
		String body, Class<RT> returnType, Class<T1> paramType1,
		Class<T2> paramType2) {
	return (Functions.Function2<T1, T2, RT>) internalCreateFunction(body,
			returnType, Tuples.pair((Type) paramType1, "p1"),
			Tuples.pair((Type) paramType2, "p2"));
}
 
Example #23
Source File: WorkbenchResolutionAdaptorRunTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private void mockMarkerResource(final URI uri) throws CoreException {
  // Resource is a file and so gets processed
  when(mockMarker.getResource()).thenReturn(mockFile);
  when(mockFile.getName()).thenReturn(uri.lastSegment());
  when(mockFile.findMarkers(anyString(), anyBoolean(), anyInt())).thenReturn(new IMarker[] {});
  when(mockMarker.getAttribute(eq(Issue.URI_KEY), anyString())).thenReturn(uri.toString());
  when(mockMarker.isSubtypeOf(eq(MarkerTypes.ANY_VALIDATION))).thenReturn(true);
  when(mockStorage2UriMapper.getUri(eq(mockFile))).thenReturn(uri);
  @SuppressWarnings("unchecked")
  Iterable<Pair<IStorage, IProject>> storages = Lists.newArrayList(Tuples.create((IStorage) mockFile, mock(IProject.class)));
  when(mockStorage2UriMapper.getStorages(eq(uri))).thenReturn(storages);
  when(mockLanguageResourceHelper.isLanguageResource(eq(mockFile))).thenReturn(true);
}
 
Example #24
Source File: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToDependencySection(NameValuePair projectNameInValue) {
	JSONStringLiteral jsonValue = (JSONStringLiteral) projectNameInValue.getValue();
	String projectName = jsonValue.getValue();
	SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));

	if (pdu != null) {
		INode valueNode = NodeModelUtils.getNode(jsonValue);
		Region region = new Region(valueNode.getOffset() + 1, valueNode.getLength() - 2);

		return Tuples.pair(pdu, region);
	}
	return null;
}
 
Example #25
Source File: ImportedNamespaceAwareLocalScopeProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected List<ImportNormalizer> getImportedNamespaceResolvers(final EObject context, final boolean ignoreCase) {
	return cache.get(Tuples.create(context, ignoreCase, "imports"), context.eResource(), new Provider<List<ImportNormalizer>>() {
		@Override
		public List<ImportNormalizer> get() {
			return internalGetImportedNamespaceResolvers(context, ignoreCase);
		}
	});
}
 
Example #26
Source File: AbstractEObjectHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Call this method only from within an IUnitOfWork
 */
protected Pair<EObject, IRegion> getXtextElementAt(XtextResource resource, final int offset) {
	// check for cross reference
	EObject crossLinkedEObject = eObjectAtOffsetHelper.resolveCrossReferencedElementAt(resource, offset);
	if (crossLinkedEObject != null) {
		if (!crossLinkedEObject.eIsProxy()) {
			IParseResult parseResult = resource.getParseResult();
			if (parseResult != null) {
				ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
				if(leafNode != null && leafNode.isHidden() && leafNode.getOffset() == offset) {
					leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
				}
				if (leafNode != null) {
					ITextRegion leafRegion = leafNode.getTextRegion();
					return Tuples.create(crossLinkedEObject, (IRegion) new Region(leafRegion.getOffset(), leafRegion.getLength()));
				}
			}
		}
	} else {
		EObject o = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
		if (o != null) {
			ITextRegion region = locationInFileProvider.getSignificantTextRegion(o);
			final IRegion region2 = new Region(region.getOffset(), region.getLength());
			if (TextUtilities.overlaps(region2, new Region(offset, 0)))
				return Tuples.create(o, region2);
		}
	}
	return null;
}
 
Example #27
Source File: AbstractCachingResourceDescriptionManager.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns all resolved imported names from a given resource description.
 *
 * @param candidate
 *          the resource description
 * @return a collection of names
 */
protected Pair<Collection<QualifiedName>, Collection<QualifiedName>> getResolvedAndUnresolvedImportedNames(final IResourceDescription candidate) {
  Iterable<QualifiedName> importedNames = candidate.getImportedNames();
  Set<QualifiedName> resolved = Sets.newHashSetWithExpectedSize(Iterables.size(importedNames));
  Set<QualifiedName> unresolved = Sets.newHashSet();
  for (QualifiedName name : importedNames) {
    if (QualifiedNames.isUnresolvedName(name)) {
      unresolved.add(name);
    } else {
      resolved.add(name);
    }
  }
  return Tuples.<Collection<QualifiedName>, Collection<QualifiedName>> pair(resolved, unresolved);
}
 
Example #28
Source File: AbstractTypeProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public <E> E get(final Object key, final Resource resource, final Provider<E> provider) {
  if (resource == null) {
    return provider.get();
  }
  CacheAdapter adapter = getOrCreate(resource);
  Pair<AbstractCyclicHandlingSupport<T>, Object> composedKey = Tuples.create(AbstractCyclicHandlingSupport.this, key);
  E element = adapter.<E> get(composedKey);
  // we could have unloaded cached values that were contained in another resource
  // thus #resource was never notified about the change
  boolean validEntry = element != null;
  if (validEntry && element instanceof EObject) {
    validEntry = !((EObject) element).eIsProxy(); // NOPMD
  }
  if (!validEntry) {
    cacheMiss(adapter);
    element = provider.get();
    @SuppressWarnings("unchecked")
    ImmutableLinkedItem<E> linkedItem = (ImmutableLinkedItem<E>) key;
    if (!(linkedItem.object instanceof EObject)) {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("cache skip: " + element); //$NON-NLS-1$
      }
      return element;
    }
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("cache: " + element); //$NON-NLS-1$
    }
    adapter.set(composedKey, element);
  } else {
    cacheHit(adapter);
  }
  return element;
}
 
Example #29
Source File: AbstractXtextInspectorTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void acceptInfo(String message, EObject object, EStructuralFeature feature, int index, String code, String... issueData) {
	if (!isExpectingInfos())
		fail("unexpected call to acceptInfo");
	Triple<String,EObject,EStructuralFeature> warning = Tuples.create(message, object, feature);
	infos.add(warning);
}
 
Example #30
Source File: XbaseDispatchingEObjectTextHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Pair<EObject, IRegion> getXtextElementAt(XtextResource resource, int offset) {
	Pair<EObject, IRegion> original = super.getXtextElementAt(resource, offset);
	if (original != null) {
		EObject object = eObjectAtOffsetHelper.resolveContainedElementAt(resource, offset);
		if (object instanceof XAbstractFeatureCall){
			JvmIdentifiableElement feature = ((XAbstractFeatureCall) object).getFeature();
			if(feature instanceof JvmExecutable 
					|| feature instanceof JvmField 
					|| feature instanceof JvmConstructor 
					|| feature instanceof XVariableDeclaration 
					|| feature instanceof JvmFormalParameter)
				return Tuples.create(object, original.getSecond());
		} else if (object instanceof XConstructorCall){
				return Tuples.create(object, original.getSecond());
		}
	}
	
	EObjectInComment eObjectReferencedInComment = javaDocTypeReferenceProvider.computeEObjectReferencedInComment(resource, offset);
	if(eObjectReferencedInComment != null) {
		EObject eObject = eObjectReferencedInComment.getEObject();
		ITextRegion region = eObjectReferencedInComment.getRegion();
		return Tuples.create(eObject, new Region(region.getOffset(), region.getLength()));
	}
	
	return original;
}