Java Code Examples for org.eclipse.xtext.util.Pair#getFirst()

The following examples show how to use org.eclipse.xtext.util.Pair#getFirst() . 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: 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 2
Source File: IssuesProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public List<Issue> getPersistedIssues(URI uri) {
	List<Issue> result = Lists.newArrayList();
	Iterable<Pair<IStorage, IProject>> storages = mapper.getStorages(uri);
	for (Pair<IStorage, IProject> storageToProject : storages) {
		IStorage iStorage = storageToProject.getFirst();
		if (iStorage instanceof IFile) {
			try {
				IMarker[] markers;
				markers = ((IFile) iStorage).findMarkers(EValidator.MARKER, true, 1);
				for (IMarker iMarker : markers) {
					Issue issue = issueUtil.createIssue(iMarker);
					if(issue != null)
						result.add(issue);
				}
			} catch (CoreException e) {
				log.error(e.getMessage(), e);
			}
		}
	}
	return result;
}
 
Example 3
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 4
Source File: AbstractLabelingTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Tests that the expected elements and their labels are exactly identical to all elements of the default test resource.
 */
@Test
public void testLabels() {
  if (getExpectedElementLabels() == null) {
    return; // TODO: remove this check once all tests have been refactored
  }
  for (Pair<ENamedElement, String> elementLabel : getExpectedElementLabels()) {
    if (elementLabel.getFirst() instanceof EClass) {
      // TODO: remove this once all tests have been refactored
      assertHasLabel(((EClass) elementLabel.getFirst()).getInstanceClass(), elementLabel.getSecond());
    } else {
      assertHasLabel(elementLabel.getFirst(), elementLabel.getSecond());
    }
  }
  // assertLabelMapConsistsOf(getExpectedElementLabels()); // TODO : revisit and enable this once all tests have been refactored
}
 
Example 5
Source File: RuntimeProjectUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the file {@link IFile} based on its {@link URI}.
 *
 * @param uri
 *          the URI of the resource for which an IFile is to be returned
 * @param mapper
 *          class returning e.g. set of storages {@link IStorage} matching given URI; injected by concrete BuilderParticipant
 * @return the file associated with given URI
 */
public static IFile findFileStorage(final URI uri, final IStorage2UriMapper mapper) {
  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(final Pair<IStorage, IProject> input) {
        IStorage storage = input.getFirst();
        if (storage instanceof IFile) {
          return true;
        }
        return false;
      }
    });

    return (IFile) fileStorage.getFirst();
  } catch (NoSuchElementException e) {
    LOGGER.debug("Cannot find file storage for " + uri); //$NON-NLS-1$
    return null;
  }
}
 
Example 6
Source File: StorageAwareTrace.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IStorage findStorage(SourceRelativeURI uri, IProject project) {
	AbsoluteURI resolvePath = resolvePath(uri);
	Iterable<Pair<IStorage, IProject>> allStorages = getStorage2uriMapper().getStorages(resolvePath.getURI());
	for (Pair<IStorage, IProject> storage : allStorages) {
		if (project.equals(storage.getSecond())) {
			return storage.getFirst();
		}
	}
	return null;
}
 
Example 7
Source File: PdaUtil.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public <S, P, D extends Pda<S, P>> Map<S, S> mapPopAndPush(Pda<S, P> pda) {
	Map<P, Pair<S, S>> popsAndPushs = collectPopsAndPushs(pda);
	Map<S, S> result = Maps.newLinkedHashMap();
	for (Pair<S, S> p : popsAndPushs.values()) {
		S push = p.getFirst();
		S pop = p.getSecond();
		if (push != null && pop != null) {
			result.put(push, pop);
			result.put(pop, push);
		}
	}
	return result;
}
 
Example 8
Source File: ElementMatcherProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected Collection<T> patternsForTransition(Pair<List<MatcherTransition>, List<MatcherState>> transition) {
	List<IElementPattern> result = Lists.newArrayList();
	Set<MatcherState> exits = Sets.newHashSet(transition.getSecond());
	for (MatcherTransition transitio : transition.getFirst())
		result.addAll(transitio.getPatterns(exits));
	return (Collection<T>) result;
}
 
Example 9
Source File: XbaseReferenceUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void createTextChange(ITextRegion referenceTextRegion, String newReferenceText, EObject referringElement,
		EObject newTargetElement, EReference reference, URI referringResourceURI,
		IRefactoringUpdateAcceptor updateAcceptor) {
	if (newReferenceText != null && updateAcceptor instanceof ImportAwareUpdateAcceptor && isReferenceToJvmType(newTargetElement, reference)) {
		JvmType newTargetType = (JvmType) newTargetElement;
		ImportAwareUpdateAcceptor importAwareUpdateAcceptor = (ImportAwareUpdateAcceptor) updateAcceptor;
		
		Pair<JvmDeclaredType, QualifiedName> importedTypeAndRelativeName = getImportedTypeAndRelativeName(newTargetType, importAwareUpdateAcceptor.getImportSection());
		if(importedTypeAndRelativeName != null) {
			JvmDeclaredType importedType = importedTypeAndRelativeName.getFirst();
			QualifiedName importRelativeName = importedTypeAndRelativeName.getSecond();
			
			importAwareUpdateAcceptor.removeImport(importedType, false, false, null);
			if (isReferencedByQualifiedName(referringElement, newTargetType, importRelativeName)) {
				QualifiedName newTypeQualifiedName = qualifiedNameProvider.getFullyQualifiedName(newTargetElement);
				newReferenceText = getLinkText(newTypeQualifiedName, newReferenceText);
			} else {
				if(!isEmpty(importedType.getPackageName())) { 
					importAwareUpdateAcceptor.acceptImport(importedType, false, false, null);
				}
				newReferenceText = getLinkText(importRelativeName, newReferenceText);
			}
		}
	}
	super.createTextChange(referenceTextRegion, newReferenceText, referringElement, newTargetElement, reference,
			referringResourceURI, updateAcceptor);
}
 
Example 10
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected ITextRegion getRegion(Pair<EObject, EObject> selection) {
	final ITextRegion firstRegion = getTextRegion(selection.getFirst());
	if (selection.getFirst() == selection.getSecond()) {
		return firstRegion;
	}
	ITextRegion secondRegion = getTextRegion(selection.getSecond());
	return new TextRegion(firstRegion.getOffset(), getEndOffset(secondRegion) - firstRegion.getOffset());
}
 
Example 11
Source File: ConcreteSyntaxConstraintProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Set<EClass> getSemanticTypeByParent(Set<ISyntaxConstraint> exclude) {
	if (type == ConstraintType.ALTERNATIVE) {
		exclude.addAll(getContents());
		if (semanticType != null)
			return Sets.newHashSet(semanticType);
	} else {
		Pair<Set<EClass>, Set<EClass>> types = getAllSemanticTypesPairs(exclude);
		if (!types.getFirst().isEmpty())
			return types.getFirst();
		if (isRoot())
			return types.getSecond();
	}
	return ((SyntaxConstraintNode) getContainer()).getSemanticTypeByParent(exclude);
}
 
Example 12
Source File: DefaultResourceUIServiceProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.9
 */
@Override
public boolean isSource(URI uri) {
	if (delegate instanceof IResourceServiceProviderExtension) {
		if (!((IResourceServiceProviderExtension) delegate).isSource(uri))
			return false;
	}
	if (workspace != null) {
		if (uri.isPlatformResource()) {
			String projectName = URI.decode(uri.segment(1));
			IProject project = workspace.getRoot().getProject(projectName);
			return project.isAccessible();
		}
		if (uri.isPlatformPlugin()) {
			return false;
		}
	}
	Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(uri);
	for (Pair<IStorage, IProject> pair : storages) {
		IStorage storage = pair.getFirst();
		if (storage instanceof IFile) {
			return ((IFile)storage).isAccessible();
		} else {
			return false;
		}
	}
	return true;
}
 
Example 13
Source File: ProcessResult.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String toString() {
	String s = "Result:\n";
	for (Pair<String, String> prop : getProperties()) {
		String first = prop.getFirst();
		String second = prop.getSecond();
		if (first == null) {
			s += second + "\n";
		} else {
			s += String.format("%s%-12s:   %s\n", IDENT1, first, second);
		}
	}
	s += "Result End.\n";
	return s;
}
 
Example 14
Source File: XtendHoverProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected XtextBrowserInformationControlInput getHoverInfo(EObject element, IRegion hoverRegion,
		XtextBrowserInformationControlInput previous) {
	XtextBrowserInformationControlInput hoverInfo = super.getHoverInfo(element, hoverRegion, previous);
	if(hoverInfo instanceof XbaseInformationControlInput){
		XbaseInformationControlInput xbaseHoverInfo = (XbaseInformationControlInput) hoverInfo;
		Pair<String, String> prefixAndSuffixPair = xtendHoverSerializer.computePreAndSuffix(element);
		String unsugaredExpression = xtendHoverSerializer.computeUnsugaredExpression(element);
		return new XbaseInformationControlInput(previous, xbaseHoverInfo, prefixAndSuffixPair.getFirst(), unsugaredExpression, prefixAndSuffixPair.getSecond());
	}
	return hoverInfo;
}
 
Example 15
Source File: JvmTypesBuilder.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a public annotation 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 class.
 * @param initializer
 *            the initializer to apply on the created annotation. If <code>null</code>, the annotation won't be initialized.
 * 
 * @return a {@link JvmAnnotationType} representing a Java annotation of the given name, <code>null</code> 
 *            if sourceElement or name are <code>null</code>.
 */
/* @Nullable */ 
public JvmAnnotationType toAnnotationType(/* @Nullable */ EObject sourceElement, /* @Nullable */ String name, 
		/* @Nullable */ Procedure1<? super JvmAnnotationType> initializer) {
	if (sourceElement == null || name == null)
		return null;
	Pair<String, String> fullName = splitQualifiedName(name);
	JvmAnnotationType annotationType = typesFactory.createJvmAnnotationType();
	annotationType.setSimpleName(fullName.getSecond());
	annotationType.setAbstract(true);
	if (fullName.getFirst() != null)
		annotationType.setPackageName(fullName.getFirst());
	associate(sourceElement, annotationType);
	return initializeSafely(annotationType, initializer);
}
 
Example 16
Source File: AbstractParseTreeConstructor.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void assignNodesByMatching(Map<EObject, AbstractToken> eObject2Token, ICompositeNode rootNode,
		Map<ILeafNode, EObject> comments) throws IOException {
	NodeIterator contents = new NodeIterator(rootNode);
	while (contents.hasNext()) {
		INode containedNode = contents.next();
		AbstractRule rule = containedNode.getGrammarElement() instanceof AbstractRule ? (AbstractRule) containedNode
				.getGrammarElement() : null;
		if (hiddenTokenHelper.isWhitespace(rule))
			continue;
		else if (containedNode instanceof ILeafNode && hiddenTokenHelper.isComment(rule))
			assignComment((ILeafNode) containedNode, eObject2Token, comments);
		else if (tokenUtil.isToken(containedNode)) {
			Pair<List<ILeafNode>, List<ILeafNode>> leadingAndTrailingHiddenTokens = tokenUtil
					.getLeadingAndTrailingHiddenTokens(containedNode);
			for (ILeafNode leadingHiddenNode : leadingAndTrailingHiddenTokens.getFirst()) {
				if (tokenUtil.isCommentNode(leadingHiddenNode)) {
					assignComment(leadingHiddenNode, eObject2Token, comments);
				}
			}
			assignTokenByMatcher(containedNode, eObject2Token);
			for (ILeafNode trailingHiddenNode : leadingAndTrailingHiddenTokens.getSecond()) {
				if (tokenUtil.isCommentNode(trailingHiddenNode)) {
					assignComment(trailingHiddenNode, eObject2Token, comments);
				}
			}
			contents.prune();
			ICompositeNode parentNode = containedNode.getParent();
			while (parentNode != null && assignTokenDirect(parentNode, eObject2Token))
				parentNode = parentNode.getParent();
			if (containedNode.getOffset() > rootNode.getEndOffset()) {
				break;
			}
		}
	}
}
 
Example 17
Source File: XtendUIValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected String getExpectedPackageName(XtendFile xtendFile) {
	URI fileURI = xtendFile.eResource().getURI();
	for(Pair<IStorage, IProject> storage: storage2UriMapper.getStorages(fileURI)) {
		if(storage.getFirst() instanceof IFile) {
			IPath fileWorkspacePath = storage.getFirst().getFullPath();
			IJavaProject javaProject = JavaCore.create(storage.getSecond());
			if(javaProject != null && javaProject.exists() && javaProject.isOpen()) {
				try {
					for(IPackageFragmentRoot root: javaProject.getPackageFragmentRoots()) {
						if(!root.isArchive() && !root.isExternal()) {
							IResource resource = root.getResource();
							if(resource != null) {
								IPath sourceFolderPath = resource.getFullPath();
								if(sourceFolderPath.isPrefixOf(fileWorkspacePath)) {
									IPath claspathRelativePath = fileWorkspacePath.makeRelativeTo(sourceFolderPath);
									return claspathRelativePath.removeLastSegments(1).toString().replace("/", ".");
								}
							}
						}
					}
				} catch (JavaModelException e) {
					LOG.error("Error resolving expected path for XtendFile", e);
				}
			}
		}
	}
	return null;
}
 
Example 18
Source File: ExternalProjectProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
N4JSExternalProject getProject(SafeURI<?> projectLocation) {
	ensureInitialized();
	Pair<N4JSExternalProject, ProjectDescription> pair = mappings.completeCache.get(projectLocation);
	if (pair != null) {
		return pair.getFirst();
	}
	return null;
}
 
Example 19
Source File: CreateXtendTypeQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void addQuickfixes(Issue issue, IssueResolutionAcceptor issueResolutionAcceptor,
		IXtextDocument xtextDocument, XtextResource resource, 
		EObject referenceOwner, EReference unresolvedReference)
		throws Exception {
	String typeString = (issue.getData() != null && issue.getData().length > 0) 
			? issue.getData()[0] 
			: xtextDocument.get(issue.getOffset(), issue.getLength());
	Pair<String, String> packageAndType = typeNameGuesser.guessPackageAndTypeName(referenceOwner, typeString);
	String typeName = packageAndType.getSecond();
	if(isEmpty(typeName)) 
		return;
	String explicitPackage = packageAndType.getFirst();
	boolean isLocal = isEmpty(explicitPackage) || explicitPackage.equals(getPackage(resource));
	if(isLocal) 
		explicitPackage = "";
	if(isEmpty(packageAndType.getSecond()))
		return;
	if (unresolvedReference == XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR) {
		if(((XConstructorCall)referenceOwner).getConstructor().eIsProxy()) {
			if(isTypeMissing(referenceOwner, typeName, explicitPackage)) {
				newJavaClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
				newXtendClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
				if(isLocal)
					newLocalXtendClassQuickfix(typeName, resource, issue, issueResolutionAcceptor);
			}
		}
	} else if(unresolvedReference == XbasePackage.Literals.XTYPE_LITERAL__TYPE
			|| unresolvedReference == TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE) {
		EStructuralFeature eContainingFeature = referenceOwner.eContainingFeature();
		if(eContainingFeature == XtendPackage.Literals.XTEND_CLASS__EXTENDS) {
			newJavaClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newXtendClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			if(isLocal)
				newLocalXtendClassQuickfix(typeName, resource, issue, issueResolutionAcceptor);
		} else if(eContainingFeature == XtendPackage.Literals.XTEND_CLASS__IMPLEMENTS
				|| eContainingFeature == XtendPackage.Literals.XTEND_INTERFACE__EXTENDS) {
			newJavaInterfaceQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newXtendInterfaceQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			if(isLocal)
				newLocalXtendInterfaceQuickfix(typeName, resource, issue, issueResolutionAcceptor);
		} else {
			newJavaClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newJavaInterfaceQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newXtendClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newXtendInterfaceQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			if(isLocal) {
				newLocalXtendClassQuickfix(typeName, resource, issue, issueResolutionAcceptor);				
				newLocalXtendInterfaceQuickfix(typeName, resource, issue, issueResolutionAcceptor);
			}
		}
	} else if(unresolvedReference == XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE) {
		newJavaAnnotationQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
		newXtendAnnotationQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
		if(isLocal) 
			newLocalXtendAnnotationQuickfix(typeName, resource, issue, issueResolutionAcceptor);
	}
}
 
Example 20
Source File: NpmCLI.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Installs npm package with given name at the given path. Updates dependencies in the package.json of that
 * location. If there is no package.json at that location npm errors will be logged to the error log. In that case
 * npm/yarn usual still installs requested dependency (if possible).
 *
 * @param packageNamesAndVersions
 *            to be installed
 * @param installPath
 *            path where package is supposed to be installed
 */
private IStatus install(List<Pair<N4JSProjectName, String>> packageNamesAndVersions, File installPath) {
	List<String> packageNamesAndVersionsMerged = new ArrayList<>(packageNamesAndVersions.size());
	for (Pair<N4JSProjectName, String> pair : packageNamesAndVersions) {
		N4JSProjectName packageName = pair.getFirst();
		String packageVersion = pair.getSecond();

		// FIXME better error reporting (show all invalid names/versions, not just the first)
		if (invalidPackageName(packageName)) {
			return statusHelper.createError("Malformed npm package name: '" + packageName + "'.");
		}
		if (invalidPackageVersion(packageVersion)) {
			return statusHelper.createError("Malformed npm package version: '" + packageVersion + "'.");
		}

		String nameAndVersion = packageVersion.isEmpty() ? packageName.getRawName()
				: packageName.getRawName() + packageVersion;
		packageNamesAndVersionsMerged.add(nameAndVersion);
	}

	IStatus status = executor.execute(
			() -> commandFactory.createInstallPackageCommand(installPath, packageNamesAndVersionsMerged, true),
			"Error while installing npm package.");

	// TODO IDE-3136 / GH-1011 workaround for a problem in node related to URL/GitHub version requirements
	// In case of a dependency like "JSONSelect@dbo/JSONSelect" (wherein "dbo/JSONSelect" is a GitHub version
	// requirement), the first installation works fine, but subsequent installations of additional npm packages may
	// uninstall(!) the earlier package that used a URL/GitHub version requirement. This is supposed to be fixed
	// in npm version 5.7.1. As a work-around we run a plain "npm install" after every installation of new packages,
	// which should re-install the package with a URL/GitHub version requirement.
	boolean isNpmUsed = !isYarnUsed(installPath);
	if (isNpmUsed) {
		VersionNumber currNpmVersion = getNpmVersion();
		VersionNumber fixedNpmVersion = SemverUtils.createVersionNumber(5, 7, 1);
		if (currNpmVersion != null && SemverMatcher.compareLoose(currNpmVersion, fixedNpmVersion) < 0) {
			IStatus workaroundStatus = executor.execute(
					() -> commandFactory.createInstallPackageCommand(installPath, Collections.emptyList(), false),
					"Error while running \"npm install\" after installing npm packages.");
			MultiStatus combinedStatus = statusHelper
					.createMultiStatus("Installing npm packages with additional \"npm install\" afterwards.");
			combinedStatus.merge(status);
			combinedStatus.merge(workaroundStatus);
			status = combinedStatus;
		}
	}

	return status;
}