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

项目: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    文件: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();
}
项目:xtext-extras    文件:EcoreQualifiedNameProvider.java   
@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);
        }

    });
}
项目: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-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;
}
项目: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    文件:DefaultDeclarativeQualifiedNameProvider.java   
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
    return cache.get(Tuples.pair(obj, "fqn"), obj.eResource(), new Provider<QualifiedName>(){

        @Override
        public QualifiedName get() {
            EObject temp = obj;
            QualifiedName qualifiedNameFromDispatcher = qualifiedName.invoke(temp);
            if (qualifiedNameFromDispatcher!=null)
                return qualifiedNameFromDispatcher;
            String name = getResolver().apply(temp);
            if (Strings.isEmpty(name))
                return null;
            QualifiedName qualifiedNameFromConverter = converter.toQualifiedName(name);
            while (temp.eContainer() != null) {
                temp = temp.eContainer();
                QualifiedName parentsQualifiedName = getFullyQualifiedName(temp);
                if (parentsQualifiedName != null)
                    return parentsQualifiedName.append(qualifiedNameFromConverter);
            }
            return qualifiedNameFromConverter;
        }
    });
}
项目: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    文件:SemanticNodeIterator.java   
protected Triple<INode, AbstractElement, EObject> findNext(INode node, boolean prune) {
    INode current = next(node, prune);
    while (current != null) {
        if (current instanceof ILeafNode && ((ILeafNode) current).isHidden()) {
            current = next(current, true);
            continue;
        }
        EObject ge = current.getGrammarElement();
        if (ge instanceof AbstractElement && isEObjectNode(current))
            return Tuples.create(current, (AbstractElement) ge, getEObjectNodeEObject(current));
        else if (GrammarUtil.isAssigned(ge) && !GrammarUtil.isEObjectRuleCall(ge)) {
            if (ge instanceof CrossReference)
                return Tuples.create(current, ((CrossReference) ge).getTerminal(), null);
            else
                return Tuples.create(current, (AbstractElement) ge, null);
        } else
            current = next(current, false);
    }
    return null;
}
项目: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;
}
项目:xtext-core    文件:FormattableDocument.java   
@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);
    }
}
项目: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    文件:EcoreQualifiedNameProvider.java   
@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);
        }

    });
}
项目: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;
}
项目:dsl-devkit    文件:AbstractTypeProvider.java   
/**
 * Gets the containing info for an expression.
 * <p>
 * The containing info for an expression consists of
 * <ul>
 * <li>the EObject that contains the expression,
 * <li>the containment EReference of that containing EObject
 * <li>if the multiplicity is > 1, the index of the expression in the containing EReference; else -1
 * </ul>
 *
 * @param expression
 *          the expression to get the containing info for
 * @return the containing info for {@code expression}
 */
protected Triple<EObject, EReference, Integer> getContainingInfo(final IExpression expression) {
  if (expression == null) {
    return null;
  }
  if (expression.eIsProxy()) {
    return null;
  }
  EReference containmentReference = expression.eContainmentFeature();
  if (containmentReference == null) {
    return null;
  }
  EObject container = expression.eContainer();
  int index = (containmentReference.isMany()) ? ((List<?>) container.eGet(containmentReference)).indexOf(expression) : -1;
  return Tuples.create(container, containmentReference, index);
}
项目:dsl-devkit    文件:ParallelResourceLoader.java   
/**
 * 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);

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

  currentlyProcessedUris.remove(uri);
  publishLoadResult(Tuples.create(uri, resource, exception));
}
项目: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);
}
项目: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();
  }
}
项目:bts    文件:AstSelectionProvider.java   
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;
}
项目:bts    文件:DirtyStateEditorSupport.java   
protected Pair<IResourceDescription.Event, Integer> mergePendingDeltas() {
    Map<URI, IResourceDescription.Delta> uriToDelta = Maps.newLinkedHashMap();
    Iterator<IResourceDescription.Delta> iter = pendingChanges.iterator();
    int size = 0;
    while(iter.hasNext()) {
        IResourceDescription.Delta delta = iter.next();
        URI uri = delta.getUri();
        IResourceDescription.Delta prev = uriToDelta.get(uri);
        if (prev == null) {
            uriToDelta.put(uri, delta);
        } else if (prev.getOld() != delta.getNew()){
            uriToDelta.put(uri, createDelta(delta, prev));
        } else {
            uriToDelta.remove(uri);
        }
        size++;
    }
    IResourceDescription.Event event = new ResourceDescriptionChangeEvent(uriToDelta.values(), dirtyStateManager);
    return Tuples.create(event, size);
}
项目: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    文件:N4JSBuilderPreferencePage.java   
/**
 * Initializes default compiler configuration.
 */
@Inject
public N4JSBuilderPreferencePage(ICompositeGenerator compositeGenerator) {
    super(new ArrayList<Triple<String, String, CompilerDescriptor>>());
    for (CompilerDescriptor compilerDescriptor : compositeGenerator.getCompilerDescriptors()) {
        this.components.add(Tuples.create(compilerDescriptor.getIdentifier(), compilerDescriptor.getName(),
                compilerDescriptor));
    }
}
项目: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    文件:OnTheFlyJavaCompiler.java   
@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"));
}
项目: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   
protected Pair<String, String> splitQualifiedName(String name) {
    String simpleName = name;
    String packageName = null;
    final int dotIdx = name.lastIndexOf('.');
    if (dotIdx != -1) {
        simpleName = name.substring(dotIdx + 1);
        packageName = name.substring(0, dotIdx);
    }
    Pair<String,String> fullName = Tuples.create(packageName, simpleName);
    return fullName;
}
项目:xtext-extras    文件:XbaseImportedNamespaceScopeProvider.java   
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);
        }
    });
}
项目:xtext-extras    文件:XImportSectionNamespaceScopeProvider.java   
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);
        }
    });
}
项目:xtext-extras    文件:XbaseCompiler.java   
protected void appendCatchAndFinally(XTryCatchFinallyExpression expr, ITreeAppendable b, boolean isReferenced) {
    final EList<XCatchClause> catchClauses = expr.getCatchClauses();
    if (!catchClauses.isEmpty()) {
        String variable = b.declareSyntheticVariable(Tuples.pair(expr, "_catchedThrowable"), "_t");
        b.append(" catch (final Throwable ").append(variable).append(") ");
        b.append("{").increaseIndentation();
        b.newLine();
        Iterator<XCatchClause> iterator = catchClauses.iterator();
        while (iterator.hasNext()) {
            XCatchClause catchClause = iterator.next();
            ITreeAppendable catchClauseAppendable = b.trace(catchClause);
            appendCatchClause(catchClause, isReferenced, variable, catchClauseAppendable);
            if (iterator.hasNext()) {
                b.append(" else ");
            }
        }
        b.append(" else {");
        b.increaseIndentation();
        final JvmType sneakyThrowType = findKnownTopLevelType(Exceptions.class, expr);
        if (sneakyThrowType == null) {
            b.append("COMPILE ERROR : '"+Exceptions.class.getCanonicalName()+"' could not be found on the classpath!");
        } else {
            b.newLine().append("throw ");
            b.append(sneakyThrowType);
            b.append(".sneakyThrow(");
            b.append(variable);
            b.append(");");
        }
        closeBlock(b);
        closeBlock(b);
    }
    final XExpression finallyExp = expr.getFinallyExpression();
    if (finallyExp != null) {
        b.append(" finally {").increaseIndentation();
        internalToJavaStatement(finallyExp, b, false);
        b.decreaseIndentation().newLine().append("}");
    }
}
项目:xtext-extras    文件:JvmDeclaredTypeSignatureHashProvider.java   
public String getHash(final JvmDeclaredType type) {
    if(type.eResource() instanceof TypeResource) {
        IMirror mirror = ((TypeResource)type.eResource()).getMirror();
        if(mirror instanceof IMirrorExtension && ((IMirrorExtension) mirror).isSealed())
            return type.getIdentifier();
    }
    return cache.get(Tuples.create(HASH_CACHE_KEY, type), type.eResource(), new Provider<String>() {
        @Override
        public String get() {
            return signatureBuilderProvider.get().appendSignature(type).hash();
        }
    });
}
项目:xtext-extras    文件:TestErrorAcceptor.java   
@Override
public void acceptError(TransformationErrorCode errorCode, String message, EObject element) {
    Triple<TransformationErrorCode, String, EObject> create = Tuples.create(errorCode, message, element);
    //      System.out.println((write ? "Write>" : "Read>") + " errorCode: " + (errorCode != null ? errorCode : "")
    //              + ", message: " + (message != null ? message : "") + ", element: " + (element != null ? element : ""));
    if (write) {
        flugschreiber.push(create);
    } else {
        Triple<TransformationErrorCode, String, EObject> pop = flugschreiber.removeLast();
        assertNotNull("Queue is empty", pop);
        boolean equals = compareTriple(pop, create);
        assertTrue("Verified", equals);
    }
}
项目:xtext-core    文件:ConcreteSyntaxConstraintProvider.java   
protected Pair<Set<EClass>, Set<EClass>> getAllSemanticTypesPairs(Set<ISyntaxConstraint> exclude) {
    Set<EClass> mandatory = Sets.newHashSet();
    Set<EClass> optional = Sets.newHashSet();
    boolean allChildrenContributeMandatoryType = !getContents().isEmpty();
    for (ISyntaxConstraint sc : getContents())
        if (exclude == null || !exclude.contains(sc)) {
            Pair<Set<EClass>, Set<EClass>> t = ((SyntaxConstraintNode) sc).getAllSemanticTypesPairs(exclude);
            if (sc.isOptional()) {
                optional.addAll(t.getFirst());
                optional.addAll(t.getSecond());
                allChildrenContributeMandatoryType = false;
            } else {
                mandatory.addAll(t.getFirst());
                optional.addAll(t.getSecond());
                if (t.getFirst().isEmpty())
                    allChildrenContributeMandatoryType = false;
            }
        }
    if ((isRoot() && isOptional())
            || (type == ConstraintType.ALTERNATIVE && !allChildrenContributeMandatoryType)) {
        optional.addAll(mandatory);
        mandatory.clear();
    }
    if (semanticType != null) {
        if (mandatory.isEmpty()
                && (optional.isEmpty() || (optional.size() == 1 && optional.contains(semanticType))))
            mandatory.add(semanticType);
        else
            optional.add(semanticType);
    }
    if (exclude == null && !isRoot() && mandatory.isEmpty() && optional.isEmpty())
        optional.addAll(((SyntaxConstraintNode) getContainer()).getSemanticTypeByParent(Sets
                .<ISyntaxConstraint> newHashSet(this)));
    return Tuples.create(mandatory, optional);
}
项目:xtext-core    文件:ValidEntryRuleInspector.java   
@Override
public Pair<Boolean, Boolean> caseCompoundElement(CompoundElement object) {
    boolean valid = true;
    boolean instantiated = false;
    for(AbstractElement element: object.getElements()) {
        Pair<Boolean, Boolean> elementResult = doSwitch(element);
        instantiated |= elementResult.getSecond().booleanValue();
        if (!instantiated)
            valid &= elementResult.getFirst().booleanValue();
    }
    valid |= instantiated;
    instantiated &= !(GrammarUtil.isOptionalCardinality(object));
    return Tuples.create(valid, instantiated);
}
项目:xtext-core    文件:ValidEntryRuleInspector.java   
@Override
public Pair<Boolean, Boolean> caseAlternatives(Alternatives object) {
    boolean valid = true;
    boolean instantiated = !GrammarUtil.isOptionalCardinality(object);
    for(AbstractElement element: object.getElements()) {
        Pair<Boolean, Boolean> elementResult = doSwitch(element);
        valid &= elementResult.getFirst().booleanValue();
        instantiated &= elementResult.getSecond().booleanValue();
    }
    return Tuples.create(valid, instantiated);
}
项目:xtext-core    文件:ListBasedDiagnosticConsumer.java   
public void consume(Diagnostic diagnostic) {
    final Pair<Integer, Integer> newRange = Tuples.create(diagnostic.getOffset(), diagnostic.getLength());
    if (coveredNodes.add(newRange)) {
        boolean changed = this.diagnostics.add(diagnostic);
        diagnosticsConsumed |= changed;
    }
}
项目:xtext-core    文件:TreeConstructionReportImpl.java   
protected void addDeadEnd(int depth, AbstractToken deadend) {
    if (deadends.size() >= THRESHOLD && depth < deadends.first().getFirst())
        return;
    if (deadends.size() >= THRESHOLD)
        deadends.remove(deadends.first());
    deadends.add(Tuples.pair(depth, deadend));
}