Skip to content

Commit

Permalink
QL: Make use of Java 17 instanceof pattern matching (#81635)
Browse files Browse the repository at this point in the history
Replace instanceof / cast with Java 17 instanceof pattern matching.
This small syntactic sugar improves readability and reduces the chance
for errors (by avoid to cast a different variable then the one checked).

Note - temporary formatting exceptions were required due to
https://bugs.eclipse.org/bugs/show_bug.cgi?id=574437

Fix #80884
  • Loading branch information
costin committed Dec 13, 2021
1 parent 30bda56 commit 10077ef
Show file tree
Hide file tree
Showing 45 changed files with 215 additions and 367 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ static Attribute resolveAgainstList(UnresolvedAttribute u, Collection<Attribute>

private static Attribute handleSpecialFields(UnresolvedAttribute u, Attribute named, boolean allowCompound) {
// if it's a object/compound type, keep it unresolved with a nice error message
if (named instanceof FieldAttribute) {
FieldAttribute fa = (FieldAttribute) named;
if (named instanceof FieldAttribute fa) {

// incompatible mappings
if (fa.field() instanceof InvalidMappedField) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ Collection<Failure> verify(LogicalPlan plan, Function<String, Collection<String>
}
if (ae instanceof Unresolvable) {
// handle Attributes differently to provide more context
if (ae instanceof UnresolvedAttribute) {
UnresolvedAttribute ua = (UnresolvedAttribute) ae;
if (ae instanceof UnresolvedAttribute ua) {
// only work out the synonyms for raw unresolved attributes
if (ua.customMessage() == false) {
boolean useQualifier = ua.qualifier() != null;
Expand Down Expand Up @@ -172,12 +171,10 @@ Collection<Failure> verify(LogicalPlan plan, Function<String, Collection<String>
b.set(PIPE_HEAD.ordinal());
} else if (p instanceof Tail) {
b.set(PIPE_TAIL.ordinal());
} else if (p instanceof Join) {
Join j = (Join) p;
} else if (p instanceof Join j) {

if (p instanceof Sequence) {
if (p instanceof Sequence s) {
b.set(SEQUENCE.ordinal());
Sequence s = (Sequence) p;
if (s.maxSpan().duration() > 0) {
b.set(SEQUENCE_MAXSPAN.ordinal());
}
Expand Down Expand Up @@ -258,8 +255,7 @@ Collection<Failure> verify(LogicalPlan plan, Function<String, Collection<String>
}

private void checkJoinKeyTypes(LogicalPlan plan, Set<Failure> localFailures) {
if (plan instanceof Join) {
Join join = (Join) plan;
if (plan instanceof Join join) {
List<KeyedFilter> queries = join.queries();
KeyedFilter until = join.until();
// pick first query and iterate its keys
Expand Down Expand Up @@ -299,8 +295,7 @@ private void checkRemoteClusterOnSameVersion(
Function<String, Collection<String>> versionIncompatibleClusters,
Collection<Failure> localFailures
) {
if (plan instanceof EsRelation) {
EsRelation esRelation = (EsRelation) plan;
if (plan instanceof EsRelation esRelation) {
Collection<String> incompatibleClusters = versionIncompatibleClusters.apply(esRelation.index().name());
if (incompatibleClusters.size() > 0) {
localFailures.add(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,7 @@ public Executable assemble(
for (int j = 0; j < keyExtractors.size(); j++) {
HitExtractor extractor = keyExtractors.get(j);

if (extractor instanceof AbstractFieldHitExtractor) {
AbstractFieldHitExtractor hitExtractor = (AbstractFieldHitExtractor) extractor;
if (extractor instanceof AbstractFieldHitExtractor hitExtractor) {
// remember if the field is optional
boolean isOptional = keys.get(j) instanceof OptionalResolvedAttribute;
// no nested fields
Expand Down Expand Up @@ -149,8 +148,7 @@ public Executable assemble(
}

private HitExtractor timestampExtractor(HitExtractor hitExtractor) {
if (hitExtractor instanceof FieldHitExtractor) {
FieldHitExtractor fe = (FieldHitExtractor) hitExtractor;
if (hitExtractor instanceof FieldHitExtractor fe) {
return (fe instanceof TimestampFieldHitExtractor) ? hitExtractor : new TimestampFieldHitExtractor(fe);
}
throw new EqlIllegalArgumentException("Unexpected extractor [{}]", hitExtractor);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,7 @@ public static List<HitExtractor> createExtractor(List<FieldExtraction> fields, E
}

public static HitExtractor createExtractor(FieldExtraction ref, EqlConfiguration cfg) {
if (ref instanceof SearchHitFieldRef) {
SearchHitFieldRef f = (SearchHitFieldRef) ref;
if (ref instanceof SearchHitFieldRef f) {
return new FieldHitExtractor(f.name(), f.getDataType(), cfg.zoneId(), f.hitName(), false);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@ private static void sorting(QueryContainer container, SearchSourceBuilder source
for (Sort sortable : container.sort().values()) {
SortBuilder<?> sortBuilder = null;

if (sortable instanceof AttributeSort) {
AttributeSort as = (AttributeSort) sortable;
if (sortable instanceof AttributeSort as) {
Attribute attr = as.attribute();

// sorting only works on not-analyzed fields - look for a multi-field replacement
Expand Down Expand Up @@ -133,8 +132,7 @@ private static void sorting(QueryContainer container, SearchSourceBuilder source
sortBuilder = fieldSort;
}
}
} else if (sortable instanceof ScriptSort) {
ScriptSort ss = (ScriptSort) sortable;
} else if (sortable instanceof ScriptSort ss) {
sortBuilder = scriptSort(
ss.script().toPainless(),
ss.script().outputType().isNumeric() ? ScriptSortType.NUMBER : ScriptSortType.STRING
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,7 @@ protected LogicalPlan rule(Filter filter) {
private static boolean isWildcard(Expression expr) {
if (expr instanceof Literal) {
Object value = expr.fold();
if (value instanceof String) {
String string = (String) value;
if (value instanceof String string) {
return string.contains("*") || string.contains("?");
}
}
Expand Down Expand Up @@ -438,8 +437,7 @@ static final class SortByLimit extends OptimizerRule<LimitWithOffset> {
protected LogicalPlan rule(LimitWithOffset limit) {
if (limit.limit().foldable()) {
LogicalPlan child = limit.child();
if (child instanceof OrderBy) {
OrderBy ob = (OrderBy) child;
if (child instanceof OrderBy ob) {
if (PushDownOrderBy.isDefaultOrderBy(ob)) {
int l = (Integer) limit.limit().fold();
OrderDirection direction = Integer.signum(l) > 0 ? OrderDirection.ASC : OrderDirection.DESC;
Expand Down Expand Up @@ -470,8 +468,7 @@ protected LogicalPlan rule(OrderBy orderBy) {
// but if the order is descending, apply that only to the first query
// which is used to discover the window for which matching is being applied.
//
if (child instanceof Join) {
Join join = (Join) child;
if (child instanceof Join join) {
List<KeyedFilter> queries = join.queries();

// the main reason DESC is used is the lack of search_before (which is emulated through search_after + ASC)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ private static class SimpleExecMapper extends MapExecRule<LogicalPlan> {
@Override
protected PhysicalPlan map(LogicalPlan p) {

if (p instanceof Sequence) {
Sequence s = (Sequence) p;
if (p instanceof Sequence s) {
List<List<Attribute>> keys = new ArrayList<>(s.children().size());
List<PhysicalPlan> matches = new ArrayList<>(keys.size());

Expand All @@ -89,29 +88,24 @@ protected PhysicalPlan map(LogicalPlan p) {
return new LocalExec(p.source(), ((LocalRelation) p).executable());
}

if (p instanceof Project) {
Project pj = (Project) p;
if (p instanceof Project pj) {
return new ProjectExec(p.source(), map(pj.child()), pj.projections());
}

if (p instanceof Filter) {
Filter fl = (Filter) p;
if (p instanceof Filter fl) {
return new FilterExec(p.source(), map(fl.child()), fl.condition());
}

if (p instanceof OrderBy) {
OrderBy o = (OrderBy) p;
if (p instanceof OrderBy o) {
return new OrderExec(p.source(), map(o.child()), o.order());
}

if (p instanceof LimitWithOffset) {
LimitWithOffset l = (LimitWithOffset) p;
if (p instanceof LimitWithOffset l) {
int limit = (Integer) DataTypeConverter.convert(Foldables.valueOf(l.limit()), DataTypes.INTEGER);
return new LimitWithOffsetExec(p.source(), map(l.child()), new Limit(limit, l.offset()));
}

if (p instanceof EsRelation) {
EsRelation c = (EsRelation) p;
if (p instanceof EsRelation c) {
List<Attribute> output = c.output();
QueryContainer container = new QueryContainer();
if (c.frozen()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ protected PhysicalPlan rule(OrderExec plan, EsQueryExec query) {
String lookup = Expressions.id(orderExpression);

// field
if (orderExpression instanceof FieldAttribute) {
FieldAttribute fa = (FieldAttribute) orderExpression;
if (orderExpression instanceof FieldAttribute fa) {
qContainer = qContainer.addSort(lookup, new AttributeSort(fa, direction, missing));
}
// unknown
Expand All @@ -106,12 +105,10 @@ private static class FoldLimit extends FoldingRule<LimitWithOffsetExec> {
protected PhysicalPlan rule(LimitWithOffsetExec limit) {
PhysicalPlan plan = limit;
PhysicalPlan child = limit.child();
if (child instanceof EsQueryExec) {
EsQueryExec query = (EsQueryExec) child;
if (child instanceof EsQueryExec query) {
plan = query.with(query.queryContainer().with(limit.limit()));
}
if (child instanceof SequenceExec) {
SequenceExec exec = (SequenceExec) child;
if (child instanceof SequenceExec exec) {
plan = exec.with(limit.limit());
}
return plan;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,7 @@ protected Query asQuery(ScalarFunction f, TranslatorHandler handler) {
}

public static Query doTranslate(ScalarFunction f, TranslatorHandler handler) {
if (f instanceof CIDRMatch) {
CIDRMatch cm = (CIDRMatch) f;
if (f instanceof CIDRMatch cm) {
if (cm.input() instanceof FieldAttribute && Expressions.foldable(cm.addresses())) {
String targetFieldName = handler.nameOf(((FieldAttribute) cm.input()).exactAttribute());

Expand Down Expand Up @@ -198,8 +197,7 @@ public static Query doTranslate(CaseInsensitiveScalarFunction f, TranslatorHandl
return q;
}

if (f instanceof BinaryComparisonCaseInsensitiveFunction) {
BinaryComparisonCaseInsensitiveFunction bccif = (BinaryComparisonCaseInsensitiveFunction) f;
if (f instanceof BinaryComparisonCaseInsensitiveFunction bccif) {

String targetFieldName = null;
String wildcardQuery = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ public void onFailure(Exception e) {
* contain as cause the VerificationException with "*,-*" pattern but we'll rewrite the INFE here with the initial
* pattern that failed resolving. More details here https://github.com/elastic/elasticsearch/issues/63529
*/
if (e instanceof IndexNotFoundException) {
IndexNotFoundException infe = (IndexNotFoundException) e;
if (e instanceof IndexNotFoundException infe) {
if (infe.getIndex() != null && infe.getIndex().getName().equals("Unknown index [*,-*]")) {
finalException = new IndexNotFoundException(indices, infe.getCause());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,9 @@ private static void qualifyEvents(List<EqlSearchResponse.Event> events, String c

private static Exception qualifyException(Exception e, String[] indices, String clusterAlias) {
Exception finalException = e;
if (e instanceof RemoteTransportException && e.getCause() instanceof IndexNotFoundException) {
IndexNotFoundException infe = (IndexNotFoundException) e.getCause();
// @formatter:off - https://bugs.eclipse.org/bugs/show_bug.cgi?id=574437
if (e instanceof RemoteTransportException && e.getCause() instanceof IndexNotFoundException infe) {
// @formatter:on
if (infe.getIndex() != null) {
String qualifiedIndex;
String exceptionIndexName = infe.getIndex().getName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,7 @@ private Tuple<QueryContainer, FieldExtraction> asFieldExtraction(Attribute attr)
// resolve it Expression
Expression expression = attributes.getOrDefault(attr, attr);

if (expression instanceof FieldAttribute) {
FieldAttribute fa = (FieldAttribute) expression;
if (expression instanceof FieldAttribute fa) {
if (fa.isNested()) {
throw new UnsupportedOperationException("Nested not yet supported");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ protected Object unwrapFieldsMultiValue(Object values) {
// extract the sub-field from a nested field (dep.dep_name -> dep_name)
return unwrapFieldsMultiValue(((Map<?, ?>) values).get(fieldName.substring(hitName.length() + 1)));
}
if (values instanceof List) {
List<?> list = (List<?>) values;
if (values instanceof List<?> list) {
if (list.isEmpty()) {
return null;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ public int hashCode() {

@Override
public boolean equals(Object obj) {
if (obj instanceof AttributeWrapper) {
AttributeWrapper aw = (AttributeWrapper) obj;
if (obj instanceof AttributeWrapper aw) {
return attr.semanticEquals(aw.attr);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,7 @@ public static List<Attribute> onlyPrimitiveFieldAttributes(Collection<Attribute>

for (Attribute a : attributes) {
if (DataTypes.isUnsupported(a.dataType()) == false && DataTypes.isPrimitive(a.dataType())) {
if (a instanceof FieldAttribute) {
FieldAttribute fa = (FieldAttribute) a;
if (a instanceof FieldAttribute fa) {
// skip nested fields and seen multi-fields
if (fa.isNested() == false && seenMultiFields.contains(fa.parent()) == false) {
filtered.add(a);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,26 +80,23 @@ protected ScriptTemplate scriptWithFoldable(Expression foldable) {
//

// wrap intervals with dedicated methods for serialization
if (fold instanceof ZonedDateTime) {
ZonedDateTime zdt = (ZonedDateTime) fold;
if (fold instanceof ZonedDateTime zdt) {
return new ScriptTemplate(
processScript("{sql}.asDateTime({})"),
paramsBuilder().variable(DateUtils.toString(zdt)).build(),
dataType()
);
}

if (fold instanceof IntervalScripting) {
IntervalScripting is = (IntervalScripting) fold;
if (fold instanceof IntervalScripting is) {
return new ScriptTemplate(
processScript(is.script()),
paramsBuilder().variable(is.value()).variable(is.typeName()).build(),
dataType()
);
}

if (fold instanceof OffsetTime) {
OffsetTime ot = (OffsetTime) fold;
if (fold instanceof OffsetTime ot) {
return new ScriptTemplate(processScript("{sql}.asTime({})"), paramsBuilder().variable(ot.toString()).build(), dataType());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,11 @@ String aggName() {
public String aggProperty() {
AggregateFunction agg = value();

if (agg instanceof InnerAggregate) {
InnerAggregate inner = (InnerAggregate) agg;
if (agg instanceof InnerAggregate inner) {
return Expressions.id((Expression) inner.outer()) + "." + inner.innerName();
}
// Count needs special handling since in most cases it is not a dedicated aggregation
else if (agg instanceof Count) {
Count c = (Count) agg;
else if (agg instanceof Count c) {
// for literals get the last count
if (c.field().foldable()) {
return COUNT_PATH;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,11 @@ Map<String, String> asAggPaths() {
int aggs = 0;

for (Param<?> p : params) {
if (p instanceof Agg) {
Agg a = (Agg) p;
if (p instanceof Agg a) {
String s = a.aggProperty() != null ? a.aggProperty() : a.aggName();
map.put(p.prefix() + aggs++, s);
}
if (p instanceof Grouping) {
Grouping g = (Grouping) p;
if (p instanceof Grouping g) {
map.put(p.prefix() + aggs++, g.groupName());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
public abstract class Predicates {

public static List<Expression> splitAnd(Expression exp) {
if (exp instanceof And) {
And and = (And) exp;
if (exp instanceof And and) {
List<Expression> list = new ArrayList<>();
list.addAll(splitAnd(and.left()));
list.addAll(splitAnd(and.right()));
Expand All @@ -31,8 +30,7 @@ public static List<Expression> splitAnd(Expression exp) {
}

public static List<Expression> splitOr(Expression exp) {
if (exp instanceof Or) {
Or or = (Or) exp;
if (exp instanceof Or or) {
List<Expression> list = new ArrayList<>();
list.addAll(splitOr(or.left()));
list.addAll(splitOr(or.right()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -511,8 +511,7 @@ private static EsField createField(

EsField esField = field.apply(fieldName);

if (parent != null && parent instanceof UnsupportedEsField) {
UnsupportedEsField unsupportedParent = (UnsupportedEsField) parent;
if (parent != null && parent instanceof UnsupportedEsField unsupportedParent) {
String inherited = unsupportedParent.getInherited();
String type = unsupportedParent.getOriginalType();

Expand Down

0 comments on commit 10077ef

Please sign in to comment.