Debian Codegraph @

gopls/internal/golang/invertifcondition.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package golang
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/token"
11 "strings"
12
13 "golang.org/x/tools/go/analysis"
14 "golang.org/x/tools/go/ast/inspector"
15 "golang.org/x/tools/gopls/internal/cache"
16 "golang.org/x/tools/gopls/internal/cache/parsego"
17 "golang.org/x/tools/gopls/internal/util/cursorutil"
18 "golang.org/x/tools/gopls/internal/util/safetoken"
19 )
20
21 // invertIfCondition is a singleFileFixFunc that inverts an if/else statement
22 func invertIfCondition(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
23 var (
24 fset = pkg.FileSet()
25 src = pgf.Src
26 )
27
28 ifStatement, _, err := canInvertIfCondition(pgf.Cursor(), start, end)
29 if err != nil {
30 return nil, nil, err
31 }
32
33 var replaceElse analysis.TextEdit
34
35 endsWithReturn, err := endsWithReturn(ifStatement.Else)
36 if err != nil {
37 return nil, nil, err
38 }
39
40 if endsWithReturn {
41 // Replace the whole else part with an empty line and an unindented
42 // version of the original if body
43 sourcePos := safetoken.StartPosition(fset, ifStatement.Pos())
44
45 indent := max(sourcePos.Column-1, 0)
46
47 standaloneBodyText := ifBodyToStandaloneCode(fset, ifStatement.Body, src)
48 replaceElse = analysis.TextEdit{
49 Pos: ifStatement.Body.Rbrace + 1, // 1 == len("}")
50 End: ifStatement.End(),
51 NewText: []byte("\n\n" + strings.Repeat("\t", indent) + standaloneBodyText),
52 }
53 } else {
54 // Replace the else body text with the if body text
55 bodyStart := safetoken.StartPosition(fset, ifStatement.Body.Lbrace)
56 bodyEnd := safetoken.EndPosition(fset, ifStatement.Body.Rbrace+1) // 1 == len("}")
57 bodyText := src[bodyStart.Offset:bodyEnd.Offset]
58 replaceElse = analysis.TextEdit{
59 Pos: ifStatement.Else.Pos(),
60 End: ifStatement.Else.End(),
61 NewText: bodyText,
62 }
63 }
64
65 // Replace the if text with the else text
66 elsePosInSource := safetoken.StartPosition(fset, ifStatement.Else.Pos())
67 elseEndInSource := safetoken.EndPosition(fset, ifStatement.Else.End())
68 elseText := src[elsePosInSource.Offset:elseEndInSource.Offset]
69 replaceBodyWithElse := analysis.TextEdit{
70 Pos: ifStatement.Body.Pos(),
71 End: ifStatement.Body.End(),
72 NewText: elseText,
73 }
74
75 // Replace the if condition with its inverse
76 inverseCondition, err := invertCondition(fset, ifStatement.Cond, src)
77 if err != nil {
78 return nil, nil, err
79 }
80 replaceConditionWithInverse := analysis.TextEdit{
81 Pos: ifStatement.Cond.Pos(),
82 End: ifStatement.Cond.End(),
83 NewText: inverseCondition,
84 }
85
86 // Return a SuggestedFix with just that TextEdit in there
87 return fset, &analysis.SuggestedFix{
88 TextEdits: []analysis.TextEdit{
89 replaceConditionWithInverse,
90 replaceBodyWithElse,
91 replaceElse,
92 },
93 }, nil
94 }
95
96 func endsWithReturn(elseBranch ast.Stmt) (bool, error) {
97 elseBlock, isBlockStatement := elseBranch.(*ast.BlockStmt)
98 if !isBlockStatement {
99 return false, fmt.Errorf("unable to figure out whether this ends with return: %T", elseBranch)
100 }
101
102 if len(elseBlock.List) == 0 {
103 // Empty blocks don't end in returns
104 return false, nil
105 }
106
107 lastStatement := elseBlock.List[len(elseBlock.List)-1]
108
109 _, lastStatementIsReturn := lastStatement.(*ast.ReturnStmt)
110 return lastStatementIsReturn, nil
111 }
112
113 // Turn { fmt.Println("Hello") } into just fmt.Println("Hello"), with one less
114 // level of indentation.
115 //
116 // The first line of the result will not be indented, but all of the following
117 // lines will.
118 func ifBodyToStandaloneCode(fset *token.FileSet, ifBody *ast.BlockStmt, src []byte) string {
119 // Get the whole body (without the surrounding braces) as a string
120 bodyStart := safetoken.StartPosition(fset, ifBody.Lbrace+1) // 1 == len("}")
121 bodyEnd := safetoken.EndPosition(fset, ifBody.Rbrace)
122 bodyWithoutBraces := string(src[bodyStart.Offset:bodyEnd.Offset])
123 bodyWithoutBraces = strings.TrimSpace(bodyWithoutBraces)
124
125 // Unindent
126 bodyWithoutBraces = strings.ReplaceAll(bodyWithoutBraces, "\n\t", "\n")
127
128 return bodyWithoutBraces
129 }
130
131 func invertCondition(fset *token.FileSet, cond ast.Expr, src []byte) ([]byte, error) {
132 condStart := safetoken.StartPosition(fset, cond.Pos())
133 condEnd := safetoken.EndPosition(fset, cond.End())
134 oldText := string(src[condStart.Offset:condEnd.Offset])
135
136 switch expr := cond.(type) {
137 case *ast.Ident, *ast.ParenExpr, *ast.CallExpr, *ast.StarExpr, *ast.IndexExpr, *ast.IndexListExpr, *ast.SelectorExpr:
138 newText := "!" + oldText
139 if oldText == "true" {
140 newText = "false"
141 } else if oldText == "false" {
142 newText = "true"
143 }
144
145 return []byte(newText), nil
146
147 case *ast.UnaryExpr:
148 if expr.Op != token.NOT {
149 // This should never happen
150 return dumbInvert(fset, cond, src), nil
151 }
152
153 inverse := expr.X
154 if p, isParen := inverse.(*ast.ParenExpr); isParen {
155 // We got !(x), remove the parentheses with the ! so we get just "x"
156 inverse = p.X
157
158 start := safetoken.StartPosition(fset, inverse.Pos())
159 end := safetoken.EndPosition(fset, inverse.End())
160 if start.Line != end.Line {
161 // The expression is multi-line, so we can't remove the parentheses
162 inverse = expr.X
163 }
164 }
165
166 start := safetoken.StartPosition(fset, inverse.Pos())
167 end := safetoken.EndPosition(fset, inverse.End())
168 textWithoutNot := src[start.Offset:end.Offset]
169
170 return textWithoutNot, nil
171
172 case *ast.BinaryExpr:
173 // These inversions are unsound for floating point NaN, but that's ok.
174 negations := map[token.Token]string{
175 token.EQL: "!=",
176 token.LSS: ">=",
177 token.GTR: "<=",
178 token.NEQ: "==",
179 token.LEQ: ">",
180 token.GEQ: "<",
181 }
182
183 negation, negationFound := negations[expr.Op]
184 if !negationFound {
185 return invertAndOr(fset, expr, src)
186 }
187
188 xPosInSource := safetoken.StartPosition(fset, expr.X.Pos())
189 opPosInSource := safetoken.StartPosition(fset, expr.OpPos)
190 yPosInSource := safetoken.StartPosition(fset, expr.Y.Pos())
191
192 textBeforeOp := string(src[xPosInSource.Offset:opPosInSource.Offset])
193
194 oldOpWithTrailingWhitespace := string(src[opPosInSource.Offset:yPosInSource.Offset])
195 newOpWithTrailingWhitespace := negation + oldOpWithTrailingWhitespace[len(expr.Op.String()):]
196
197 textAfterOp := string(src[yPosInSource.Offset:condEnd.Offset])
198
199 return []byte(textBeforeOp + newOpWithTrailingWhitespace + textAfterOp), nil
200 }
201
202 return dumbInvert(fset, cond, src), nil
203 }
204
205 // dumbInvert is a fallback, inverting cond into !(cond).
206 func dumbInvert(fset *token.FileSet, expr ast.Expr, src []byte) []byte {
207 start := safetoken.StartPosition(fset, expr.Pos())
208 end := safetoken.EndPosition(fset, expr.End())
209 text := string(src[start.Offset:end.Offset])
210 return []byte("!(" + text + ")")
211 }
212
213 func invertAndOr(fset *token.FileSet, expr *ast.BinaryExpr, src []byte) ([]byte, error) {
214 if expr.Op != token.LAND && expr.Op != token.LOR {
215 // Neither AND nor OR, don't know how to invert this
216 return dumbInvert(fset, expr, src), nil
217 }
218
219 oppositeOp := "&&"
220 if expr.Op == token.LAND {
221 oppositeOp = "||"
222 }
223
224 xEndInSource := safetoken.EndPosition(fset, expr.X.End())
225 opPosInSource := safetoken.StartPosition(fset, expr.OpPos)
226 whitespaceAfterBefore := src[xEndInSource.Offset:opPosInSource.Offset]
227
228 invertedBefore, err := invertCondition(fset, expr.X, src)
229 if err != nil {
230 return nil, err
231 }
232
233 invertedAfter, err := invertCondition(fset, expr.Y, src)
234 if err != nil {
235 return nil, err
236 }
237
238 yPosInSource := safetoken.StartPosition(fset, expr.Y.Pos())
239
240 oldOpWithTrailingWhitespace := string(src[opPosInSource.Offset:yPosInSource.Offset])
241 newOpWithTrailingWhitespace := oppositeOp + oldOpWithTrailingWhitespace[len(expr.Op.String()):]
242
243 return []byte(string(invertedBefore) + string(whitespaceAfterBefore) + newOpWithTrailingWhitespace + string(invertedAfter)), nil
244 }
245
246 // canInvertIfCondition reports whether we can do invert-if-condition on the
247 // code in the given range.
248 func canInvertIfCondition(curFile inspector.Cursor, start, end token.Pos) (*ast.IfStmt, bool, error) {
249 curIf, _ := curFile.FindByPos(start, end)
250 stmt, _ := cursorutil.FirstEnclosing[*ast.IfStmt](curIf)
251 if stmt == nil {
252 return nil, false, fmt.Errorf("not an if statement")
253 }
254 if stmt.Else == nil {
255 // Can't invert conditions without else clauses
256 return nil, false, fmt.Errorf("else clause required")
257 }
258
259 if _, hasElseIf := stmt.Else.(*ast.IfStmt); hasElseIf {
260 // Can't invert conditions with else-if clauses, unclear what that
261 // would look like
262 return nil, false, fmt.Errorf("else-if not supported")
263 }
264
265 return stmt, true, nil
266 }