Debian Codegraph @

gopls/internal/golang/completion/keywords.go

raw symbols SCIP
1 // Copyright 2020 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
10 "golang.org/x/tools/gopls/internal/protocol"
11 "golang.org/x/tools/internal/astutil"
12 )
13
14 const (
15 BREAK = "break"
16 CASE = "case"
17 CHAN = "chan"
18 CONST = "const"
19 CONTINUE = "continue"
20 DEFAULT = "default"
21 DEFER = "defer"
22 ELSE = "else"
23 FALLTHROUGH = "fallthrough"
24 FOR = "for"
25 FUNC = "func"
26 GO = "go"
27 GOTO = "goto"
28 IF = "if"
29 IMPORT = "import"
30 INTERFACE = "interface"
31 MAP = "map"
32 PACKAGE = "package"
33 RANGE = "range"
34 RETURN = "return"
35 SELECT = "select"
36 STRUCT = "struct"
37 SWITCH = "switch"
38 TYPE = "type"
39 VAR = "var"
40 )
41
42 // addKeywordCompletions offers keyword candidates appropriate at the position.
43 func (c *completer) addKeywordCompletions() {
44 seen := make(map[string]bool)
45
46 if c.wantTypeName() && c.inference.objType == nil {
47 // If we want a type name but don't have an expected obj type,
48 // include "interface", "struct", "func", "chan", and "map".
49
50 // "interface" and "struct" are more common declaring named types.
51 // Give them a higher score if we are in a type declaration.
52 structIntf, funcChanMap := stdScore, highScore
53 if len(c.path) > 1 {
54 if _, namedDecl := c.path[1].(*ast.TypeSpec); namedDecl {
55 structIntf, funcChanMap = highScore, stdScore
56 }
57 }
58
59 c.addKeywordItems(seen, structIntf, STRUCT, INTERFACE)
60 c.addKeywordItems(seen, funcChanMap, FUNC, CHAN, MAP)
61 }
62
63 // If we are at the file scope, only offer decl keywords. We don't
64 // get *ast.Idents at the file scope because non-keyword identifiers
65 // turn into *ast.BadDecl, not *ast.Ident.
66 if len(c.path) == 1 || is[*ast.File](c.path[1]) {
67 c.addKeywordItems(seen, stdScore, TYPE, CONST, VAR, FUNC, IMPORT)
68 return
69 } else if _, ok := c.path[0].(*ast.Ident); !ok {
70 // Otherwise only offer keywords if the client is completing an identifier.
71 return
72 }
73
74 if len(c.path) > 2 {
75 // Offer "range" if we are in ast.ForStmt.Init. This is what the
76 // AST looks like before "range" is typed, e.g. "for i := r<>".
77 if loop, ok := c.path[2].(*ast.ForStmt); ok && loop.Init != nil && astutil.NodeContainsPos(loop.Init, c.pos) {
78 c.addKeywordItems(seen, stdScore, RANGE)
79 }
80 }
81
82 // Only suggest keywords if we are beginning a statement.
83 switch n := c.path[1].(type) {
84 case *ast.BlockStmt, *ast.ExprStmt:
85 // OK - our ident must be at beginning of statement.
86 case *ast.CommClause:
87 // Make sure we aren't in the Comm statement.
88 if !n.Colon.IsValid() || c.pos <= n.Colon {
89 return
90 }
91 case *ast.CaseClause:
92 // Make sure we aren't in the case List.
93 if !n.Colon.IsValid() || c.pos <= n.Colon {
94 return
95 }
96 default:
97 return
98 }
99
100 // Filter out keywords depending on scope
101 // Skip the first one because we want to look at the enclosing scopes
102 path := c.path[1:]
103 for i, n := range path {
104 switch node := n.(type) {
105 case *ast.CaseClause:
106 // only recommend "fallthrough" and "break" within the bodies of a case clause
107 if c.pos > node.Colon {
108 c.addKeywordItems(seen, stdScore, BREAK)
109 // "fallthrough" is only valid in switch statements.
110 // A case clause is always nested within a block statement in a switch statement,
111 // that block statement is nested within either a TypeSwitchStmt or a SwitchStmt.
112 if i+2 >= len(path) {
113 continue
114 }
115 if _, ok := path[i+2].(*ast.SwitchStmt); ok {
116 c.addKeywordItems(seen, stdScore, FALLTHROUGH)
117 }
118 }
119 case *ast.CommClause:
120 if c.pos > node.Colon {
121 c.addKeywordItems(seen, stdScore, BREAK)
122 }
123 case *ast.TypeSwitchStmt, *ast.SelectStmt, *ast.SwitchStmt:
124 // if there is no default case yet, it's highly likely to add a default in switch.
125 // we don't offer 'default' anymore if user has used it already in current switch.
126 if !hasDefaultClause(node) {
127 c.addKeywordItems(seen, highScore, CASE, DEFAULT)
128 }
129 case *ast.ForStmt, *ast.RangeStmt:
130 c.addKeywordItems(seen, stdScore, BREAK, CONTINUE)
131 // This is a bit weak, functions allow for many keywords
132 case *ast.FuncDecl:
133 if node.Body != nil && c.pos > node.Body.Lbrace {
134 // requireReturnObj checks whether user must provide some objects after return.
135 requireReturnObj := func(sig *ast.FuncType) bool {
136 results := sig.Results
137 if results == nil || results.List == nil {
138 return false // nothing to return
139 }
140 // If any result is named, allow a bare return.
141 for _, r := range results.List {
142 for _, name := range r.Names {
143 if name.Name != "_" {
144 return false
145 }
146 }
147 }
148 return true
149 }
150 ret := RETURN
151 if requireReturnObj(node.Type) {
152 // as user must return something, we offer a space after return.
153 // function literal inside a function will be affected by outer function,
154 // but 'go fmt' will help to remove the ending space.
155 // the benefit is greater than introducing an unnecessary space.
156 ret += " "
157 }
158
159 c.addKeywordItems(seen, stdScore, DEFER, ret, FOR, GO, SWITCH, SELECT, IF, ELSE, VAR, CONST, GOTO, TYPE)
160 }
161 }
162 }
163 }
164
165 // hasDefaultClause reports whether the given node contains a direct default case.
166 // It does not traverse child nodes to look for nested default clauses,
167 // and returns false if the node is not a switch statement.
168 func hasDefaultClause(node ast.Node) bool {
169 var cases []ast.Stmt
170 switch node := node.(type) {
171 case *ast.TypeSwitchStmt:
172 cases = node.Body.List
173 case *ast.SelectStmt:
174 cases = node.Body.List
175 case *ast.SwitchStmt:
176 cases = node.Body.List
177 }
178 for _, c := range cases {
179 if clause, ok := c.(*ast.CaseClause); ok &&
180 clause.List == nil { // default case
181 return true
182 }
183 }
184 return false
185 }
186
187 // addKeywordItems dedupes and adds completion items for the specified
188 // keywords with the specified score.
189 func (c *completer) addKeywordItems(seen map[string]bool, score float64, kws ...string) {
190 for _, kw := range kws {
191 if seen[kw] {
192 continue
193 }
194 seen[kw] = true
195
196 if matchScore := c.matcher.Score(kw); matchScore > 0 {
197 c.items = append(c.items, CompletionItem{
198 Label: kw,
199 Kind: protocol.KeywordCompletion,
200 InsertText: kw,
201 Score: score * float64(matchScore),
202 })
203 }
204 }
205 }