Skip to content

Commit d08951c

Browse files
committed
[codegen] refactor search index codegen to reduce fragments boilerplate
Change-Id: Ifcfff898b614cd450795c265464a7ca11aac0cba Signed-off-by: rmp22 <195054967+rmp22@users.noreply.github.com>
1 parent 46a7579 commit d08951c

1 file changed

Lines changed: 37 additions & 4 deletions

File tree

packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@
3737
import javax.annotation.processing.SupportedOptions;
3838
import javax.lang.model.SourceVersion;
3939
import javax.lang.model.element.Element;
40+
import javax.lang.model.element.ElementKind;
41+
import javax.lang.model.element.ExecutableElement;
4042
import javax.lang.model.element.Modifier;
4143
import javax.lang.model.element.Name;
4244
import javax.lang.model.element.TypeElement;
@@ -138,10 +140,41 @@ public Name visitType(TypeElement typeElement, Void aVoid) {
138140
} else if ((forTarget & SearchIndexable.ARC) != 0) {
139141
builder = arcConstructorBuilder;
140142
}
141-
builder.addCode(
142-
"$N(new com.android.settingslib.search.SearchIndexableData($L.class, $L"
143-
+ ".SEARCH_INDEX_DATA_PROVIDER));\n",
144-
addIndex, className, className);
143+
boolean hasNoArgConstructor = false;
144+
for (Element enclosed : ((TypeElement) element).getEnclosedElements()) {
145+
if (enclosed.getKind() == ElementKind.CONSTRUCTOR &&
146+
((ExecutableElement) enclosed).getParameters().isEmpty()) {
147+
hasNoArgConstructor = true;
148+
break;
149+
}
150+
}
151+
152+
builder.beginControlFlow("try")
153+
.addCode(
154+
"$N(new com.android.settingslib.search.SearchIndexableData($L.class, " +
155+
"$L.SEARCH_INDEX_DATA_PROVIDER));\n",
156+
addIndex, className, className)
157+
.nextControlFlow("catch (Throwable e1)");
158+
159+
if (hasNoArgConstructor) {
160+
builder.beginControlFlow("try")
161+
.addStatement("Object obj = new $L()", className)
162+
.beginControlFlow("if (obj instanceof $T)",
163+
ClassName.get("com.android.settings.search", "SearchIndexProviderHolder"))
164+
.addStatement(
165+
"$N(new com.android.settingslib.search.SearchIndexableData($L.class, " +
166+
"(($T) obj).getSearchIndexProvider()))",
167+
addIndex, className,
168+
ClassName.get("com.android.settings.search", "SearchIndexProviderHolder"))
169+
.endControlFlow()
170+
.nextControlFlow("catch (Throwable e2)")
171+
.addComment("// No-arg instantiation failed or not a SearchIndexProviderHolder.")
172+
.endControlFlow();
173+
} else {
174+
builder.addComment("// Skipped instantiation: $L has no no-arg constructor", className);
175+
}
176+
177+
builder.endControlFlow();
145178
} else {
146179
throw new IllegalStateException("Null classname from " + element);
147180
}

0 commit comments

Comments
 (0)