| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package completion |
| 6 |
|
| 7 |
import ( |
| 8 |
"go/ast" |
| 9 |
"go/token" |
| 10 |
"math" |
| 11 |
"slices" |
| 12 |
) |
| 13 |
|
| 14 |
type labelType int |
| 15 |
|
| 16 |
const ( |
| 17 |
labelNone labelType = iota |
| 18 |
labelBreak |
| 19 |
labelContinue |
| 20 |
labelGoto |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
func (c *completer) wantLabelCompletion() labelType { |
| 26 |
if _, ok := c.path[0].(*ast.Ident); ok && len(c.path) > 1 { |
| 27 |
|
| 28 |
|
| 29 |
return takesLabel(c.path[1]) |
| 30 |
} |
| 31 |
|
| 32 |
return labelNone |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
func takesLabel(n ast.Node) labelType { |
| 38 |
if bs, ok := n.(*ast.BranchStmt); ok { |
| 39 |
switch bs.Tok { |
| 40 |
case token.BREAK: |
| 41 |
return labelBreak |
| 42 |
case token.CONTINUE: |
| 43 |
return labelContinue |
| 44 |
case token.GOTO: |
| 45 |
return labelGoto |
| 46 |
} |
| 47 |
} |
| 48 |
return labelNone |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
func (c *completer) labels(lt labelType) { |
| 54 |
if c.enclosingFunc == nil { |
| 55 |
return |
| 56 |
} |
| 57 |
|
| 58 |
addLabel := func(score float64, l *ast.LabeledStmt) { |
| 59 |
labelObj := c.pkg.TypesInfo().ObjectOf(l.Label) |
| 60 |
if labelObj != nil { |
| 61 |
c.deepState.enqueue(candidate{obj: labelObj, score: score}) |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
switch lt { |
| 66 |
case labelBreak, labelContinue: |
| 67 |
|
| 68 |
|
| 69 |
for i, p := range c.path { |
| 70 |
switch p := p.(type) { |
| 71 |
case *ast.FuncLit: |
| 72 |
|
| 73 |
return |
| 74 |
case *ast.LabeledStmt: |
| 75 |
switch p.Stmt.(type) { |
| 76 |
case *ast.ForStmt, *ast.RangeStmt: |
| 77 |
|
| 78 |
addLabel(highScore*math.Pow(.99, float64(i)), p) |
| 79 |
case *ast.SwitchStmt, *ast.SelectStmt, *ast.TypeSwitchStmt: |
| 80 |
|
| 81 |
if lt == labelBreak { |
| 82 |
addLabel(highScore*math.Pow(.99, float64(i)), p) |
| 83 |
} |
| 84 |
} |
| 85 |
} |
| 86 |
} |
| 87 |
case labelGoto: |
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
ast.Inspect(c.enclosingFunc.body, func(n ast.Node) bool { |
| 92 |
if n == nil { |
| 93 |
return false |
| 94 |
} |
| 95 |
|
| 96 |
switch n := n.(type) { |
| 97 |
|
| 98 |
|
| 99 |
case *ast.BlockStmt, *ast.CommClause, *ast.CaseClause: |
| 100 |
return slices.Contains(c.path, n) |
| 101 |
case *ast.LabeledStmt: |
| 102 |
addLabel(highScore, n) |
| 103 |
} |
| 104 |
|
| 105 |
return true |
| 106 |
}) |
| 107 |
} |
| 108 |
} |