org.eclipse.xtext.util.Pair Java Examples

The following examples show how to use org.eclipse.xtext.util.Pair. 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: ProjectUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @return null if there is no such file or the file is not editable
 */
public IFile findFileStorage(final URI uri, final boolean validateEdit) {
	Iterable<Pair<IStorage, IProject>> storages = mapper.getStorages(uri);
	try {
		Pair<IStorage, IProject> fileStorage = Iterables.find(storages, new Predicate<Pair<IStorage, IProject>>() {
			@Override
			public boolean apply(Pair<IStorage, IProject> input) {
				IStorage storage = input.getFirst();
				if (storage instanceof IFile) {
					IFile file = (IFile) storage;
					return file.isAccessible()
							&& (!validateEdit || !file.isReadOnly() || workspace.validateEdit(new IFile[] { file },
									null).isOK());
				}
				return false;
			}
		});
		return (IFile) fileStorage.getFirst();
	} catch (NoSuchElementException e) {
		return null;
	}
}
 
Example #2
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 #3
Source File: AcfContentAssistProcessorTestBuilder.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc} Code copied from parent. Override required to run in UI because of getSourceViewer, which creates a new Shell.
 */
@Override
public ICompletionProposal[] computeCompletionProposals(final String currentModelToParse, final int cursorPosition) throws Exception {
  Pair<ICompletionProposal[], BadLocationException> result = UiThreadDispatcher.dispatchAndWait(new Function<Pair<ICompletionProposal[], BadLocationException>>() {
    @Override
    public Pair<ICompletionProposal[], BadLocationException> run() {
      final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse));
      final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse);
      return internalComputeCompletionProposals(cursorPosition, xtextDocument);
    }
  });
  if (result.getSecond() != null) {
    throw result.getSecond();
  }
  return result.getFirst();
}
 
Example #4
Source File: EclipseExternalLibraryWorkspace.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public FileURI getLocation(ProjectReference reference) {
	N4JSProjectName name = new N4JSProjectName(reference.getProjectName());
	N4JSExternalProject project = projectProvider.getProject(name);

	if (null == project) {
		return null;
	}

	FileURI refLocation = (FileURI) project.getIProject().getLocation();
	Pair<N4JSExternalProject, ProjectDescription> pair = projectProvider.getProjectWithDescription(refLocation);
	if (null != pair) {
		return refLocation;
	}

	return null;
}
 
Example #5
Source File: AssignmentQuantityAllocator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public String toString(Map<ISyntaxConstraint, Pair<Integer, Integer>> minmax) {
	Map<ISyntaxConstraint, String> postfix = Maps.newHashMap();
	for (Map.Entry<ISyntaxConstraint, Integer> e : assignmentQuants.entrySet()) {
		String s = ":" + e.getValue();
		if (minmax != null && minmax.containsKey(e.getKey())) {
			Pair<Integer, Integer> p = minmax.get(e.getKey());
			s += "<" + p.getFirst() + "," + (p.getSecond() == Integer.MAX_VALUE ? "*" : p.getSecond()) + ">";
		}
		postfix.put(e.getKey(), s);
	}
	Iterator<ISyntaxConstraint> i = assignmentQuants.keySet().iterator();
	if (!i.hasNext())
		return "";
	ISyntaxConstraint root = i.next();
	while (i.hasNext())
		root = root.findCommonContainer(i.next());
	return root.toString(postfix);
}
 
Example #6
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 #7
Source File: XtendHoverSerializer.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public Pair<String, String> computePreAndSuffix(EObject element) {
	ICompositeNode node = NodeModelUtils.getNode(element);
	if (node != null) {
		XtextResource resource = (XtextResource) element.eResource();
		if (resource != null) {
			IParseResult parseResult = resource.getParseResult();
			if (parseResult != null) {
				String model = parseResult.getRootNode().getText();
				return Tuples.create(model.substring(0, node.getTotalOffset()) + "\n",
						"\n" + model.substring(node.getTotalEndOffset()));
			}
		}
	}
	return Tuples.create("", "");

}
 
Example #8
Source File: ValidMarkerUpdateJob.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets an {@link IFile} from the {@link IStorage2UriMapper} corresponding to given {@link URI}. If none
 * could be found, <code>null</code> is returned.
 *
 * @param uri
 *          the URI
 * @return the file from the storage to URI mapper or <code>null</code> if no match found
 */
private IFile getFileFromStorageMapper(final URI uri) {
  if (storage2UriMapper == null) {
    return null; // Should not occur
  }

  for (Pair<IStorage, IProject> storage : storage2UriMapper.getStorages(uri)) {
    if (storage.getFirst() instanceof IFile) {
      return (IFile) storage.getFirst();
    }
  }
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug(MessageFormat.format("Could not find storage for URI {0}", uri.toString())); //$NON-NLS-1$
  }
  return null;
}
 
Example #9
Source File: AbstractTraceRegion.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected Map<SourceRelativeURI, List<Pair<ILocationData, AbstractTraceRegion>>> collectMatchingLocations(
		SourceRelativeURI expectedAssociatedPath) {
	Map<SourceRelativeURI, List<Pair<ILocationData, AbstractTraceRegion>>> result = Maps
			.newHashMapWithExpectedSize(2);
	Iterator<AbstractTraceRegion> treeIterator = treeIterator();
	while (treeIterator.hasNext()) {
		AbstractTraceRegion next = treeIterator.next();
		SourceRelativeURI associatedPath = next.getAssociatedSrcRelativePath();
		List<Pair<ILocationData, AbstractTraceRegion>> matchingLocations = getCollectingList(associatedPath,
				expectedAssociatedPath, result);
		for (ILocationData locationData : next.getAssociatedLocations()) {
			if (associatedPath == null) {
				matchingLocations = getCollectingList(locationData.getSrcRelativePath(), expectedAssociatedPath, result);
			}
			if (matchingLocations != null) {
				matchingLocations.add(Tuples.create(locationData, next));
			}
		}
	}
	return result;
}
 
Example #10
Source File: ExternalProjectMappings.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new external library workspace instance with the preference store that provides the configured library
 * location.
 *
 * @param preferenceStore
 *            the preference store to get the registered external library locations.
 */
protected ExternalProjectMappings(EclipseBasedN4JSWorkspace userWorkspace,
		ExternalLibraryPreferenceStore preferenceStore,
		Map<FileURI, Pair<N4JSExternalProject, ProjectDescription>> completeCache, boolean initialized) {

	this.userWorkspace = userWorkspace;
	this.preferenceStore = preferenceStore;

	this.completeCache = completeCache != null ? new LinkedHashMap<>(completeCache) : Collections.emptyMap();
	removeDuplicatesFromCompleteCache();

	Mappings mappings = computeMappings();
	this.completeList = mappings.completeList;
	this.completeProjectNameMapping = mappings.completeProjectNameMapping;
	this.reducedProjectUriMapping = mappings.reducedProjectUriMapping;
	this.reducedProjectsLocationMapping = mappings.reducedProjectsLocationMapping;
	this.reducedSet = mappings.reducedSet;
	this.initialized = initialized;
}
 
Example #11
Source File: ConcreteSyntaxValidator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected List<IConcreteSyntaxDiagnostic> validateQuantities(IQuantities quants, ISyntaxConstraint rule) {
	List<IConcreteSyntaxDiagnostic> diag = new ArrayList<IConcreteSyntaxDiagnostic>();
	Map<ISyntaxConstraint, Pair<Integer, Integer>> minmax = Maps.newHashMap();
	for (Map.Entry<EStructuralFeature, Collection<ISyntaxConstraint>> e : quants.groupByFeature().entrySet()) {
		int min = UNDEF, max = 0;
		Set<ISyntaxConstraint> involved = new HashSet<ISyntaxConstraint>();
		for (ISyntaxConstraint a : e.getValue()) {
			involved.add(a);
			int mi = intervalProvider.getMin(quants, a, involved);
			if (mi != UNDEF)
				min = min == UNDEF ? mi : mi + min;
			int ma = intervalProvider.getMax(quants, a, involved, null);
			if (ma != UNDEF && max != MAX)
				max = ma == MAX ? ma : max + ma;
			minmax.put(a, Tuples.create(mi, ma));
		}
		int actual = quants.getFeatureQuantity(e.getKey());
		if (actual < min || actual > max)
			diag.add(diagnosticProvider.createFeatureQuantityDiagnostic(rule, quants, e.getKey(), actual, min, max,
					involved));
	}
	//		System.out.println("Validation: " + obj.toString(minmax));
	return diag;
}
 
Example #12
Source File: DerivedResourceMarkerBasedOpenerContributor.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean collectSourceFileOpeners(IEditorPart editor, IAcceptor<FileOpener> acceptor) {
	IStorage storage = getStorage(editor);
	if (storage instanceof IResource) {
		IResource resource = (IResource) storage;
		try {
			Set<URI> uris = Sets.newHashSet();
			IMarker[] markers = derivedResourceMarkers.findDerivedResourceMarkers(resource);
			for (IMarker marker : markers) {
				String source = derivedResourceMarkers.getSource(marker);
				if (source != null)
					uris.add(URI.createURI(source));
			}
			for (URI uri : uris)
				for (Pair<IStorage, IProject> destination : storage2UriMapper.getStorages(uri))
					acceptor.accept(createOpener(destination.getFirst()));
			return true;
		} catch (CoreException e) {
			LOG.error(e.getMessage(), e);
		}
	}
	return false;
}
 
Example #13
Source File: AbstractUtilTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Prepare mocks for all tests.
 */
public static void prepareMocksBase() {
  oldDesc = mock(IResourceDescription.class);
  newDesc = mock(IResourceDescription.class);
  delta = mock(Delta.class);
  resource = mock(Resource.class);
  uriCorrect = mock(URI.class);
  when(uriCorrect.isPlatformResource()).thenReturn(true);
  when(uriCorrect.isFile()).thenReturn(true);
  when(uriCorrect.toFileString()).thenReturn(DUMMY_PATH);
  when(uriCorrect.toPlatformString(true)).thenReturn(DUMMY_PATH);
  when(delta.getNew()).thenReturn(newDesc);
  when(delta.getOld()).thenReturn(oldDesc);
  when(delta.getUri()).thenReturn(uriCorrect);
  when(resource.getURI()).thenReturn(uriCorrect);
  file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uriCorrect.toPlatformString(true)));
  Iterable<Pair<IStorage, IProject>> storages = singleton(Tuples.<IStorage, IProject> create(file, file.getProject()));
  mapperCorrect = mock(Storage2UriMapperImpl.class);
  when(mapperCorrect.getStorages(uriCorrect)).thenReturn(storages);
}
 
Example #14
Source File: HiddenAndTokenNodeIterator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private INode findNext() {
	if (nextNodes.isEmpty()) {
		while (nodeIterator.hasNext()) {
			INode candidate = nodeIterator.next();
			if (tokenUtil.isToken(candidate)) {
				nodeIterator.prune();
				Pair<List<ILeafNode>, List<ILeafNode>> leadingAndTrailingHiddenTokens = tokenUtil
						.getLeadingAndTrailingHiddenTokens(candidate);
				nextNodes.addAll(leadingAndTrailingHiddenTokens.getFirst());
				nextNodes.add(candidate);
				nextNodes.addAll(leadingAndTrailingHiddenTokens.getSecond());
				return nextNodes.poll();
			} else if (tokenUtil.isWhitespaceOrCommentNode(candidate)) {
				return candidate;
			}
		}
		return null;
	}
	return nextNodes.poll();
}
 
Example #15
Source File: RawTypeReferenceComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public JvmTypeReference doVisitCompoundTypeReference(JvmCompoundTypeReference reference, Pair<Resource, Set<JvmType>> context) {
	JvmCompoundTypeReference result = null;
	List<JvmTypeReference> components = reference.getReferences();
	int recent = -1;
	for (int i = 0; i < components.size(); i++) {
		JvmTypeReference component = components.get(i);
		JvmTypeReference rawType = visit(component, context);
		if (rawType != null && component != rawType) {
			if (result == null) {
				result = (JvmCompoundTypeReference) EcoreUtil.create(reference.eClass());
			}
			for (int j = recent + 1; j < i; j++) {
				result.getReferences().add(components.get(j));
			}
			result.getReferences().add(rawType);
			recent = i;
		}
	}
	if (result != null)
		return result;
	return reference;
}
 
Example #16
Source File: ExternalProjectMappings.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
Set<SafeURI<?>> computeUserWorkspaceDependencies(
		Map<N4JSProjectName, List<N4JSExternalProject>> completeProjectNameMappingTmp,
		Map<FileURI, Pair<N4JSExternalProject, ProjectDescription>> reducedProjectUriMappingTmp) {

	Set<SafeURI<?>> uwsDeps = new HashSet<>();
	// respect closed workspace projects by omitting them
	Collection<SafeURI<?>> projectsInUserWSopen = new LinkedList<>();
	for (PlatformResourceURI projectInUserWS : userWorkspace.getAllProjectLocations()) {
		projectsInUserWSopen.add(projectInUserWS);
	}

	computeNecessaryDependenciesRek(completeProjectNameMappingTmp, reducedProjectUriMappingTmp,
			projectsInUserWSopen, uwsDeps);
	uwsDeps.removeAll(projectsInUserWSopen);

	return uwsDeps;
}
 
Example #17
Source File: StringProduction.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected ProdElement parsePrim(Stack<Pair<Token, String>> tokens) {
	Pair<Token, String> current = tokens.pop();
	switch (current.getFirst()) {
		case PL:
			ProdElement result1 = parseAlt(tokens);
			if (tokens.peek().getFirst().equals(Token.PR))
				tokens.pop();
			else
				throw new RuntimeException("')' expected, but " + tokens.peek().getFirst() + " found");
			parseCardinality(tokens, result1);
			return result1;
		case STRING:
			ProdElement result2 = createElement(ElementType.TOKEN);
			result2.value = current.getSecond();
			parseCardinality(tokens, result2);
			return result2;
		case ID:
			ProdElement result3 = createElement(ElementType.TOKEN);
			result3.name = current.getSecond();
			parseCardinality(tokens, result3);
			return result3;
		default:
			throw new RuntimeException("Unexpected token " + current.getFirst());
	}
}
 
Example #18
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 #19
Source File: BacktrackingSemanticSequencer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isValueValid(ISemState state, int index, Object value) {
	List<AbstractElement> candidates = state.getToBeValidatedAssignedElements();
	if (candidates.isEmpty())
		return true;

	Pair<AbstractElement, Integer> key = Tuples.create(state.getAssignedGrammarElement(), index);
	if (valid.get(key) == Boolean.TRUE)
		return true;

	ISemanticNode semanticNode = getNode(state.getFeatureID(), index);
	INode node = semanticNode == null ? null : semanticNode.getNode();
	Multimap<AbstractElement, ISerializationContext> assignments = ArrayListMultimap.create();
	for (AbstractElement ele : candidates)
		assignments.put(ele, context);
	Set<AbstractElement> found = assignmentFinder.findAssignmentsByValue(eObject, assignments, value, node);
	boolean result = found.contains(state.getAssignedGrammarElement());
	valid.put(key, result);
	return result;
}
 
Example #20
Source File: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private SafeURI<?> getProjectDescriptionLocationForName(N4JSProjectName projectName) {
	IN4JSProject project = model.findAllProjectMappings().get(projectName);
	SafeURI<?> rootLocation = null;
	if (project == null) {
		for (Pair<FileURI, ProjectDescription> pair : extWS.getProjectsIncludingUnnecessary()) {
			String name = pair.getSecond().getProjectName();
			if (name != null && Objects.equal(projectName, new N4JSProjectName(name))) {
				rootLocation = pair.getFirst();
			}
		}
	} else {
		rootLocation = project.getLocation();
	}

	if (rootLocation != null) {
		SafeURI<?> pckjsonUri = rootLocation.appendSegment(IN4JSProject.PACKAGE_JSON);
		return pckjsonUri;
	}
	return null;
}
 
Example #21
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 #22
Source File: XtextSpyLabelProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts")
public Image getImage(final Object element) {
  Image image = super.getImage(element);
  if (image != null) {
    Pair<Object, Integer> decoration = getDecoration(element);
    if (decoration != null && decoration.getFirst() != null) {
      Image overlay = convertToImage(decoration.getFirst());
      if (overlay != null) {
        image = new DecorationOverlayIcon(image, ImageDescriptor.createFromImage(overlay), decoration.getSecond()).createImage();
      }
    }
  }
  return image;
}
 
Example #23
Source File: CheckEclipseGeneratorConfigProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public CheckGeneratorConfig get(final URI uri) {
  CheckGeneratorConfig result = new CheckGeneratorConfig();
  IProject project = null;
  if (uri != null) {
    Pair<IStorage, IProject> pair = Iterables.getFirst(storage2UriMapper.getStorages(uri), null);
    if (pair != null) {
      project = pair.getSecond();
    }
  }
  xbaseBuilderPreferenceAccess.loadBuilderPreferences(result, project);
  return result;
}
 
Example #24
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public ITextRegion selectNext(XtextResource resource, ITextRegion currentEditorSelection) {
	Pair<EObject, EObject> currentlySelected = getSelectedAstElements(resource, currentEditorSelection);
	if (currentlySelected == null) {
		return selectEnclosing(resource, currentEditorSelection);
	}
	EObject second = currentlySelected.getSecond();
	EObject nextSibling = EcoreUtil2.getNextSibling(second);
	if (nextSibling != null) {
		return register(getRegion(Tuples.create(currentlySelected.getFirst(), nextSibling)));
	} else {
		if (second.eContainer() == null)
			return ITextRegion.EMPTY_REGION;
		return register(getRegion(Tuples.create(second.eContainer(), second.eContainer())));
	}
}
 
Example #25
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;
}
 
Example #26
Source File: JavaBreakPointProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IEclipseTrace getJavaTrace(final IJavaStratumLineBreakpoint breakpoint) throws CoreException {
	IEclipseTrace result;
	IClassFile classFile = getClassFile(breakpoint);
	if (classFile == null) {
		URI uri = URI.createURI((String) breakpoint.getMarker().getAttribute(
				StratumBreakpointAdapterFactory.ORG_ECLIPSE_XTEXT_XBASE_SOURCE_URI));
		Pair<IStorage, IProject> storage = Iterables.getFirst(storage2UriMapper.getStorages(uri), null);
		if (storage == null)
			return null;
		result = traceForStorageProvider.getTraceToTarget(storage.getFirst());
	} else {
		result = traceForTypeRootProvider.getTraceToSource(classFile);
	}
	return result;
}
 
Example #27
Source File: JvmTypesBuilder.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a public enum declaration, associated to the given sourceElement. It sets the given name, which might be
 * fully qualified using the standard Java notation.
 * 
 * @param sourceElement
 *            the sourceElement the resulting element is associated with.
 * @param name
 *            the qualified name of the resulting enum type.
 * @param initializer
 *            the initializer to apply on the created enumeration type. If <code>null</code>, the enum won't be initialized.
 * 
 * @return a result representing a Java enum type with the given name, <code>null</code> 
 *            if sourceElement or name are <code>null</code>.
 */
/* @Nullable */ 
public JvmEnumerationType toEnumerationType(/* @Nullable */ EObject sourceElement, /* @Nullable */ String name, 
		/* @Nullable */ Procedure1<? super JvmEnumerationType> initializer) {
	if (sourceElement == null || name == null)
		return null;
	Pair<String, String> fullName = splitQualifiedName(name);
	JvmEnumerationType result = typesFactory.createJvmEnumerationType();
	result.setSimpleName(fullName.getSecond());
	result.setVisibility(JvmVisibility.PUBLIC);
	if (fullName.getFirst() != null)
		result.setPackageName(fullName.getFirst());
	associate(sourceElement, result);
	return initializeSafely(result, initializer);
}
 
Example #28
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 #29
Source File: BuiltinSchemeUriMapperContribution.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(URI uri) {
	if (N4Scheme.isN4Scheme(uri)) {
		Pair<IStorage, IProject> result = Tuples.create(new N4SchemeURIBasedStorage(uri.trimFragment(), registrar),
				null);
		return Collections.singletonList(result);
	}
	return Collections.emptyList();
}
 
Example #30
Source File: FormattingConfigBasedStream.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public Pair<AbstractRule, String> getSpaces(LineEntry entry, boolean isLineStart) {
	String space = getSpacesStr(entry, isLineStart);
	if (space == null)
		return null;
	AbstractRule rule = hiddenTokenHelper.getWhitespaceRuleFor(entry.hiddenTokenDefinition, space);
	if (rule == null)
		return null;
	return Tuples.create(rule, space);
}