Java 类org.eclipse.xtext.util.Pair 实例源码

项目:n4js    文件:NfarStorageMapper.java   
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(URI uri) {
    if (uri.isArchive()) {
        URIBasedStorage storage = new URIBasedStorage(uri);
        String authority = uri.authority();
        URI archiveFileURI = URI.createURI(authority.substring(0, authority.length() - 1));
        Optional<? extends IN4JSEclipseProject> optionalProject = eclipseCore.findProject(archiveFileURI);
        if (optionalProject.isPresent()) {
            return Collections.singletonList(Tuples.<IStorage, IProject> create(storage, optionalProject.get()
                    .getProject()));
        } else {
            return Collections.singletonList(Tuples.create(storage, null));
        }
    } else {
        return Collections.emptyList();
    }
}
项目:n4js    文件:EclipseExternalLibraryWorkspace.java   
@Override
public URI getLocation(URI projectURI, ProjectReference reference,
        N4JSSourceContainerType expectedN4JSSourceContainerType) {

    ensureInitialized();
    if (PROJECT.equals(expectedN4JSSourceContainerType)) {

        final String name = reference.getProject().getProjectId();
        final ExternalProject project = getProjectMapping().get(name);

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

        final File referencedProject = new File(project.getLocationURI());
        final URI referencedLocation = URI.createFileURI(referencedProject.getAbsolutePath());
        final Pair<ExternalProject, ProjectDescription> pair = get(referencedLocation);
        if (null != pair) {
            return referencedLocation;
        }

    }

    return null;
}
项目:n4js    文件:EclipseExternalLibraryWorkspace.java   
@Override
public Iterable<IProject> getProjects(java.net.URI rootLocation) {
    ensureInitialized();
    final File rootFolder = new File(rootLocation);

    final Map<String, IProject> projectsMapping = newTreeMap();
    final URI rootUri = URI.createFileURI(rootFolder.getAbsolutePath());

    for (Entry<URI, Optional<Pair<ExternalProject, ProjectDescription>>> entry : projectCache.asMap().entrySet()) {
        final URI projectLocation = entry.getKey();
        if (rootUri.equals(projectLocation.trimSegments(1))) {
            final Pair<ExternalProject, ProjectDescription> pair = entry.getValue().orNull();
            if (null != pair && null != pair.getFirst()) {
                final ExternalProject project = pair.getFirst();
                projectsMapping.put(project.getName(), project);
            }
        }
    }

    return unmodifiableCollection(projectsMapping.values());
}
项目:n4js    文件:EclipseExternalLibraryWorkspace.java   
@Override
public Iterable<ProjectDescription> getProjectsDescriptions(java.net.URI rootLocation) {
    ensureInitialized();
    final File rootFolder = new File(rootLocation);

    final Set<ProjectDescription> projectsMapping = newHashSet();
    final URI rootUri = URI.createFileURI(rootFolder.getAbsolutePath());

    for (Entry<URI, Optional<Pair<ExternalProject, ProjectDescription>>> entry : projectCache.asMap().entrySet()) {
        final URI projectLocation = entry.getKey();
        if (rootUri.equals(projectLocation.trimSegments(1))) {
            final Pair<ExternalProject, ProjectDescription> pair = entry.getValue().orNull();
            if (null != pair && null != pair.getFirst()) {
                final ProjectDescription description = pair.getSecond();
                if (description != null) {
                    projectsMapping.add(description);
                }
            }
        }
    }

    return unmodifiableCollection(projectsMapping);
}
项目:n4js    文件:BuildInstruction.java   
private boolean shouldGenerate(Resource resource, IProject aProject) {
    try {
        Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(resource.getURI());
        for (Pair<IStorage, IProject> pair : storages) {
            if (pair.getFirst() instanceof IFile && pair.getSecond().equals(aProject)) {
                IFile file = (IFile) pair.getFirst();
                int findMaxProblemSeverity = file.findMaxProblemSeverity(null, true, IResource.DEPTH_INFINITE);
                // If the generator itself placed an error marker on the resource, we have to ignore that error.
                // Easiest way here is to remove that error marker-type and look for other severe errors once more:
                if (findMaxProblemSeverity == IMarker.SEVERITY_ERROR) {
                    // clean
                    GeneratorMarkerSupport generatorMarkerSupport = injector
                            .getInstance(GeneratorMarkerSupport.class);
                    generatorMarkerSupport.deleteMarker(resource);
                    // and recompute:
                    findMaxProblemSeverity = file.findMaxProblemSeverity(null, true, IResource.DEPTH_INFINITE);
                }
                // the final decision to build:
                return findMaxProblemSeverity != IMarker.SEVERITY_ERROR;
            }
        }
        return false;
    } catch (CoreException exc) {
        throw new WrappedException(exc);
    }
}
项目:n4js    文件:NpmManager.java   
private Collection<File> adaptNPMPackages(final IProgressMonitor monitor, final MultiStatus status,
        final Collection<String> addedDependencies) {

    logger.logInfo(LINE_SINGLE);
    logger.logInfo("Adapting npm package structure to N4JS project structure... [step 3 of 4]");
    monitor.setTaskName("Adapting npm package structure to N4JS project structure... [step 3 of 4]");
    final Pair<IStatus, Collection<File>> result = npmPackageToProjectAdapter.adaptPackages(addedDependencies);
    final IStatus adaptionStatus = result.getFirst();

    // log possible errors, but proceed with the process
    // assume that at least some packages were installed correctly and can be adapted
    if (!adaptionStatus.isOK()) {
        logger.logError(adaptionStatus);
        status.merge(adaptionStatus);
    }

    final Collection<File> adaptedPackages = result.getSecond();
    logger.logInfo("Packages structures has been adapted to N4JS project structure.");
    monitor.worked(2);

    logger.logInfo(LINE_SINGLE);
    return adaptedPackages;
}
项目:n4js    文件:ExternalProjectCacheLoader.java   
@Override
public Optional<Pair<ExternalProject, ProjectDescription>> load(final URI rootLocation) throws Exception {

    if (null != rootLocation && rootLocation.isFile()) {
        final File projectRoot = new File(rootLocation.toFileString());
        if (projectRoot.exists() && projectRoot.isDirectory()) {
            final URI manifestLocation = rootLocation.appendSegment(IN4JSProject.N4MF_MANIFEST);
            final ProjectDescription projectDescription = packageManager.loadManifest(manifestLocation);
            if (null != projectDescription) {
                final ExternalProject project = new ExternalProject(projectRoot, NATURE_ID, BUILDER_ID);
                return Optional.of(Tuples.create(project, projectDescription));
            }
        }
    }

    return Optional.absent();
}
项目:Saturn    文件:KronusFormatter.java   
protected void formatBrackets(final FormattingConfig c, final String left, final String right) {
  List<Pair<Keyword, Keyword>> _findKeywordPairs = this._kronusGrammarAccess.findKeywordPairs(left, right);
  for (final Pair<Keyword, Keyword> pair : _findKeywordPairs) {
    {
      FormattingConfig.NoSpaceLocator _setNoSpace = c.setNoSpace();
      Keyword _first = pair.getFirst();
      _setNoSpace.before(_first);
      FormattingConfig.NoSpaceLocator _setNoSpace_1 = c.setNoSpace();
      Keyword _first_1 = pair.getFirst();
      _setNoSpace_1.after(_first_1);
      FormattingConfig.NoSpaceLocator _setNoSpace_2 = c.setNoSpace();
      Keyword _second = pair.getSecond();
      _setNoSpace_2.before(_second);
    }
  }
}
项目:OCCI-Studio    文件:OCCIFormatter.java   
@Override
protected void configureFormatting(FormattingConfig c) {
    org.eclipse.cmf.occi.core.xtext.services.OCCIGrammarAccess f = (org.eclipse.cmf.occi.core.xtext.services.OCCIGrammarAccess) getGrammarAccess();
    for(Pair<Keyword, Keyword> pair: f.findKeywordPairs("{", "}")) {
        c.setIndentation(pair.getFirst(), pair.getSecond());
        c.setLinewrap(1).after(pair.getFirst());
        c.setLinewrap(1).before(pair.getSecond());
        c.setLinewrap(1).after(pair.getSecond());
    }
    for(Keyword comma: f.findKeywords(",")) {
        c.setNoLinewrap().before(comma);
        c.setNoSpace().before(comma);
        c.setLinewrap().after(comma);
    }
    c.setLinewrap(0, 1, 2).before(f.getSL_COMMENTRule());
    c.setLinewrap(0, 1, 2).before(f.getML_COMMENTRule());
    c.setLinewrap(0, 1, 1).after(f.getML_COMMENTRule());
}
项目:xtext-extras    文件:SerializerTester.java   
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;
}
项目:xtext-extras    文件:RawTypeReferenceComputer.java   
@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;
}
项目:dsl-devkit    文件:ValidMarkerUpdateJob.java   
/**
 * 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;
}
项目:xtext-extras    文件:RawTypeReferenceComputer.java   
@Override
public JvmTypeReference doVisitParameterizedTypeReference(JvmParameterizedTypeReference reference, Pair<Resource, Set<JvmType>> context) {
    JvmType type = reference.getType();
    if (type != null && !type.eIsProxy()) {
        if (type instanceof JvmTypeParameterDeclarator) {
            if (!((JvmTypeParameterDeclarator) type).getTypeParameters().isEmpty()) {
                JvmParameterizedTypeReference result = factory.createJvmParameterizedTypeReference();
                result.setType(type);
                return result;
            }
        } else if (type instanceof JvmTypeParameter) {
            Set<JvmType> recursionGuard = context.getSecond();
            if (recursionGuard.add(type)) {
                return getRawTypeFromConstraints(((JvmTypeParameter) type).getConstraints(), context);
            } else {
                return createObjectReference(context.getFirst());
            }
        }
    }
    return reference;
}
项目:dsl-devkit    文件:AcfContentAssistProcessorTestBuilder.java   
/**
 * 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();
  }
}
项目:xtext-core    文件:AbstractTraceRegion.java   
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;
}
项目:dsl-devkit    文件:AcfContentAssistProcessorTestBuilder.java   
/**
 * {@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();
}
项目:xtext-core    文件:AssignmentQuantityAllocator.java   
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);
}
项目:xtext-core    文件:ConcreteSyntaxValidator.java   
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;
}
项目:xtext-core    文件:IReferableElementsUnloader.java   
@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());
    }
}
项目:xtext-core    文件:HiddenAndTokenNodeIterator.java   
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();
}
项目:dsl-devkit    文件:AbstractUtilTest.java   
/**
 * 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);
}
项目:xtext-core    文件:AbstractElementFinder.java   
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;
}
项目:xtext-core    文件:BacktrackingSemanticSequencer.java   
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;
}
项目:dsl-devkit    文件:RuntimeProjectUtil.java   
/**
 * 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;
  }
}
项目:xtext-core    文件:FormattingConfigBasedStream.java   
/**
 * @param endIndex
 *            the index of the last entry to flush, exclusive.
 */
protected void flush(ITokenStream intoStream, int endIndex) throws IOException {
    for (int i = 0; i < endIndex; i++) {
        LineEntry e = this.entries.get(i);
        Pair<AbstractRule, String> spaces = getSpaces(e, i == 0);
        //              if (i == 0 && startWithNL && !e.isBreakable())
        //                  throw new IllegalStateException("break for non-breakable item");
        //              else if (i != 0 && e.isBreak())
        //                  throw new IllegalStateException("break within line");
        //              if (i == 0 && startWithNL && spaces.getSecond().indexOf('\n') < 0)
        //                  throw new IllegalStateException("missing newline before " + e.value);
        // System.out.println("Spaces: '" + sp + "' before '" + e.val
        // + "'");
        if (spaces != null)
            intoStream.writeHidden(spaces.getFirst(), spaces.getSecond());
        if (e.isHidden)
            intoStream.writeHidden(e.grammarElement, e.value);
        else
            intoStream.writeSemantic(e.grammarElement, e.value);
    }
}
项目:xtext-core    文件:SerializerTestHelper.java   
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;
}
项目:xtext-core    文件:NfaToProduction.java   
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;
}
项目:xtext-core    文件:StringProduction.java   
protected void parseCardinality(Stack<Pair<Token, String>> tokens, ProdElement ele) {
    if (!tokens.isEmpty())
        switch (tokens.peek().getFirst()) {
            case QM:
                tokens.pop();
                ele.optional = true;
                break;
            case STAR:
                tokens.pop();
                ele.optional = true;
                ele.many = true;
                break;
            case PLUS:
                tokens.pop();
                ele.many = true;
                break;
            default:
        }
}
项目:xtext-core    文件:StringProduction.java   
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());
    }
}
项目:dsl-devkit    文件:AbstractLabelingTest.java   
/**
 * 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
}
项目:xtext-core    文件:ChangeSerializer.java   
@Override
public void applyModifications(IAcceptor<IEmfResourceChange> changeAcceptor) {
    monitor.setTaskName("Preparing Text Changes...");
    Set<Resource> resources = Sets.newLinkedHashSet();
    for (Pair<Notifier, IModification<? extends Notifier>> p : modifications) {
        Notifier context = p.getFirst();
        if (context instanceof EObject)
            resources.add(((EObject) context).eResource());
        else if (context instanceof Resource)
            resources.add((Resource) context);
        else if (context instanceof ResourceSet) {
            throw new IllegalStateException("Not supported");
        }
    }
    for (Resource res : resources) {
        // TODO: use the exact context
        beginRecordChanges(res);
    }
    checkCanceled();
    for (Pair<Notifier, IModification<? extends Notifier>> entry : modifications) {
        apply(entry.getFirst(), entry.getSecond());
    }
    checkCanceled();
    endRecordChanges(changeAcceptor);
}
项目:dsl-devkit    文件:CheckMarkerUpdateJob.java   
/**
 * Gets an {@link IFile} from the {@link IStorage2UriMapper} corresponding to given {@link URI}. If none
 * could be found, <code>null</code> is returned.
 * 
 * @param storage2UriMapper
 *          the storage to URI mapper
 * @param fileUri
 *          the URI
 * @return the file from the storage to URI mapper or <code>null</code> if no match found
 */
private IFile getFileFromStorageMapper(final IStorage2UriMapper storage2UriMapper, final URI fileUri) {
  if (storage2UriMapper == null) {
    return null; // Should not occur
  }

  for (Pair<IStorage, IProject> storage : storage2UriMapper.getStorages(fileUri)) {
    if (storage.getFirst() instanceof IFile) {
      return (IFile) storage.getFirst();
    }
  }
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug(MessageFormat.format("Could not find storage for URI {0}", fileUri.toString())); //$NON-NLS-1$
  }
  return null;
}
项目:n4js    文件:N4JSExternalLibraryStorage2UriMapperContribution.java   
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(final URI uri) {
    final IN4JSEclipseProject project = eclipseCore.findProject(uri).orNull();
    if (null != project && project.exists()) {
        final IProject resourceProject = project.getProject();
        return singleton(Tuples.create(new URIBasedStorage(uri), resourceProject));
    }
    return emptyList();
}
项目:n4js    文件:EclipseExternalLibraryWorkspace.java   
private Pair<ExternalProject, ProjectDescription> get(URI location) {
    try {
        return projectCache.get(location).orNull();
    } catch (ExecutionException e) {
        final String message = "Error while getting external project with description for location: " + location;
        LOGGER.error(message, e);
        return null;
    }

}
项目:n4js    文件:ContainerTypesHelper.java   
private TMemberEntry getOrCreateEntry(TMember member) {
    Pair<String, Boolean> p = Tuples.pair(member.getName(), member.isStatic());
    TMemberEntry entry = memberEntries.get(p);
    if (entry == null) {
        entry = new TMemberEntry(member.getName(), member.isStatic());
        memberEntries.put(p, entry);
    }
    return entry;
}
项目:n4js    文件:NpmManager.java   
private Pair<Collection<String>, Iterable<java.net.URI>> getChangedDependencies(final IProgressMonitor monitor,
        Set<String> oldNPMs) {

    logger.logInfo(LINE_SINGLE);
    logger.logInfo("Calculating dependency changes... [step 2 of 4]");
    monitor.setTaskName("Calculating dependency changes... [step 2 of 4]");

    externalLibraryWorkspace.updateState();
    URI targetPlatformNodeModulesLocation = locationProvider.getTargetPlatformNodeModulesLocation();

    Map<String, String> afterDependencies = locationProvider.getTargetPlatformContent().dependencies;
    if (null == afterDependencies) {
        afterDependencies = newHashMap();
    }
    final Set<String> newDependencies = new HashSet<>(afterDependencies.keySet());

    Set<String> newNpmProjectNames = new HashSet<>();
    Iterable<IProject> newNPMs = externalLibraryWorkspace.getProjects(targetPlatformNodeModulesLocation);
    for (IProject newNPM : newNPMs) {
        newNpmProjectNames.add(newNPM.getName());
    }

    Set<String> overwrittenShippedLibNames = getOverwrittenShippedLibs(newNpmProjectNames);
    newDependencies.addAll(overwrittenShippedLibNames);

    final Collection<String> addedDependencies = difference(newDependencies, oldNPMs);
    final Collection<String> deletedDependencies = difference(oldNPMs, newDependencies);
    final File nodeModulesFolder = new File(targetPlatformNodeModulesLocation);
    final Iterable<java.net.URI> toBeDeleted = from(deletedDependencies)
            .transform(name -> new File(nodeModulesFolder, name).toURI());
    monitor.worked(1);
    logger.logInfo("Dependency changes have been successfully calculated.");

    Pair<Collection<String>, Iterable<java.net.URI>> changedDeps = Tuples.pair(addedDependencies, toBeDeleted);

    return changedDeps;
}
项目:n4js    文件:BuiltinSchemeUriMapperContribution.java   
@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();
}
项目:xtext-extras    文件:OnTheFlyJavaCompiler.java   
protected Pair<String, String> createFullCode(String statementCode,
        Type returnType, Pair<Type, String>... params) {
    String className = "_$GeneratedClass";
    StringBuilder sb = new StringBuilder("public class ").append(className)
            .append(" implements ")
            .append("org.eclipse.xtext.xbase.lib.Functions.Function")
            .append(params.length).append("<");
    for (Pair<Type, String> type : params) {
        sb.append(toString(type.getFirst())).append(",");
    }
    sb.append(toString(returnType));
    sb.append("> {\n");
    sb.append("public ").append(toString(returnType));
    sb.append(" apply(");

    for (int i = 0; i < params.length; i++) {
        Pair<Type, String> pair = params[i];
        sb.append(toString(pair.getFirst())).append(" ")
                .append(pair.getSecond());
        if (i + 1 < params.length)
            sb.append(",");
    }
    sb.append(") {\n");
    sb.append(statementCode);
    sb.append("\n}}");
    return Tuples.pair(className, sb.toString());
}
项目:xtext-extras    文件:XbaseSeverityConverter.java   
/**
 * Returns decoded delegation key or <code>null</code> if encodedValue can not be parsed.
 * @return {@link Pair} where getFirst() is delegationKey and getSecond() is the defaultSeverity.
 * @see XbaseSeverityConverter#encodeDefaultSeverity(String, String)
 */
public static Pair<String, String> decodeDelegationKey(String encodedValue) {
    List<String> split = Strings.split(encodedValue, DEFAULT_SEVERITY_SEPARATOR);
    if (split.size() == 2) {
        return Tuples.create(split.get(0), split.get(1));
    } else if (split.size() == 1) {
        return Tuples.create(split.get(0), SeverityConverter.SEVERITY_WARNING);
    } else {
        return null;
    }
}
项目:xtext-extras    文件:JvmTypesBuilder.java   
/**
 * 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);
}