Skip to content

Commit 4ae828b

Browse files
committed
Rework GoStructInitializationInspection
fixes #2819
1 parent eb669fc commit 4ae828b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+599
-71
lines changed

src/com/goide/completion/GoStructLiteralCompletion.java

+3-10
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@
1919
import com.goide.psi.*;
2020
import com.goide.psi.impl.GoPsiImplUtil;
2121
import com.intellij.psi.PsiElement;
22-
import com.intellij.util.ObjectUtils;
2322
import com.intellij.util.containers.ContainerUtil;
24-
import org.jetbrains.annotations.Contract;
2523
import org.jetbrains.annotations.NotNull;
2624
import org.jetbrains.annotations.Nullable;
2725

@@ -61,8 +59,8 @@ enum Variants {
6159

6260
@NotNull
6361
static Variants allowedVariants(@Nullable GoReferenceExpression structFieldReference) {
64-
GoValue value = parent(structFieldReference, GoValue.class);
65-
GoElement element = parent(value, GoElement.class);
62+
GoValue value = GoPsiTreeUtil.getDirectParentOfType(structFieldReference, GoValue.class);
63+
GoElement element = GoPsiTreeUtil.getDirectParentOfType(value, GoElement.class);
6664
if (element != null && element.getKey() != null) {
6765
return Variants.NONE;
6866
}
@@ -75,7 +73,7 @@ static Variants allowedVariants(@Nullable GoReferenceExpression structFieldRefer
7573
boolean hasValueInitializers = false;
7674
boolean hasFieldValueInitializers = false;
7775

78-
GoLiteralValue literalValue = parent(element, GoLiteralValue.class);
76+
GoLiteralValue literalValue = GoPsiTreeUtil.getDirectParentOfType(element, GoLiteralValue.class);
7977
List<GoElement> fieldInitializers = literalValue != null ? literalValue.getElementList() : Collections.emptyList();
8078
for (GoElement initializer : fieldInitializers) {
8179
if (initializer == element) {
@@ -105,9 +103,4 @@ static Set<String> alreadyAssignedFields(@Nullable GoLiteralValue literal) {
105103
return identifier != null ? identifier.getText() : null;
106104
});
107105
}
108-
109-
@Contract("null,_->null")
110-
private static <T> T parent(@Nullable PsiElement of, @NotNull Class<T> parentClass) {
111-
return ObjectUtils.tryCast(of != null ? of.getParent() : null, parentClass);
112-
}
113106
}

src/com/goide/inspections/GoStructInitializationInspection.java

+99-45
Original file line numberDiff line numberDiff line change
@@ -22,25 +22,32 @@
2222
import com.goide.util.GoUtil;
2323
import com.intellij.codeInspection.*;
2424
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
25-
import com.intellij.openapi.progress.ProgressManager;
2625
import com.intellij.openapi.project.Project;
26+
import com.intellij.openapi.util.Comparing;
2727
import com.intellij.openapi.util.InvalidDataException;
2828
import com.intellij.openapi.util.WriteExternalException;
2929
import com.intellij.psi.PsiElement;
3030
import com.intellij.psi.util.PsiTreeUtil;
31-
import com.intellij.util.containers.ContainerUtil;
31+
import com.intellij.util.ObjectUtils;
3232
import org.jdom.Element;
33+
import org.jetbrains.annotations.Contract;
3334
import org.jetbrains.annotations.NotNull;
3435
import org.jetbrains.annotations.Nullable;
3536

3637
import javax.swing.*;
3738
import java.util.List;
3839

40+
import static com.intellij.util.containers.ContainerUtil.*;
41+
import static java.lang.Math.min;
42+
import static java.util.stream.Collectors.toList;
43+
import static java.util.stream.IntStream.range;
44+
3945
public class GoStructInitializationInspection extends GoInspectionBase {
40-
public static final String REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME = "Replace with named struct field";
46+
public static final String REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME = "Replace with named struct fields";
47+
private static final GoReplaceWithNamedStructFieldQuickFix QUICK_FIX = new GoReplaceWithNamedStructFieldQuickFix();
4148
public boolean reportLocalStructs;
4249
/**
43-
* @deprecated use reportLocalStructs
50+
* @deprecated use {@link #reportLocalStructs}
4451
*/
4552
@SuppressWarnings("WeakerAccess") public Boolean reportImportedStructs;
4653

@@ -49,67 +56,114 @@ public class GoStructInitializationInspection extends GoInspectionBase {
4956
protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) {
5057
return new GoVisitor() {
5158
@Override
52-
public void visitLiteralValue(@NotNull GoLiteralValue o) {
53-
if (PsiTreeUtil.getParentOfType(o, GoReturnStatement.class, GoShortVarDeclaration.class, GoAssignmentStatement.class) == null) {
54-
return;
55-
}
56-
PsiElement parent = o.getParent();
57-
GoType refType = GoPsiImplUtil.getLiteralType(parent, false);
58-
if (refType instanceof GoStructType) {
59-
processStructType(holder, o, (GoStructType)refType);
59+
public void visitLiteralValue(@NotNull GoLiteralValue literalValue) {
60+
GoStructType structType = getLiteralStructType(literalValue);
61+
if (structType == null || !isStructImportedOrLocalAllowed(structType, literalValue)) return;
62+
63+
List<GoElement> elements = literalValue.getElementList();
64+
List<GoNamedElement> definitions = getFieldDefinitions(structType);
65+
66+
if (!areElementsKeysMatchesDefinitions(elements, definitions)) return;
67+
registerProblemsForElementsWithoutKeys(elements, definitions.size());
68+
}
69+
70+
private void registerProblemsForElementsWithoutKeys(@NotNull List<GoElement> elements, int definitionsCount) {
71+
for (int i = 0; i < min(elements.size(), definitionsCount); i++) {
72+
if (elements.get(i).getKey() != null) continue;
73+
holder.registerProblem(elements.get(i), "Unnamed field initialization", ProblemHighlightType.WEAK_WARNING, QUICK_FIX);
6074
}
6175
}
6276
};
6377
}
6478

65-
@Override
66-
public JComponent createOptionsPanel() {
67-
return new SingleCheckboxOptionsPanel("Report for local type definitions as well", this, "reportLocalStructs");
68-
}
79+
@Contract("null -> null")
80+
private static GoStructType getLiteralStructType(@Nullable GoLiteralValue literalValue) {
81+
GoCompositeLit parentLit = GoPsiTreeUtil.getDirectParentOfType(literalValue, GoCompositeLit.class);
82+
if (parentLit != null && !isStructLit(parentLit)) return null;
6983

70-
private void processStructType(@NotNull ProblemsHolder holder, @NotNull GoLiteralValue element, @NotNull GoStructType structType) {
71-
if (reportLocalStructs || !GoUtil.inSamePackage(structType.getContainingFile(), element.getContainingFile())) {
72-
processLiteralValue(holder, element, structType.getFieldDeclarationList());
73-
}
84+
GoStructType litType = ObjectUtils.tryCast(GoPsiImplUtil.getLiteralType(literalValue, parentLit == null), GoStructType.class);
85+
GoNamedElement definition = getFieldDefinition(GoPsiTreeUtil.getDirectParentOfType(literalValue, GoValue.class));
86+
return definition != null && litType != null ? getUnderlyingStructType(definition.getGoType(null)) : litType;
7487
}
7588

76-
private static void processLiteralValue(@NotNull ProblemsHolder holder,
77-
@NotNull GoLiteralValue o,
78-
@NotNull List<GoFieldDeclaration> fields) {
79-
List<GoElement> vals = o.getElementList();
80-
for (int elemId = 0; elemId < vals.size(); elemId++) {
81-
ProgressManager.checkCanceled();
82-
GoElement element = vals.get(elemId);
83-
if (element.getKey() == null && elemId < fields.size()) {
84-
String structFieldName = getFieldName(fields.get(elemId));
85-
LocalQuickFix[] fixes = structFieldName != null ? new LocalQuickFix[]{new GoReplaceWithNamedStructFieldQuickFix(structFieldName)}
86-
: LocalQuickFix.EMPTY_ARRAY;
87-
holder.registerProblem(element, "Unnamed field initialization", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fixes);
88-
}
89-
}
89+
@Nullable
90+
private static GoNamedElement getFieldDefinition(@Nullable GoValue value) {
91+
GoKey key = PsiTreeUtil.getPrevSiblingOfType(value, GoKey.class);
92+
GoFieldName fieldName = key != null ? key.getFieldName() : null;
93+
PsiElement field = fieldName != null ? fieldName.resolve() : null;
94+
return field instanceof GoAnonymousFieldDefinition || field instanceof GoFieldDefinition ? ObjectUtils
95+
.tryCast(field, GoNamedElement.class) : null;
9096
}
9197

9298
@Nullable
93-
private static String getFieldName(@NotNull GoFieldDeclaration declaration) {
94-
List<GoFieldDefinition> list = declaration.getFieldDefinitionList();
95-
GoFieldDefinition fieldDefinition = ContainerUtil.getFirstItem(list);
96-
return fieldDefinition != null ? fieldDefinition.getIdentifier().getText() : null;
99+
@Contract("null -> null")
100+
private static GoStructType getUnderlyingStructType(@Nullable GoType type) {
101+
return type != null ? ObjectUtils.tryCast(type.getUnderlyingType(), GoStructType.class) : null;
102+
}
103+
104+
private static boolean isStructLit(@NotNull GoCompositeLit compositeLit) {
105+
return getUnderlyingStructType(compositeLit.getGoType(null)) != null;
106+
}
107+
108+
private boolean isStructImportedOrLocalAllowed(@NotNull GoStructType structType, @NotNull GoLiteralValue literalValue) {
109+
return reportLocalStructs || !GoUtil.inSamePackage(structType.getContainingFile(), literalValue.getContainingFile());
110+
}
111+
112+
private static boolean areElementsKeysMatchesDefinitions(@NotNull List<GoElement> elements, @NotNull List<GoNamedElement> definitions) {
113+
return range(0, elements.size()).allMatch(i -> isNullOrNamesEqual(elements.get(i).getKey(), GoPsiImplUtil.getByIndex(definitions, i)));
114+
}
115+
116+
@Contract("null, _ -> true; !null, null -> false")
117+
private static boolean isNullOrNamesEqual(@Nullable GoKey key, @Nullable GoNamedElement elementToCompare) {
118+
return key == null || elementToCompare != null && Comparing.equal(key.getText(), elementToCompare.getName());
119+
}
120+
121+
@NotNull
122+
private static List<GoNamedElement> getFieldDefinitions(@Nullable GoStructType type) {
123+
return type != null ? type.getFieldDeclarationList().stream()
124+
.flatMap(declaration -> getFieldDefinitions(declaration).stream())
125+
.collect(toList()) : emptyList();
126+
}
127+
128+
@NotNull
129+
private static List<GoNamedElement> getFieldDefinitions(@NotNull GoFieldDeclaration declaration) {
130+
GoNamedElement anonymousDefinition = ObjectUtils.tryCast(declaration.getAnonymousFieldDefinition(), GoNamedElement.class);
131+
return anonymousDefinition != null
132+
? list(anonymousDefinition)
133+
: map(declaration.getFieldDefinitionList(), definition -> ObjectUtils.tryCast(definition, GoNamedElement.class));
134+
}
135+
136+
@Override
137+
public JComponent createOptionsPanel() {
138+
return new SingleCheckboxOptionsPanel("Report for local type definitions as well", this, "reportLocalStructs");
97139
}
98140

99141
private static class GoReplaceWithNamedStructFieldQuickFix extends LocalQuickFixBase {
100-
private String myStructField;
101142

102-
public GoReplaceWithNamedStructFieldQuickFix(@NotNull String structField) {
143+
public GoReplaceWithNamedStructFieldQuickFix() {
103144
super(REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME);
104-
myStructField = structField;
105145
}
106146

107147
@Override
108148
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
109-
PsiElement startElement = descriptor.getStartElement();
110-
if (startElement instanceof GoElement) {
111-
startElement.replace(GoElementFactory.createLiteralValueElement(project, myStructField, startElement.getText()));
112-
}
149+
PsiElement element = ObjectUtils.tryCast(descriptor.getStartElement(), GoElement.class);
150+
GoLiteralValue literal = element != null && element.isValid() ? PsiTreeUtil.getParentOfType(element, GoLiteralValue.class) : null;
151+
152+
List<GoElement> elements = literal != null ? literal.getElementList() : emptyList();
153+
List<GoNamedElement> definitions = getFieldDefinitions(getLiteralStructType(literal));
154+
if (!areElementsKeysMatchesDefinitions(elements, definitions)) return;
155+
addKeysToElements(project, elements, definitions);
156+
}
157+
}
158+
159+
private static void addKeysToElements(@NotNull Project project,
160+
@NotNull List<GoElement> elements,
161+
@NotNull List<GoNamedElement> definitions) {
162+
for (int i = 0; i < min(elements.size(), definitions.size()); i++) {
163+
GoElement element = elements.get(i);
164+
String fieldDefinitionName = definitions.get(i).getName();
165+
GoValue value = fieldDefinitionName != null && element.getKey() == null ? element.getValue() : null;
166+
if (value != null) element.replace(GoElementFactory.createLiteralValueElement(project, fieldDefinitionName, value.getText()));
113167
}
114168
}
115169

src/com/goide/psi/GoPsiTreeUtil.java

+7
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,10 @@
2626
import com.intellij.psi.stubs.StubElement;
2727
import com.intellij.psi.util.PsiTreeUtil;
2828
import com.intellij.psi.util.PsiUtilCore;
29+
import com.intellij.util.ObjectUtils;
2930
import com.intellij.util.SmartList;
3031
import com.intellij.util.containers.ContainerUtil;
32+
import org.jetbrains.annotations.Contract;
3133
import org.jetbrains.annotations.NotNull;
3234
import org.jetbrains.annotations.Nullable;
3335

@@ -155,5 +157,10 @@ private static PsiElement findNotWhiteSpaceElementAtOffset(@NotNull GoFile file,
155157
}
156158
return element;
157159
}
160+
161+
@Contract("null,_->null")
162+
public static <T> T getDirectParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass) {
163+
return element != null ? ObjectUtils.tryCast(element.getParent(), aClass) : null;
164+
}
158165
}
159166

src/com/goide/psi/impl/GoElementFactory.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ public static GoType createType(@NotNull Project project, @NotNull String text)
256256
return PsiTreeUtil.findChildOfType(file, GoType.class);
257257
}
258258

259-
public static PsiElement createLiteralValueElement(@NotNull Project project, @NotNull String key, @NotNull String value) {
259+
public static GoElement createLiteralValueElement(@NotNull Project project, @NotNull String key, @NotNull String value) {
260260
GoFile file = createFileFromText(project, "package a; var _ = struct { a string } { " + key + ": " + value + " }");
261261
return PsiTreeUtil.findChildOfType(file, GoElement.class);
262262
}

src/com/goide/psi/impl/GoPsiImplUtil.java

+4-2
Original file line numberDiff line numberDiff line change
@@ -569,11 +569,12 @@ public static GoType getLiteralType(@Nullable PsiElement context, boolean consid
569569
@Nullable
570570
public static GoValue getParentGoValue(@NotNull PsiElement element) {
571571
PsiElement place = element;
572-
while ((place = PsiTreeUtil.getParentOfType(place, GoLiteralValue.class)) != null) {
572+
do {
573573
if (place.getParent() instanceof GoValue) {
574574
return (GoValue)place.getParent();
575575
}
576576
}
577+
while ((place = PsiTreeUtil.getParentOfType(place, GoLiteralValue.class)) != null);
577578
return null;
578579
}
579580

@@ -1468,7 +1469,8 @@ public static GoExpression getValue(@NotNull GoConstDefinition definition) {
14681469
return getByIndex(((GoConstSpec)parent).getExpressionList(), index);
14691470
}
14701471

1471-
private static <T> T getByIndex(@NotNull List<T> list, int index) {
1472+
@Nullable
1473+
public static <T> T getByIndex(@NotNull List<T> list, int index) {
14721474
return 0 <= index && index < list.size() ? list.get(index) : null;
14731475
}
14741476

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package foo
2+
3+
type S struct {
4+
X string
5+
string
6+
Y int
7+
}
8+
func main() {
9+
var s S
10+
s = S{X: "X", string: "a", Y: 1}
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package foo
2+
3+
type S struct {
4+
X string
5+
string
6+
Y int
7+
}
8+
func main() {
9+
var s S
10+
s = S{<caret><weak_warning descr="Unnamed field initialization">"X"</weak_warning>, <weak_warning descr="Unnamed field initialization">"a"</weak_warning>, Y: 1}
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package foo
2+
3+
type S struct {
4+
X, Y int
5+
}
6+
func main() {
7+
s := S{X: 1, Y: 0, 2}
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package foo
2+
3+
type S struct {
4+
X, Y int
5+
}
6+
func main() {
7+
s := S{<weak_warning descr="Unnamed field initialization"><caret>1</weak_warning>, <weak_warning descr="Unnamed field initialization">0</weak_warning>, 2}
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package foo
2+
3+
type S struct {
4+
X, Y int
5+
}
6+
func main() {
7+
s := S{<caret>1, 0, X: 2}
8+
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package foo
2+
3+
type S struct {
4+
t int
5+
}
6+
7+
func main() {
8+
var _ = []S{ {t: 1} }
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package foo
2+
3+
type S struct {
4+
t int
5+
}
6+
7+
func main() {
8+
var _ = []S{ {<weak_warning descr="Unnamed field initialization"><caret>1</weak_warning>} }
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package foo
2+
3+
func main() {
4+
type B struct {
5+
Y int
6+
}
7+
8+
type S struct {
9+
X int
10+
B
11+
Z int
12+
}
13+
14+
s := S{X: 1, B: B{Y: 2}, Z: 3}
15+
print(s.B.Y)
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package foo
2+
3+
func main() {
4+
type B struct {
5+
Y int
6+
}
7+
8+
type S struct {
9+
X int
10+
B
11+
Z int
12+
}
13+
14+
s := S{<weak_warning descr="Unnamed field initialization">1<caret></weak_warning>, <weak_warning descr="Unnamed field initialization">B{Y: 2}</weak_warning>, <weak_warning descr="Unnamed field initialization">3</weak_warning>}
15+
print(s.B.Y)
16+
}

0 commit comments

Comments
 (0)