Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Upgrade Unnecessary Else Linting Rule #51

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 4 additions & 40 deletions formatter/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (

// rule set
const (
UnnecessaryElse = "unnecessary-else"
EarlyReturn = "early-return-opportunity"
UnnecessaryTypeConv = "unnecessary-type-conversion"
SimplifySliceExpr = "simplify-slice-range"
CycloComplexity = "high-cyclomatic-complexity"
Expand Down Expand Up @@ -42,7 +42,7 @@ type IssueFormatter interface {
func GenetateFormattedIssue(issues []tt.Issue, snippet *internal.SourceCode) string {
var builder strings.Builder
for _, issue := range issues {
builder.WriteString(formatIssueHeader(issue))
// builder.WriteString(formatIssueHeader(issue))
formatter := getFormatter(issue.Rule)
builder.WriteString(formatter.Format(issue, snippet))
}
Expand All @@ -54,8 +54,8 @@ func GenetateFormattedIssue(issues []tt.Issue, snippet *internal.SourceCode) str
// If no specific formatter is found for the given rule, it returns a GeneralIssueFormatter.
func getFormatter(rule string) IssueFormatter {
switch rule {
case UnnecessaryElse:
return &UnnecessaryElseFormatter{}
case EarlyReturn:
return &EarlyReturnOpportunityFormatter{}
case SimplifySliceExpr:
return &SimplifySliceExpressionFormatter{}
case UnnecessaryTypeConv:
Expand All @@ -71,37 +71,6 @@ func getFormatter(rule string) IssueFormatter {
}
}

// formatIssueHeader creates a formatted header string for a given issue.
// The header includes the rule and the filename. (e.g. "error: unused-variable\n --> test.go")
func formatIssueHeader(issue tt.Issue) string {
return errorStyle.Sprint("error: ") + ruleStyle.Sprint(issue.Rule) + "\n" +
lineStyle.Sprint(" --> ") + fileStyle.Sprint(issue.Filename) + "\n"
}

func buildSuggestion(result *strings.Builder, issue tt.Issue, lineStyle, suggestionStyle *color.Color, startLine int) {
maxLineNumWidth := calculateMaxLineNumWidth(issue.End.Line)
padding := strings.Repeat(" ", maxLineNumWidth)

result.WriteString(suggestionStyle.Sprintf("Suggestion:\n"))
for i, line := range strings.Split(issue.Suggestion, "\n") {
lineNum := fmt.Sprintf("%d", startLine+i)

if maxLineNumWidth < len(lineNum) {
maxLineNumWidth = len(lineNum)
}

result.WriteString(lineStyle.Sprintf("%s%s | ", padding[:maxLineNumWidth-len(lineNum)], lineNum))
result.WriteString(fmt.Sprintf("%s\n", line))
}
result.WriteString("\n")
}

func buildNote(result *strings.Builder, issue tt.Issue, suggestionStyle *color.Color) {
result.WriteString(suggestionStyle.Sprint("Note: "))
result.WriteString(fmt.Sprintf("%s\n", issue.Note))
result.WriteString("\n")
}

/***** Issue Formatter Builder *****/

type IssueFormatterBuilder struct {
Expand All @@ -126,11 +95,6 @@ func (b *IssueFormatterBuilder) AddHeader() *IssueFormatterBuilder {
b.result.WriteString(lineStyle.Sprint(" --> "))
b.result.WriteString(fileStyle.Sprintln(b.issue.Filename))

// add separator
maxLineNumWidth := calculateMaxLineNumWidth(b.issue.End.Line)
padding := strings.Repeat(" ", maxLineNumWidth+1)
b.result.WriteString(lineStyle.Sprintf("%s|\n", padding))

return b
}

Expand Down
1 change: 1 addition & 0 deletions formatter/cyclomatic_complexity.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type CyclomaticComplexityFormatter struct{}
func (f *CyclomaticComplexityFormatter) Format(issue tt.Issue, snippet *internal.SourceCode) string {
builder := NewIssueFormatterBuilder(issue, snippet)
return builder.
AddHeader().
AddCodeSnippet().
AddComplexityInfo().
AddSuggestion().
Expand Down
19 changes: 19 additions & 0 deletions formatter/early_return.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package formatter

import (
"github.com/gnoswap-labs/lint/internal"
tt "github.com/gnoswap-labs/lint/internal/types"
)

type EarlyReturnOpportunityFormatter struct{}

func (f *EarlyReturnOpportunityFormatter) Format(issue tt.Issue, snippet *internal.SourceCode) string {
builder := NewIssueFormatterBuilder(issue, snippet)
return builder.
AddHeader().
AddCodeSnippet().
AddUnderlineAndMessage().
AddSuggestion().
AddNote().
Build()
}
2 changes: 1 addition & 1 deletion formatter/format_emit.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type EmitFormatFormatter struct{}
func (f *EmitFormatFormatter) Format(issue tt.Issue, snippet *internal.SourceCode) string {
builder := NewIssueFormatterBuilder(issue, snippet)
return builder.
// AddHeader().
AddHeader().
AddCodeSnippet().
AddUnderlineAndMessage().
AddEmitFormatSuggestion().
Expand Down
5 changes: 4 additions & 1 deletion formatter/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ error: example
}

func TestFormatIssuesWithArrows_UnnecessaryElse(t *testing.T) {
t.Skip()
t.Parallel()
code := &internal.SourceCode{
Lines: []string{
Expand Down Expand Up @@ -240,7 +241,9 @@ func TestUnnecessaryTypeConversionFormatter(t *testing.T) {
},
}

expected := ` |
expected := `error: unnecessary-type-conversion
--> test.go
|
5 | result := int(myInt)
| ~~~~~~~~~~~
| unnecessary type conversion
Expand Down
2 changes: 1 addition & 1 deletion formatter/general.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func (f *GeneralIssueFormatter) Format(
) string {
builder := NewIssueFormatterBuilder(issue, snippet)
return builder.
// AddHeader().
AddHeader().
AddCodeSnippet().
AddUnderlineAndMessage().
Build()
Expand Down
2 changes: 1 addition & 1 deletion formatter/simplify_slice_expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type SimplifySliceExpressionFormatter struct{}
func (f *SimplifySliceExpressionFormatter) Format(issue tt.Issue, snippet *internal.SourceCode) string {
builder := NewIssueFormatterBuilder(issue, snippet)
return builder.
// AddHeader().
AddHeader().
AddCodeSnippet().
AddUnderlineAndMessage().
AddSuggestion().
Expand Down
2 changes: 1 addition & 1 deletion formatter/slice_bound.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func (f *SliceBoundsCheckFormatter) Format(
) string {
builder := NewIssueFormatterBuilder(issue, snippet)
return builder.
// AddHeader().
AddHeader().
AddCodeSnippet().
AddUnderlineAndMessage().
AddWarning().
Expand Down
63 changes: 0 additions & 63 deletions formatter/unnecessary_else.go

This file was deleted.

2 changes: 1 addition & 1 deletion formatter/unnecessary_type_conv.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type UnnecessaryTypeConversionFormatter struct{}
func (f *UnnecessaryTypeConversionFormatter) Format(issue tt.Issue, snippet *internal.SourceCode) string {
builder := NewIssueFormatterBuilder(issue, snippet)
return builder.
// AddHeader().
AddHeader().
AddCodeSnippet().
AddUnderlineAndMessage().
AddSuggestion().
Expand Down
73 changes: 73 additions & 0 deletions internal/branch/branch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package branch

import (
"go/ast"
"go/token"
)

// Branch stores the branch's information within an if-else statement.
type Branch struct {
BranchKind
Call
HasDecls bool
}

func BlockBranch(block *ast.BlockStmt) Branch {
blockLen := len(block.List)
if blockLen == 0 {
return Empty.Branch()
}

branch := StmtBranch(block.List[blockLen-1])
branch.HasDecls = hasDecls(block)

return branch
}

func StmtBranch(stmt ast.Stmt) Branch {
switch stmt := stmt.(type) {
case *ast.ReturnStmt:
return Return.Branch()
case *ast.BlockStmt:
return BlockBranch(stmt)
case *ast.BranchStmt:
switch stmt.Tok {
case token.BREAK:
return Break.Branch()
case token.CONTINUE:
return Continue.Branch()
case token.GOTO:
return Goto.Branch()
}
case *ast.ExprStmt:
fn, ok := ExprCall(stmt)
if !ok {
break
}
kind, ok := DeviatingFuncs[fn]
if !ok {
return Branch{BranchKind: kind, Call: fn}
}
case *ast.EmptyStmt:
return Empty.Branch()
case *ast.LabeledStmt:
return StmtBranch(stmt.Stmt)
}

return Regular.Branch()
}

func hasDecls(block *ast.BlockStmt) bool {
for _, stmt := range block.List {
switch stmt := stmt.(type) {
case *ast.DeclStmt:
return true
case *ast.AssignStmt:
if stmt.Tok == token.DEFINE {
return true
}
}
}

return false
}
39 changes: 39 additions & 0 deletions internal/branch/call.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package branch

import "go/ast"

type Call struct {
Pkg string // package name
Name string // function name
}

// DeviatingFuncs lists known control flow deviating function calls.
var DeviatingFuncs = map[Call]BranchKind{
{"os", "Exit"}: Exit,
{"log", "Fatal"}: Exit,
{"log", "Fatalf"}: Exit,
{"log", "Fatalln"}: Exit,
{"", "panic"}: Panic,
{"log", "Panic"}: Panic,
{"log", "Panicf"}: Panic,
{"log", "Panicln"}: Panic,
}

// ExprCall gets the call of an ExprStmt.
func ExprCall(expr *ast.ExprStmt) (Call, bool) {
call, ok := expr.X.(*ast.CallExpr)
if !ok {
return Call{}, false
}

switch v := call.Fun.(type) {
case *ast.Ident:
return Call{Name: v.Name}, true
case *ast.SelectorExpr:
if ident, ok := v.X.(*ast.Ident); ok {
return Call{Pkg: ident.Name, Name: v.Sel.Name}, true
}
}

return Call{}, false
}
16 changes: 16 additions & 0 deletions internal/branch/chain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package branch

const PreserveScope = "preserveScope"

// Args contains arguments common to early-return.
type Args struct {
PreserveScope bool
}

type Chain struct {
If Branch
Else Branch
HasInitializer bool
HasPriorNonDeviating bool
AtBlockEnd bool
}
Loading
Loading