Example usage for com.google.common.collect RangeSet add

List of usage examples for com.google.common.collect RangeSet add

Introduction

In this page you can find the example usage for com.google.common.collect RangeSet add.

Prototype

void add(Range<C> range);

Source Link

Document

Adds the specified range to this RangeSet (optional operation).

Usage

From source file:eu.trentorise.opendata.semtext.SemText.java

/**
 * Returns a copy of the this SemText without terms intersecting provided
 * ranges.//ww  w. j a  va2s  .co m
 *
 */
// note: Current version is inefficient, tried RangeMap.remove, but it only removes matching subsegments! 
public SemText deleteTerms(Iterable<Range<Integer>> deletionRanges) {
    checkNotNull(deletionRanges);

    ImmutableList.Builder<Sentence> sentencesB = ImmutableList.builder();

    RangeSet<Integer> rangeSet = TreeRangeSet.create();

    for (Range r : deletionRanges) {
        rangeSet.add(r);
    }

    for (Sentence sentence : sentences) {
        ImmutableList.Builder<Term> termsB = ImmutableList.builder();
        for (Term term : sentence.getTerms()) {
            RangeSet<Integer> intersection = rangeSet.subRangeSet(SemTexts.spanToRange(term));
            if (intersection.isEmpty()) {
                termsB.add(term);
            }

        }
        sentencesB.add(sentence.withTerms(termsB.build()));
    }

    return this.withSentences(sentencesB.build());
}

From source file:org.rf.ide.core.testdata.model.table.keywords.names.EmbeddedKeywordNamesSupport.java

@VisibleForTesting
static RangeSet<Integer> findEmbeddedArgumentsRanges(final String definitionName) {
    final RangeSet<Integer> varRanges = TreeRangeSet.create();

    if (definitionName.isEmpty()) {
        return varRanges;
    }//from   ww  w.j  a va 2  s .c om
    int varStart = -1;
    int currentIndex = 0;
    int currentState = 0;

    while (currentIndex < definitionName.length()) {
        final char character = definitionName.charAt(currentIndex);

        if (currentState == KeywordDfaState.START_STATE) {
            currentState = character == '$' ? KeywordDfaState.VAR_DOLLAR_DETECTED : KeywordDfaState.START_STATE;

        } else if (currentState == KeywordDfaState.VAR_DOLLAR_DETECTED) {
            currentState = character == '{' ? KeywordDfaState.VAR_START_DETECTED : KeywordDfaState.START_STATE;

        } else if (currentState == KeywordDfaState.VAR_START_DETECTED) {
            varStart = currentIndex - 2;
            if (character == '}') {
                currentState = KeywordDfaState.START_STATE;
            } else if (character == '\\') {
                currentState = KeywordDfaState.IN_VAR_ESCAPING;
            } else {
                currentState = KeywordDfaState.IN_VAR_NO_ESCAPE_CURRENTLY;
            }

        } else if (currentState == KeywordDfaState.IN_VAR_ESCAPING) {
            currentState = KeywordDfaState.IN_VAR_NO_ESCAPE_CURRENTLY;

        } else if (currentState == KeywordDfaState.IN_VAR_NO_ESCAPE_CURRENTLY) {
            if (character == '}') {
                varRanges.add(Range.closed(varStart, currentIndex));
                currentState = KeywordDfaState.START_STATE;
            } else if (character == '\\') {
                currentState = KeywordDfaState.IN_VAR_ESCAPING;
            } else {
                currentState = KeywordDfaState.IN_VAR_NO_ESCAPE_CURRENTLY;
            }

        } else {
            throw new IllegalStateException("Unrecognized state");
        }
        currentIndex++;
    }
    return varRanges;
}

From source file:com.google.errorprone.bugpatterns.javadoc.UnescapedEntity.java

private RangeSet<Integer> fixGenerics(RangeSet<Integer> generics, RangeSet<Integer> preTags,
        RangeSet<Integer> dontEmitCodeFix, VisitorState state) {
    RangeSet<Integer> emittedFixes = TreeRangeSet.create();
    for (Range<Integer> range : generics.asRanges()) {
        if (emittedFixes.intersects(range) || dontEmitCodeFix.intersects(range)) {
            continue;
        }/*from  w  ww  .  ja v a  2s  .co m*/
        Range<Integer> regionToWrap = preTags.rangeContaining(range.lowerEndpoint());
        if (regionToWrap == null) {
            regionToWrap = range;
        }
        emittedFixes.add(regionToWrap);
        state.reportMatch(
                buildDescription(getDiagnosticPosition(range.lowerEndpoint(), state.getPath().getLeaf()))
                        .setMessage(
                                "This looks like a type with type parameters. The < and > characters here will "
                                        + "be interpreted as HTML, which can be avoided by wrapping it in a "
                                        + "{@code } tag.")
                        .addFix(wrapInCodeTag(regionToWrap)).build());
    }
    return emittedFixes;
}

From source file:com.google.testing.pogen.parser.template.soy.SoyParser.java

@Override
protected RangeSet<Integer> parseRepeatedPart(String template) throws TemplateParseException {
    // TODO(kazuu): We parse CALL_PATTERNs only in 1 file. We can't detect
    // repeated pattern for calling other template.

    // Get a set of merged ranges which locates the inner parts of
    // for/foreach
    RangeSet<Integer> forRanges = parseForTags(template);

    Map<String, Range<Integer>> templateRanges = parseTemplateTags(template);
    List<StringWithIndex> calls = getMatchedStringAndIndexes(template, CALL_PATTERN, 1);

    boolean added;
    do {/*www. j  a  v a  2  s. co m*/
        added = false;
        for (int i = calls.size() - 1; i >= 0; i--) {
            StringWithIndex nameAndIndex = calls.get(i);
            if (forRanges.contains(nameAndIndex.getIndex())) {
                // If a template definition is called from another repeated part, it's
                // treated as repeated part
                forRanges.add(templateRanges.get(nameAndIndex.getString()));
                calls.remove(i);
                added = true;
            }
        }
    } while (added);
    return forRanges;
}

From source file:org.apache.druid.query.filter.InDimFilter.java

@Override
public RangeSet<String> getDimensionRangeSet(String dimension) {
    if (!Objects.equals(getDimension(), dimension) || getExtractionFn() != null) {
        return null;
    }/*from w  w  w. j av  a2  s.co m*/
    RangeSet<String> retSet = TreeRangeSet.create();
    for (String value : values) {
        String valueEquivalent = NullHandling.nullToEmptyIfNeeded(value);
        if (valueEquivalent == null) {
            // Case when SQL compatible null handling is enabled
            // Range.singleton(null) is invalid, so use the fact that
            // only null values are less than empty string.
            retSet.add(Range.lessThan(""));
        } else {
            retSet.add(Range.singleton(valueEquivalent));
        }
    }
    return retSet;
}

From source file:com.google.googlejavaformat.java.JavaInput.java

public RangeSet<Integer> characterRangesToTokenRanges(Collection<Range<Integer>> characterRanges)
        throws FormatterException {
    RangeSet<Integer> tokenRangeSet = TreeRangeSet.create();
    for (Range<Integer> characterRange0 : characterRanges) {
        Range<Integer> characterRange = characterRange0.canonical(DiscreteDomain.integers());
        tokenRangeSet.add(characterRangeToTokenRange(characterRange.lowerEndpoint(),
                characterRange.upperEndpoint() - characterRange.lowerEndpoint()));
    }//from   w w w  . j  a  va  2 s  . c o  m
    return tokenRangeSet;
}

From source file:org.sosy_lab.cpachecker.cpa.arg.ARGPathExport.java

private String tokensToText(Set<Integer> tokens) {
    StringBuilder result = new StringBuilder();
    RangeSet<Integer> tokenRanges = TreeRangeSet.create();
    for (Integer token : tokens) {
        tokenRanges.add(Range.closed(token, token));
    }/*from w w  w . ja  v a 2  s.co  m*/
    for (Range<Integer> range : tokenRanges.asRanges()) {
        if (result.length() > 0) {
            result.append(",");
        }
        Integer from = range.lowerEndpoint();
        Integer to = range.upperEndpoint();
        if (to - from == 0) {
            result.append(from);
        } else {
            result.append(from);
            result.append("-");
            result.append(to);
        }
    }

    return result.toString();
}

From source file:com.google.googlejavaformat.java.JavaOutput.java

/**
 * Emit a list of {@link Replacement}s to convert from input to output.
 *
 * @return a list of {@link Replacement}s, sorted by start index, without overlaps
 */// w  w w.java 2 s  . c om
public ImmutableList<Replacement> getFormatReplacements(RangeSet<Integer> iRangeSet0) {
    ImmutableList.Builder<Replacement> result = ImmutableList.builder();
    Map<Integer, Range<Integer>> kToJ = JavaOutput.makeKToIJ(this);

    // Expand the token ranges to align with re-formattable boundaries.
    RangeSet<Integer> breakableRanges = TreeRangeSet.create();
    RangeSet<Integer> iRangeSet = iRangeSet0.subRangeSet(Range.closed(0, javaInput.getkN()));
    for (Range<Integer> iRange : iRangeSet.asRanges()) {
        Range<Integer> range = expandToBreakableRegions(iRange.canonical(DiscreteDomain.integers()));
        if (range.equals(EMPTY_RANGE)) {
            // the range contains only whitespace
            continue;
        }
        breakableRanges.add(range);
    }

    // Construct replacements for each reformatted region.
    for (Range<Integer> range : breakableRanges.asRanges()) {

        Input.Tok startTok = startTok(javaInput.getToken(range.lowerEndpoint()));
        Input.Tok endTok = endTok(javaInput.getToken(range.upperEndpoint() - 1));

        // Add all output lines in the given token range to the replacement.
        StringBuilder replacement = new StringBuilder();

        int replaceFrom = startTok.getPosition();
        // Replace leading whitespace in the input with the whitespace from the formatted file
        while (replaceFrom > 0) {
            char previous = javaInput.getText().charAt(replaceFrom - 1);
            if (!CharMatcher.whitespace().matches(previous)) {
                break;
            }
            replaceFrom--;
        }

        int i = kToJ.get(startTok.getIndex()).lowerEndpoint();
        // Include leading blank lines from the formatted output, unless the formatted range
        // starts at the beginning of the file.
        while (i > 0 && getLine(i - 1).isEmpty()) {
            i--;
        }
        // Write out the formatted range.
        for (; i < kToJ.get(endTok.getIndex()).upperEndpoint(); i++) {
            // It's possible to run out of output lines (e.g. if the input ended with
            // multiple trailing newlines).
            if (i < getLineCount()) {
                if (i > 0) {
                    replacement.append(lineSeparator);
                }
                replacement.append(getLine(i));
            }
        }

        int replaceTo = Math.min(endTok.getPosition() + endTok.length(), javaInput.getText().length());
        // If the formatted ranged ended in the trailing trivia of the last token before EOF,
        // format all the way up to EOF to deal with trailing whitespace correctly.
        if (endTok.getIndex() == javaInput.getkN() - 1) {
            replaceTo = javaInput.getText().length();
        }
        // Replace trailing whitespace in the input with the whitespace from the formatted file.
        // If the trailing whitespace in the input includes one or more line breaks, preserve the
        // whitespace after the last newline to avoid re-indenting the line following the formatted
        // line.
        int newline = -1;
        while (replaceTo < javaInput.getText().length()) {
            char next = javaInput.getText().charAt(replaceTo);
            if (!CharMatcher.whitespace().matches(next)) {
                break;
            }
            int newlineLength = Newlines.hasNewlineAt(javaInput.getText(), replaceTo);
            if (newlineLength != -1) {
                newline = replaceTo;
                // Skip over the entire newline; don't count the second character of \r\n as a newline.
                replaceTo += newlineLength;
            } else {
                replaceTo++;
            }
        }
        if (newline != -1) {
            replaceTo = newline;
        }

        if (newline == -1) {
            // There wasn't an existing trailing newline; add one.
            replacement.append(lineSeparator);
        }
        for (; i < getLineCount(); i++) {
            String after = getLine(i);
            int idx = CharMatcher.whitespace().negate().indexIn(after);
            if (idx == -1) {
                // Write out trailing empty lines from the formatted output.
                replacement.append(lineSeparator);
            } else {
                if (newline == -1) {
                    // If there wasn't a trailing newline in the input, indent the next line.
                    replacement.append(after.substring(0, idx));
                }
                break;
            }
        }

        result.add(Replacement.create(replaceFrom, replaceTo, replacement.toString()));
    }
    return result.build();
}

From source file:org.eclipse.fx.ui.controls.styledtext.internal.ContentView.java

private void bindCaretListener() {
    this.caretOffset.addListener((x, o, n) -> {
        int oldCaretLine = getContent().getLineAtOffset(o.intValue());
        int newCaretLine = getContent().getLineAtOffset(n.intValue());

        RangeSet<Integer> toUpdate = TreeRangeSet.create();
        toUpdate.add(Range.closed(Integer.valueOf(oldCaretLine), Integer.valueOf(oldCaretLine)));
        toUpdate.add(Range.closed(Integer.valueOf(newCaretLine), Integer.valueOf(newCaretLine)));

        updateNodesNow(toUpdate);/*  w w  w.j a v  a2 s .co m*/
    });
}

From source file:org.eclipse.fx.ui.controls.styledtext.internal.ContentView.java

private void bindSelectionListener() {
    this.textSelection.addListener((x, o, n) -> {
        RangeSet<Integer> toUpdate = TreeRangeSet.create();
        if (o != null)
            toUpdate.add(getAffectedLines(o));
        if (n != null)
            toUpdate.add(getAffectedLines(n));
        updateNodesNow(toUpdate);/*from www  .j  a va 2 s. c  o m*/
    });
}