use of com.google.common.base.Converter in project error-prone by google.
the class CanonicalDuration method matchMethodInvocation.
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Api api;
if (JAVA_TIME_MATCHER.matches(tree, state)) {
api = Api.JAVA;
} else if (JODA_MATCHER.matches(tree, state)) {
api = Api.JODA;
} else {
return NO_MATCH;
}
if (tree.getArguments().size() != 1) {
// TODO(cushon): ofSeconds w/ nano adjustment?
return NO_MATCH;
}
Tree arg = getOnlyElement(tree.getArguments());
if (!(arg instanceof LiteralTree)) {
// don't inline constants
return NO_MATCH;
}
Number value = constValue(arg, Number.class);
if (value == null) {
return NO_MATCH;
}
if (value.intValue() == 0) {
switch(api) {
case JODA:
ExpressionTree receiver = getReceiver(tree);
SuggestedFix fix;
if (receiver == null) {
// static import of the method
fix = SuggestedFix.builder().addImport(api.getDurationFullyQualifiedName()).replace(tree, "Duration.ZERO").build();
} else {
fix = SuggestedFix.replace(state.getEndPosition(getReceiver(tree)), state.getEndPosition(tree), ".ZERO");
}
return buildDescription(tree).setMessage("Duration can be expressed more clearly without units, as Duration.ZERO").addFix(fix).build();
case JAVA:
// don't rewrite e.g. `ofMillis(0)` to `ofDays(0)`
return NO_MATCH;
}
throw new AssertionError(api);
}
MethodSymbol sym = getSymbol(tree);
if (!METHOD_NAME_TO_UNIT.containsKey(sym.getSimpleName().toString())) {
return NO_MATCH;
}
TemporalUnit unit = METHOD_NAME_TO_UNIT.get(sym.getSimpleName().toString());
if (Objects.equals(BLACKLIST.get(unit), value.longValue())) {
return NO_MATCH;
}
Duration duration = Duration.of(value.longValue(), unit);
// largest unit that can be used to exactly express the duration.
for (Map.Entry<ChronoUnit, Converter<Duration, Long>> entry : CONVERTERS.entrySet()) {
ChronoUnit nextUnit = entry.getKey();
if (unit.equals(nextUnit)) {
// We reached the original unit, no simplification is possible.
break;
}
Converter<Duration, Long> converter = entry.getValue();
long nextValue = converter.convert(duration);
if (converter.reverse().convert(nextValue).equals(duration)) {
// We reached a larger than original unit that precisely expresses the duration, rewrite to
// use it instead.
String name = FACTORIES.get(api, nextUnit);
String replacement = String.format("%s(%d%s)", name, nextValue, nextValue == ((int) nextValue) ? "" : "L");
ExpressionTree receiver = getReceiver(tree);
if (receiver == null) {
// static import of the method
SuggestedFix fix = SuggestedFix.builder().addStaticImport(api.getDurationFullyQualifiedName() + "." + name).replace(tree, replacement).build();
return describeMatch(tree, fix);
} else {
return describeMatch(tree, SuggestedFix.replace(state.getEndPosition(receiver), state.getEndPosition(tree), "." + replacement));
}
}
}
return NO_MATCH;
}
Aggregations