Debian Codegraph @

gopls/internal/cache/parsego/file.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 parsego
6
7 import (
8 "go/ast"
9 "go/parser"
10 "go/scanner"
11 "go/token"
12 "sync"
13 "unicode"
14
15 "golang.org/x/tools/go/ast/inspector"
16 "golang.org/x/tools/gopls/internal/protocol"
17 "golang.org/x/tools/gopls/internal/util/bug"
18 "golang.org/x/tools/gopls/internal/util/safetoken"
19 )
20
21 // A File contains the results of parsing a Go file.
22 type File struct {
23 URI protocol.DocumentURI
24 Mode parser.Mode
25
26 // File is the file resulting from parsing. It is always non-nil.
27 //
28 // Clients must not access the AST's legacy ast.Object-related
29 // fields without first ensuring that [File.Resolve] was
30 // already called.
31 File *ast.File
32 Tok *token.File
33 // Source code used to build the AST. It may be different from the
34 // actual content of the file if we have fixed the AST.
35 Src []byte
36
37 cursor inspector.Cursor // cursor of *ast.File, sans sibling files
38 cursorOnce sync.Once
39
40 // fixedSrc and fixedAST report on "fixing" that occurred during parsing of
41 // this file.
42 //
43 // fixedSrc means Src holds file content that was modified to improve parsing.
44 // fixedAST means File was modified after parsing, so AST positions may not
45 // reflect the content of Src.
46 //
47 // TODO(rfindley): there are many places where we haphazardly use the Src or
48 // positions without checking these fields. Audit these places and guard
49 // accordingly. After doing so, we may find that we don't need to
50 // differentiate fixedSrc and fixedAST.
51 fixedSrc bool
52 fixedAST bool
53 Mapper *protocol.Mapper // may map fixed Src, not file content
54 ParseErr scanner.ErrorList
55
56 // resolveOnce guards the lazy ast.Object resolution. See [File.Resolve].
57 resolveOnce sync.Once
58 }
59
60 func (pgf *File) String() string { return string(pgf.URI) }
61
62 // Cursor returns a cursor for pgf.File, for fast and convenient navigation.
63 func (pgf *File) Cursor() inspector.Cursor {
64 pgf.cursorOnce.Do(func() {
65 inspect := inspector.New([]*ast.File{pgf.File})
66 pgf.cursor, _ = inspect.Root().FirstChild()
67 _ = pgf.cursor.Node().(*ast.File)
68 })
69 return pgf.cursor
70 }
71
72 // Fixed reports whether p was "Fixed", meaning that its source or positions
73 // may not correlate with the original file.
74 func (pgf *File) Fixed() bool {
75 return pgf.fixedSrc || pgf.fixedAST
76 }
77
78 // -- go/token domain convenience helpers --
79
80 // PositionPos returns the token.Pos of protocol position p within the file.
81 func (pgf *File) PositionPos(p protocol.Position) (token.Pos, error) {
82 offset, err := pgf.Mapper.PositionOffset(p)
83 if err != nil {
84 return token.NoPos, err
85 }
86 return safetoken.Pos(pgf.Tok, offset)
87 }
88
89 // PosPosition returns a protocol Position for the token.Pos in this file.
90 func (pgf *File) PosPosition(pos token.Pos) (protocol.Position, error) {
91 return pgf.Mapper.PosPosition(pgf.Tok, pos)
92 }
93
94 // PosRange returns a protocol Range for the token.Pos interval in this file.
95 func (pgf *File) PosRange(start, end token.Pos) (protocol.Range, error) {
96 return pgf.Mapper.PosRange(pgf.Tok, start, end)
97 }
98
99 // PosLocation returns a protocol Location for the token.Pos interval in this file.
100 func (pgf *File) PosLocation(start, end token.Pos) (protocol.Location, error) {
101 return pgf.Mapper.PosLocation(pgf.Tok, start, end)
102 }
103
104 // PosText returns the source text for the token.Pos interval in this file.
105 func (pgf *File) PosText(start, end token.Pos) ([]byte, error) {
106 return pgf.Mapper.PosText(pgf.Tok, start, end)
107 }
108
109 // NodeRange returns a protocol Range for the ast.Node interval in this file.
110 func (pgf *File) NodeRange(node ast.Node) (protocol.Range, error) {
111 return pgf.Mapper.NodeRange(pgf.Tok, node)
112 }
113
114 // NodeOffsets returns offsets for the ast.Node.
115 func (pgf *File) NodeOffsets(node ast.Node) (start int, end int, _ error) {
116 return safetoken.Offsets(pgf.Tok, node.Pos(), node.End())
117 }
118
119 // NodeLocation returns a protocol Location for the ast.Node interval in this file.
120 func (pgf *File) NodeLocation(node ast.Node) (protocol.Location, error) {
121 return pgf.Mapper.PosLocation(pgf.Tok, node.Pos(), node.End())
122 }
123
124 // NodeText returns the source text for the ast.Node interval in this file.
125 func (pgf *File) NodeText(node ast.Node) ([]byte, error) {
126 return pgf.Mapper.NodeText(pgf.Tok, node)
127 }
128
129 // RangePos parses a protocol Range back into the go/token domain.
130 func (pgf *File) RangePos(r protocol.Range) (token.Pos, token.Pos, error) {
131 start, end, err := pgf.Mapper.RangeOffsets(r)
132 if err != nil {
133 return token.NoPos, token.NoPos, err
134 }
135 return pgf.Tok.Pos(start), pgf.Tok.Pos(end), nil
136 }
137
138 // CheckNode asserts that the Node's positions are valid w.r.t. pgf.Tok.
139 func (pgf *File) CheckNode(node ast.Node) {
140 // Avoid safetoken.Offsets, and put each assertion on its own source line.
141 pgf.CheckPos(node.Pos())
142 pgf.CheckPos(node.End())
143 }
144
145 // CheckPos asserts that the position is valid w.r.t. pgf.Tok.
146 func (pgf *File) CheckPos(pos token.Pos) {
147 if !pos.IsValid() {
148 bug.Report("invalid token.Pos")
149 } else if _, err := safetoken.Offset(pgf.Tok, pos); err != nil {
150 bug.Report("token.Pos out of range")
151 }
152 }
153
154 // Resolve lazily resolves ast.Ident.Objects in the enclosed syntax tree.
155 //
156 // Resolve must be called before accessing any of:
157 // - pgf.File.Scope
158 // - pgf.File.Unresolved
159 // - Ident.Obj, for any Ident in pgf.File
160 func (pgf *File) Resolve() {
161 pgf.resolveOnce.Do(func() {
162 if pgf.File.Scope != nil {
163 return // already resolved by parsing without SkipObjectResolution.
164 }
165 defer func() {
166 // (panic handler duplicated from go/parser)
167 if e := recover(); e != nil {
168 // A bailout indicates the resolution stack has exceeded max depth.
169 if _, ok := e.(bailout); !ok {
170 panic(e)
171 }
172 }
173 }()
174 declErr := func(token.Pos, string) {}
175 resolveFile(pgf.File, pgf.Tok, declErr)
176 })
177 }
178
179 // Indentation returns the string of spaces representing the indentation
180 // of the line containing the specified position.
181 // This can be used to ensure that inserted code maintains consistent indentation
182 // and column alignment.
183 func (pgf *File) Indentation(pos token.Pos) (string, error) {
184 line := safetoken.Line(pgf.Tok, pos)
185 start, end, err := safetoken.Offsets(pgf.Tok, pgf.Tok.LineStart(line), pos)
186 if err != nil {
187 return "", err
188 }
189
190 s := string(pgf.Src[start:end])
191 for i, r := range s {
192 if !unicode.IsSpace(r) {
193 return s[:i], nil // prefix of spaces
194 }
195 }
196 return s, nil
197 }