Debian Codegraph @

gopls/internal/golang/completion/labels.go

raw symbols SCIP
1 // Copyright 2019 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 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 // wantLabelCompletion returns true if we want (only) label
24 // completions at the position.
25 func (c *completer) wantLabelCompletion() labelType {
26 if _, ok := c.path[0].(*ast.Ident); ok && len(c.path) > 1 {
27 // We want a label if we are an *ast.Ident child of a statement
28 // that accepts a label, e.g. "break Lo<>".
29 return takesLabel(c.path[1])
30 }
31
32 return labelNone
33 }
34
35 // takesLabel returns the corresponding labelType if n is a statement
36 // that accepts a label, otherwise labelNone.
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 // labels adds completion items for labels defined in the enclosing
52 // function.
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 // "break" and "continue" only accept labels from enclosing statements.
68
69 for i, p := range c.path {
70 switch p := p.(type) {
71 case *ast.FuncLit:
72 // Labels are function scoped, so don't continue out of functions.
73 return
74 case *ast.LabeledStmt:
75 switch p.Stmt.(type) {
76 case *ast.ForStmt, *ast.RangeStmt:
77 // Loop labels can be used for "break" or "continue".
78 addLabel(highScore*math.Pow(.99, float64(i)), p)
79 case *ast.SwitchStmt, *ast.SelectStmt, *ast.TypeSwitchStmt:
80 // Switch and select labels can be used only for "break".
81 if lt == labelBreak {
82 addLabel(highScore*math.Pow(.99, float64(i)), p)
83 }
84 }
85 }
86 }
87 case labelGoto:
88 // Goto accepts any label in the same function not in a nested
89 // block. It also doesn't take labels that would jump across
90 // variable definitions, but ignore that case for now.
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 // Only search into block-like nodes enclosing our "goto".
98 // This prevents us from finding labels in nested blocks.
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 }