Skip to content

Commit

Permalink
Rework GoStructInitializationInspection
Browse files Browse the repository at this point in the history
fixes #2819
  • Loading branch information
wbars committed Nov 16, 2016
1 parent eb669fc commit c8af522
Show file tree
Hide file tree
Showing 23 changed files with 306 additions and 97 deletions.
129 changes: 83 additions & 46 deletions src/com/goide/inspections/GoStructInitializationInspection.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,94 +22,131 @@
import com.goide.util.GoUtil;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ObjectUtils;
import org.jdom.Element;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.List;

import static com.intellij.openapi.util.NullUtils.hasNull;
import static com.intellij.util.containers.ContainerUtil.*;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;

public class GoStructInitializationInspection extends GoInspectionBase {
public static final String REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME = "Replace with named struct field";
public static final String REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME = "Replace with named struct fields";
private static final GoReplaceWithNamedStructFieldQuickFix QUICK_FIX = new GoReplaceWithNamedStructFieldQuickFix();
public boolean reportLocalStructs;
/**
* @deprecated use reportLocalStructs
* @deprecated use {@link #reportLocalStructs}
*/
@SuppressWarnings("WeakerAccess") public Boolean reportImportedStructs;

@NotNull
@Override
protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) {
return new GoVisitor() {

@Override
public void visitLiteralValue(@NotNull GoLiteralValue o) {
if (PsiTreeUtil.getParentOfType(o, GoReturnStatement.class, GoShortVarDeclaration.class, GoAssignmentStatement.class) == null) {
return;
}
PsiElement parent = o.getParent();
GoType refType = GoPsiImplUtil.getLiteralType(parent, false);
if (refType instanceof GoStructType) {
processStructType(holder, o, (GoStructType)refType);
public void visitCompositeLit(@NotNull GoCompositeLit compositeLit) {
GoLiteralValue literalValue = compositeLit.getLiteralValue();
GoStructType structType = getStructType(literalValue);
if (structType == null || !isStructImportedOrLocalAllowed(structType, literalValue)) return;

List<String> elementsNames = getNames(literalValue.getElementList());
if (hasNull(elementsNames.toArray()) && areElementsNamesMatchesDefinitions(elementsNames, getFieldDefinitionsNames(structType))) {
holder.registerProblem(literalValue, "Unnamed field initializations", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, QUICK_FIX);
}
}
};
}

@Override
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel("Report for local type definitions as well", this, "reportLocalStructs");
@Nullable
@Contract("null -> null")
private static GoStructType getStructType(@Nullable GoLiteralValue literal) {
return literal != null ? ObjectUtils.tryCast(GoPsiImplUtil.getLiteralType(literal.getParent(), false), GoStructType.class) : null;
}

private void processStructType(@NotNull ProblemsHolder holder, @NotNull GoLiteralValue element, @NotNull GoStructType structType) {
if (reportLocalStructs || !GoUtil.inSamePackage(structType.getContainingFile(), element.getContainingFile())) {
processLiteralValue(holder, element, structType.getFieldDeclarationList());
}
private boolean isStructImportedOrLocalAllowed(@NotNull GoStructType structType, @NotNull GoLiteralValue literalValue) {
return reportLocalStructs || !GoUtil.inSamePackage(structType.getContainingFile(), literalValue.getContainingFile());
}

private static void processLiteralValue(@NotNull ProblemsHolder holder,
@NotNull GoLiteralValue o,
@NotNull List<GoFieldDeclaration> fields) {
List<GoElement> vals = o.getElementList();
for (int elemId = 0; elemId < vals.size(); elemId++) {
ProgressManager.checkCanceled();
GoElement element = vals.get(elemId);
if (element.getKey() == null && elemId < fields.size()) {
String structFieldName = getFieldName(fields.get(elemId));
LocalQuickFix[] fixes = structFieldName != null ? new LocalQuickFix[]{new GoReplaceWithNamedStructFieldQuickFix(structFieldName)}
: LocalQuickFix.EMPTY_ARRAY;
holder.registerProblem(element, "Unnamed field initialization", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fixes);
}
}
@NotNull
private static List<String> getNames(@NotNull List<GoElement> elements) {
return map(elements, element -> {
GoKey key = element.getKey();
return key != null ? key.getText() : null;
});
}

private static boolean areElementsNamesMatchesDefinitions(@NotNull List<String> elementsNames,
@NotNull List<String> fieldDefinitionsNames) {
return range(0, elementsNames.size()).allMatch(i -> isNullOrEqual(elementsNames.get(i), getByIndex(fieldDefinitionsNames, i)));
}

@Contract("null, _ -> true")
private static boolean isNullOrEqual(@Nullable Object o, @Nullable Object objectToCompare) {
return o == null || Comparing.equal(o, objectToCompare);
}

@Nullable
private static String getFieldName(@NotNull GoFieldDeclaration declaration) {
List<GoFieldDefinition> list = declaration.getFieldDefinitionList();
GoFieldDefinition fieldDefinition = ContainerUtil.getFirstItem(list);
return fieldDefinition != null ? fieldDefinition.getIdentifier().getText() : null;
private static String getByIndex(@NotNull List<String> list, int index) {
return 0 <= index && index < list.size() ? list.get(index) : null;
}

@NotNull
private static List<String> getFieldDefinitionsNames(@NotNull GoStructType type) {
return type.getFieldDeclarationList().stream()
.flatMap(declaration -> getFieldDefinitionsNames(declaration).stream())
.collect(toList());
}

@NotNull
private static List<String> getFieldDefinitionsNames(@NotNull GoFieldDeclaration declaration) {
GoAnonymousFieldDefinition definition = declaration.getAnonymousFieldDefinition();
return definition != null ? list(definition.getName()) : map(declaration.getFieldDefinitionList(), GoNamedElement::getName);
}

@Override
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel("Report for local type definitions as well", this, "reportLocalStructs");
}

private static class GoReplaceWithNamedStructFieldQuickFix extends LocalQuickFixBase {
private String myStructField;

public GoReplaceWithNamedStructFieldQuickFix(@NotNull String structField) {
public GoReplaceWithNamedStructFieldQuickFix() {
super(REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME);
myStructField = structField;
}

@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement startElement = descriptor.getStartElement();
if (startElement instanceof GoElement) {
startElement.replace(GoElementFactory.createLiteralValueElement(project, myStructField, startElement.getText()));
}
GoLiteralValue literal = ObjectUtils.tryCast(descriptor.getStartElement(), GoLiteralValue.class);
GoStructType structType = getStructType(literal);
List<GoElement> elements = structType != null ? literal.getElementList() : emptyList();
List<String> fieldDefinitionNames = structType != null ? getFieldDefinitionsNames(structType) : emptyList();
if (!areElementsNamesMatchesDefinitions(getNames(elements), fieldDefinitionNames)) return;
replaceElementsByNamed(elements, fieldDefinitionNames, project);
}
}

private static void replaceElementsByNamed(@NotNull List<GoElement> elements,
@NotNull List<String> fieldDefinitionNames,
@NotNull Project project) {
for (int i = 0; i < elements.size(); i++) {
GoElement element = elements.get(i);
String fieldDefinitionName = getByIndex(fieldDefinitionNames, i);
GoValue value = fieldDefinitionName != null && element.getKey() == null ? element.getValue() : null;
if (value == null) continue;

GoElement namedElement = GoElementFactory.createLiteralValueElement(project, fieldDefinitionName, value.getText());
element.replace(namedElement);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/com/goide/psi/impl/GoElementFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ public static GoType createType(@NotNull Project project, @NotNull String text)
return PsiTreeUtil.findChildOfType(file, GoType.class);
}

public static PsiElement createLiteralValueElement(@NotNull Project project, @NotNull String key, @NotNull String value) {
public static GoElement createLiteralValueElement(@NotNull Project project, @NotNull String key, @NotNull String value) {
GoFile file = createFileFromText(project, "package a; var _ = struct { a string } { " + key + ": " + value + " }");
return PsiTreeUtil.findChildOfType(file, GoElement.class);
}
Expand Down
9 changes: 0 additions & 9 deletions testData/inspections/go-struct-initialization/quickFix.go

This file was deleted.

11 changes: 11 additions & 0 deletions testData/inspections/struct-initialization/anonField-after.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package foo

type S struct {
X string
string
Y int
}
func main() {
var s S
s = S{X: "X", string: "a", Y: 1}
}
11 changes: 11 additions & 0 deletions testData/inspections/struct-initialization/anonField.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package foo

type S struct {
X string
string
Y int
}
func main() {
var s S
s = S<weak_warning descr="Unnamed field initializations">{<caret>"X", "a", Y: 1}</weak_warning>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package foo

type S struct {
X, Y int
}
func main() {
s := S{X: 1, Y: 0, 2}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package foo

type S struct {
X, Y int
}
func main() {
s := S<weak_warning descr="Unnamed field initializations">{<caret>1, 0, 2}</weak_warning>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package foo

type S struct {
X, Y int
}
func main() {
s := S{<caret>1, 0, X: 2}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package foo

func main() {
type B struct {
Y int
}

type S struct {
X int
B
Z int
}

s := S{X: 1, B: B{Y: 2}, Z: 3}
print(s.B.Y)
}
16 changes: 16 additions & 0 deletions testData/inspections/struct-initialization/innerAnonStruct.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package foo

func main() {
type B struct {
Y int
}

type S struct {
X int
B
Z int
}

s := S<weak_warning descr="Unnamed field initializations">{1<caret>, B{Y: 2}, 3}</weak_warning>
print(s.B.Y)
}
16 changes: 16 additions & 0 deletions testData/inspections/struct-initialization/innerStruct-after.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package foo

func main() {
type B struct {
Y int
}

type S struct {
X int
b B
Z int
}

s := S{X: 1, b: B{Y: 2}}
print(s.b.Y)
}
16 changes: 16 additions & 0 deletions testData/inspections/struct-initialization/innerStruct.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package foo

func main() {
type B struct {
Y int
}

type S struct {
X int
b B
Z int
}

s := S<weak_warning descr="Unnamed field initializations">{1<caret>, B{Y: 2}}</weak_warning>
print(s.b.Y)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package foo

type S struct {
X, Y int
}
func main() {
var s S
s = S<weak_warning descr="Unnamed field initializations">{0, 0}</weak_warning>
s = S<weak_warning descr="Unnamed field initializations">{X: 0, 0}</weak_warning>
s = S<weak_warning descr="Unnamed field initializations">{0, Y: 0}</weak_warning>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package foo

type S struct {
X, Y int
}
func main() {
var s S
s = S{X: 0, Y: 0}
}
9 changes: 9 additions & 0 deletions testData/inspections/struct-initialization/onelineQuickfix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package foo

type S struct {
X, Y int
}
func main() {
var s S
s = S<weak_warning descr="Unnamed field initializations">{<caret>0, 0}</weak_warning>
}
9 changes: 9 additions & 0 deletions testData/inspections/struct-initialization/quickFix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package foo

import "io"

func _() {
_ = io.LimitedReader<weak_warning descr="Unnamed field initializations">{
<caret>nil,
}</weak_warning>
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,15 @@ func _() {
}

// bad defs
_ = io.LimitedReader{
<weak_warning descr="Unnamed field initialization">nil</weak_warning>,
}
_ = os.LinkError{
<weak_warning descr="Unnamed field initialization">"string"</weak_warning>,
<weak_warning descr="Unnamed field initialization">"string"</weak_warning>,
<weak_warning descr="Unnamed field initialization">"string"</weak_warning>,
<weak_warning descr="Unnamed field initialization">nil</weak_warning>,
}
_ = io.LimitedReader<weak_warning descr="Unnamed field initializations">{
nil,
}</weak_warning>
_ = os.LinkError<weak_warning descr="Unnamed field initializations">{
"string",
"string",
"string",
nil,
}</weak_warning>
}

type assertion struct {
Expand Down
Loading

0 comments on commit c8af522

Please sign in to comment.