use of com.google.common.collect.Iterables.getLast in project error-prone by google.
the class MissingDefault method matchSwitch.
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
Type switchType = ASTHelpers.getType(tree.getExpression());
if (switchType.asElement().getKind() == ElementKind.ENUM) {
// by MissingCasesInEnumSwitch
return NO_MATCH;
}
Optional<? extends CaseTree> maybeDefault = tree.getCases().stream().filter(c -> c.getExpression() == null).findFirst();
if (!maybeDefault.isPresent()) {
Description.Builder description = buildDescription(tree);
if (!tree.getCases().isEmpty()) {
// Inserting the default after the last case is easier than finding the closing brace
// for the switch statement. Hopefully we don't often see switches with zero cases.
CaseTree lastCase = getLast(tree.getCases());
String replacement;
if (lastCase.getStatements().isEmpty() || Reachability.canCompleteNormally(Iterables.getLast(lastCase.getStatements()))) {
replacement = "\nbreak;\ndefault: // fall out\n";
} else {
replacement = "\ndefault: // fall out\n";
}
description.addFix(SuggestedFix.postfixWith(getLast(tree.getCases()), replacement));
}
return description.build();
}
CaseTree defaultCase = maybeDefault.get();
if (!defaultCase.getStatements().isEmpty()) {
return NO_MATCH;
}
// If `default` case is empty, and last in switch, add `// fall out` comment
// TODO(epmjohnston): Maybe move comment logic to go/bugpattern/FallThrough
int idx = tree.getCases().indexOf(defaultCase);
if (idx != tree.getCases().size() - 1) {
return NO_MATCH;
}
int end = state.getEndPosition(tree);
if (ErrorProneTokens.getTokens(state.getSourceCode().subSequence(state.getEndPosition(defaultCase), end).toString(), state.context).stream().anyMatch(t -> !t.comments().isEmpty())) {
return NO_MATCH;
}
return buildDescription(defaultCase).setMessage("Default case should be documented with a comment").addFix(SuggestedFix.postfixWith(defaultCase, " // fall out")).build();
}
Aggregations