Debian Codegraph @

gopls/internal/cache/parsego/parse.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 //go:generate go run resolver_gen.go
6
7 // The parsego package defines the [File] type, a wrapper around a go/ast.File
8 // that is useful for answering LSP queries. Notably, it bundles the
9 // *token.File and *protocol.Mapper necessary for token.Pos locations to and
10 // from UTF-16 LSP positions.
11 //
12 // Run `go generate` to update resolver.go from GOROOT.
13 package parsego
14
15 import (
16 "bytes"
17 "context"
18 "fmt"
19 "go/ast"
20 "go/parser"
21 "go/scanner"
22 "go/token"
23 "reflect"
24 "slices"
25
26 "golang.org/x/tools/gopls/internal/label"
27 "golang.org/x/tools/gopls/internal/protocol"
28 "golang.org/x/tools/gopls/internal/util/safetoken"
29 "golang.org/x/tools/internal/astutil"
30 "golang.org/x/tools/internal/diff"
31 "golang.org/x/tools/internal/event"
32 )
33
34 // Common parse modes; these should be reused wherever possible to increase
35 // cache hits.
36 const (
37 // Header specifies that the main package declaration and imports are needed.
38 // This is the mode used when attempting to examine the package graph structure.
39 Header = parser.AllErrors | parser.ParseComments | parser.ImportsOnly | parser.SkipObjectResolution
40
41 // Full specifies the full AST is needed.
42 // This is used for files of direct interest where the entire contents must
43 // be considered.
44 Full = parser.AllErrors | parser.ParseComments | parser.SkipObjectResolution
45 )
46
47 // Parse parses a buffer of Go source, repairing the tree if necessary.
48 //
49 // The provided ctx is used only for logging.
50 func Parse(ctx context.Context, fset *token.FileSet, uri protocol.DocumentURI, src []byte, mode parser.Mode, purgeFuncBodies bool) (res *File, fixes []FixType) {
51 if purgeFuncBodies {
52 src = astutil.PurgeFuncBodies(src)
53 }
54 ctx, done := event.Start(ctx, "cache.ParseGoSrc", label.File.Of(uri.Path()))
55 defer done()
56
57 file, err := parser.ParseFile(fset, uri.Path(), src, mode)
58 var parseErr scanner.ErrorList
59 if err != nil {
60 // We passed a byte slice, so the only possible error is a parse error.
61 parseErr = err.(scanner.ErrorList)
62 }
63 // Inv: file != nil.
64
65 tokenFile := func(file *ast.File) *token.File {
66 return fset.File(file.FileStart)
67 }
68
69 tok := tokenFile(file)
70
71 fixedSrc := false
72 fixedAST := false
73 // If there were parse errors, attempt to fix them up.
74 if parseErr != nil {
75 // Fix any badly parsed parts of the AST.
76 astFixes := fixAST(file, tok, src)
77 fixedAST = len(astFixes) > 0
78 if fixedAST {
79 fixes = append(fixes, astFixes...)
80 }
81
82 for i := range 10 {
83 // Fix certain syntax errors that render the file unparsable.
84 newSrc, srcFix := fixSrc(file, tok, src)
85 if newSrc == nil {
86 break
87 }
88
89 // If we thought there was something to fix 10 times in a row,
90 // it is likely we got stuck in a loop somehow. Log out a diff
91 // of the last changes we made to aid in debugging.
92 if i == 9 {
93 unified := diff.Unified("before", "after", string(src), string(newSrc))
94 event.Log(ctx, fmt.Sprintf("fixSrc loop - last diff:\n%v", unified), label.File.Of(tok.Name()))
95 }
96
97 newFile, newErr := parser.ParseFile(fset, uri.Path(), newSrc, mode)
98 assert(newFile != nil, "ParseFile returned nil") // I/O error can't happen
99
100 // Maintain the original parseError so we don't try formatting the
101 // doctored file.
102 file = newFile
103 src = newSrc
104 tok = tokenFile(file)
105
106 // Only now that we accept the fix do we record the src fix from above.
107 fixes = append(fixes, srcFix)
108 fixedSrc = true
109
110 if newErr == nil {
111 break // nothing to fix
112 }
113
114 // Note that fixedAST is reset after we fix src.
115 astFixes = fixAST(file, tok, src)
116 fixedAST = len(astFixes) > 0
117 if fixedAST {
118 fixes = append(fixes, astFixes...)
119 }
120 }
121 }
122 assert(file != nil, "nil *ast.File")
123
124 return &File{
125 URI: uri,
126 Mode: mode,
127 Src: src,
128 fixedSrc: fixedSrc,
129 fixedAST: fixedAST,
130 File: file,
131 Tok: tok,
132 Mapper: protocol.NewMapper(uri, src),
133 ParseErr: parseErr,
134 }, fixes
135 }
136
137 // fixAST inspects the AST and potentially modifies any *ast.BadStmts so that it can be
138 // type-checked more effectively.
139 //
140 // If fixAST returns true, the resulting AST is considered "fixed", meaning
141 // positions have been mangled, and type checker errors may not make sense.
142 func fixAST(n ast.Node, tok *token.File, src []byte) (fixes []FixType) {
143 var err error
144 ast.PreorderStack(n, nil, func(n ast.Node, stack []ast.Node) bool {
145 var parent ast.Node
146 if len(stack) > 0 {
147 parent = stack[len(stack)-1]
148 }
149
150 switch n := n.(type) {
151 case *ast.BadStmt:
152 if fixDeferOrGoStmt(n, parent, tok, src) {
153 fixes = append(fixes, FixedDeferOrGo)
154 // Recursively fix in our fixed node.
155 moreFixes := fixAST(parent, tok, src)
156 fixes = append(fixes, moreFixes...)
157 } else {
158 err = fmt.Errorf("unable to parse defer or go from *ast.BadStmt: %v", err)
159 }
160 return false
161 case *ast.BadExpr:
162 if fixArrayType(n, parent, tok, src) {
163 fixes = append(fixes, FixedArrayType)
164 // Recursively fix in our fixed node.
165 moreFixes := fixAST(parent, tok, src)
166 fixes = append(fixes, moreFixes...)
167 return false
168 }
169
170 // Fix cases where parser interprets if/for/switch "init"
171 // statement as "cond" expression, e.g.:
172 //
173 // // "i := foo" is init statement, not condition.
174 // for i := foo
175 //
176 if fixInitStmt(n, parent, tok, src) {
177 fixes = append(fixes, FixedInit)
178 }
179 return false
180 case *ast.SelectorExpr:
181 // Fix cases where a keyword prefix results in a phantom "_" selector, e.g.:
182 //
183 // foo.var<> // want to complete to "foo.variance"
184 //
185 if fixPhantomSelector(n, tok, src) {
186 fixes = append(fixes, FixedPhantomSelector)
187 }
188 return true
189
190 case *ast.BlockStmt:
191 switch parent.(type) {
192 case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
193 // Adjust closing curly brace of empty switch/select
194 // statements so we can complete inside them.
195 if fixEmptySwitch(n, tok, src) {
196 fixes = append(fixes, FixedEmptySwitch)
197 }
198 }
199
200 return true
201 default:
202 return true
203 }
204 })
205 return fixes
206 }
207
208 // TODO(rfindley): revert this instrumentation once we're certain the crash in
209 // #59097 is fixed.
210 type FixType int
211
212 const (
213 noFix FixType = iota
214 FixedCurlies
215 FixedDanglingSelector
216 FixedDeferOrGo
217 FixedArrayType
218 FixedInit
219 FixedPhantomSelector
220 FixedEmptySwitch
221 )
222
223 // fixSrc attempts to modify the file's source code to fix certain
224 // syntax errors that leave the rest of the file unparsed.
225 //
226 // fixSrc returns a non-nil result if and only if a fix was applied.
227 func fixSrc(f *ast.File, tf *token.File, src []byte) (newSrc []byte, fix FixType) {
228 ast.PreorderStack(f, nil, func(n ast.Node, stack []ast.Node) bool {
229 if newSrc != nil {
230 return false
231 }
232
233 switch n := n.(type) {
234 case *ast.BlockStmt:
235 parent := stack[len(stack)-1]
236 newSrc = fixMissingCurlies(f, n, parent, tf, src)
237 if newSrc != nil {
238 fix = FixedCurlies
239 }
240 case *ast.SelectorExpr:
241 newSrc = fixDanglingSelector(n, tf, src)
242 if newSrc != nil {
243 fix = FixedDanglingSelector
244 }
245 }
246
247 return newSrc == nil
248 })
249
250 return newSrc, fix
251 }
252
253 // fixMissingCurlies adds in curly braces for block statements that
254 // are missing curly braces. For example:
255 //
256 // if foo
257 //
258 // becomes
259 //
260 // if foo {}
261 func fixMissingCurlies(f *ast.File, b *ast.BlockStmt, parent ast.Node, tok *token.File, src []byte) []byte {
262 // If the "{" is already in the source code, there isn't anything to
263 // fix since we aren't missing curlies.
264 if b.Lbrace.IsValid() {
265 braceOffset, err := safetoken.Offset(tok, b.Lbrace)
266 if err != nil {
267 return nil
268 }
269 if braceOffset < len(src) && src[braceOffset] == '{' {
270 return nil
271 }
272 }
273
274 parentLine := safetoken.Line(tok, parent.Pos())
275
276 if parentLine >= tok.LineCount() {
277 // If we are the last line in the file, no need to fix anything.
278 return nil
279 }
280
281 // Insert curlies at the end of parent's starting line. The parent
282 // is the statement that contains the block, e.g. *ast.IfStmt. The
283 // block's Pos()/End() can't be relied upon because they are based
284 // on the (missing) curly braces. We assume the statement is a
285 // single line for now and try sticking the curly braces at the end.
286 insertPos := tok.LineStart(parentLine+1) - 1
287
288 // Scootch position backwards until it's not in a comment. For example:
289 //
290 // if foo<> // some amazing comment |
291 // someOtherCode()
292 //
293 // insertPos will be located at "|", so we back it out of the comment.
294 didSomething := true
295 for didSomething {
296 didSomething = false
297 for _, c := range f.Comments {
298 if c.Pos() < insertPos && insertPos <= c.End() {
299 insertPos = c.Pos()
300 didSomething = true
301 }
302 }
303 }
304
305 // Bail out if line doesn't end in an ident or ".". This is to avoid
306 // cases like below where we end up making things worse by adding
307 // curlies:
308 //
309 // if foo &&
310 // bar<>
311 switch precedingToken(insertPos, tok, src) {
312 case token.IDENT, token.PERIOD:
313 // ok
314 default:
315 return nil
316 }
317
318 var buf bytes.Buffer
319 buf.Grow(len(src) + 3)
320 offset, err := safetoken.Offset(tok, insertPos)
321 if err != nil {
322 return nil
323 }
324 buf.Write(src[:offset])
325
326 // Detect if we need to insert a semicolon to fix "for" loop situations like:
327 //
328 // for i := foo(); foo<>
329 //
330 // Just adding curlies is not sufficient to make things parse well.
331 if fs, ok := parent.(*ast.ForStmt); ok {
332 if _, ok := fs.Cond.(*ast.BadExpr); !ok {
333 if xs, ok := fs.Post.(*ast.ExprStmt); ok {
334 if _, ok := xs.X.(*ast.BadExpr); ok {
335 buf.WriteByte(';')
336 }
337 }
338 }
339 }
340
341 // Insert "{}" at insertPos.
342 buf.WriteByte('{')
343 buf.WriteByte('}')
344 buf.Write(src[offset:])
345 return buf.Bytes()
346 }
347
348 // fixEmptySwitch moves empty switch/select statements' closing curly
349 // brace down one line. This allows us to properly detect incomplete
350 // "case" and "default" keywords as inside the switch statement. For
351 // example:
352 //
353 // switch {
354 // def<>
355 // }
356 //
357 // gets parsed like:
358 //
359 // switch {
360 // }
361 //
362 // Later we manually pull out the "def" token, but we need to detect
363 // that our "<>" position is inside the switch block. To do that we
364 // move the curly brace so it looks like:
365 //
366 // switch {
367 //
368 // }
369 //
370 // The resulting bool reports whether any fixing occurred.
371 func fixEmptySwitch(body *ast.BlockStmt, tok *token.File, src []byte) bool {
372 // We only care about empty switch statements.
373 if len(body.List) > 0 || !body.Rbrace.IsValid() {
374 return false
375 }
376
377 // If the right brace is actually in the source code at the
378 // specified position, don't mess with it.
379 braceOffset, err := safetoken.Offset(tok, body.Rbrace)
380 if err != nil {
381 return false
382 }
383 if braceOffset < len(src) && src[braceOffset] == '}' {
384 return false
385 }
386
387 braceLine := safetoken.Line(tok, body.Rbrace)
388 if braceLine >= tok.LineCount() {
389 // If we are the last line in the file, no need to fix anything.
390 return false
391 }
392
393 // Move the right brace down one line.
394 body.Rbrace = tok.LineStart(braceLine + 1)
395 return true
396 }
397
398 // fixDanglingSelector inserts a real "_" selector expression in place
399 // of a phantom parser-inserted "_" selector so that the parser will
400 // not consume the following non-identifier token.
401 // For example:
402 //
403 // func _() {
404 // x.<>
405 // }
406 //
407 // var x struct { i int }
408 //
409 // To fix completion at "<>", we insert a real "_" after the "." so the
410 // following declaration of "x" can be parsed and type checked
411 // normally.
412 func fixDanglingSelector(s *ast.SelectorExpr, tf *token.File, src []byte) []byte {
413 if !isPhantomUnderscore(s.Sel, tf, src) {
414 return nil
415 }
416
417 if !s.X.End().IsValid() {
418 return nil
419 }
420
421 insertOffset, err := safetoken.Offset(tf, s.X.End())
422 if err != nil {
423 return nil
424 }
425 // Insert directly after the selector's ".".
426 insertOffset++
427 if src[insertOffset-1] != '.' {
428 return nil
429 }
430
431 return slices.Concat(src[:insertOffset], []byte("_"), src[insertOffset:])
432 }
433
434 // fixPhantomSelector tries to fix selector expressions whose Sel is a
435 // phantom (parser-invented) "_". If the text after the '.' is a
436 // keyword, it updates Sel to a fake ast.Ident of that name. For
437 // example:
438 //
439 // foo.var
440 //
441 // yields a "_" selector instead of "var" since "var" is a keyword.
442 //
443 // TODO(rfindley): should this constitute an ast 'fix'?
444 //
445 // The resulting bool reports whether any fixing occurred.
446 func fixPhantomSelector(sel *ast.SelectorExpr, tf *token.File, src []byte) bool {
447 if !isPhantomUnderscore(sel.Sel, tf, src) {
448 return false
449 }
450
451 // Only consider selectors directly abutting the selector ".". This
452 // avoids false positives in cases like:
453 //
454 // foo. // don't think "var" is our selector
455 // var bar = 123
456 //
457 if sel.Sel.Pos() != sel.X.End()+1 {
458 return false
459 }
460
461 maybeKeyword := readKeyword(sel.Sel.Pos(), tf, src)
462 if maybeKeyword == "" {
463 return false
464 }
465
466 return replaceNode(sel, sel.Sel, &ast.Ident{
467 Name: maybeKeyword,
468 NamePos: sel.Sel.Pos(),
469 })
470 }
471
472 // isPhantomUnderscore reports whether the given ident from a
473 // SelectorExpr.Sel was invented by the parser and is not present in
474 // source text. The parser creates a blank "_" identifier when the
475 // syntax (e.g. a selector) demands one but none is present. The fixer
476 // also inserts them.
477 func isPhantomUnderscore(id *ast.Ident, tok *token.File, src []byte) bool {
478 switch id.Name {
479 case "_": // go1.24 parser
480 offset, err := safetoken.Offset(tok, id.Pos())
481 return err == nil && offset < len(src) && src[offset] != '_'
482 }
483 return false // real
484 }
485
486 // fixInitStmt fixes cases where the parser misinterprets an
487 // if/for/switch "init" statement as the "cond" conditional. In cases
488 // like "if i := 0" the user hasn't typed the semicolon yet so the
489 // parser is looking for the conditional expression. However, "i := 0"
490 // are not valid expressions, so we get a BadExpr.
491 //
492 // The resulting bool reports whether any fixing occurred.
493 func fixInitStmt(bad *ast.BadExpr, parent ast.Node, tok *token.File, src []byte) bool {
494 if !bad.Pos().IsValid() || !bad.End().IsValid() {
495 return false
496 }
497
498 // Try to extract a statement from the BadExpr.
499 start, end, err := safetoken.Offsets(tok, bad.Pos(), bad.End())
500 if err != nil {
501 return false
502 }
503 assert(end <= len(src), "offset overflow") // golang/go#72026
504 stmtBytes := src[start:end]
505 stmt, err := parseStmt(tok, bad.Pos(), stmtBytes)
506 if err != nil {
507 return false
508 }
509
510 // If the parent statement doesn't already have an "init" statement,
511 // move the extracted statement into the "init" field and insert a
512 // dummy expression into the required "cond" field.
513 switch p := parent.(type) {
514 case *ast.IfStmt:
515 if p.Init != nil {
516 return false
517 }
518 p.Init = stmt
519 p.Cond = &ast.Ident{
520 Name: "_",
521 NamePos: stmt.End(),
522 }
523 return true
524 case *ast.ForStmt:
525 if p.Init != nil {
526 return false
527 }
528 p.Init = stmt
529 p.Cond = &ast.Ident{
530 Name: "_",
531 NamePos: stmt.End(),
532 }
533 return true
534 case *ast.SwitchStmt:
535 if p.Init != nil {
536 return false
537 }
538 p.Init = stmt
539 p.Tag = nil
540 return true
541 }
542 return false
543 }
544
545 // readKeyword reads the keyword starting at pos, if any.
546 func readKeyword(pos token.Pos, tok *token.File, src []byte) string {
547 var kwBytes []byte
548 offset, err := safetoken.Offset(tok, pos)
549 if err != nil {
550 return ""
551 }
552 for i := offset; i < len(src); i++ {
553 // Use a simplified identifier check since keywords are always lowercase ASCII.
554 if src[i] < 'a' || src[i] > 'z' {
555 break
556 }
557 kwBytes = append(kwBytes, src[i])
558
559 // Stop search at arbitrarily chosen too-long-for-a-keyword length.
560 if len(kwBytes) > 15 {
561 return ""
562 }
563 }
564
565 if kw := string(kwBytes); token.Lookup(kw).IsKeyword() {
566 return kw
567 }
568
569 return ""
570 }
571
572 // fixArrayType tries to parse an *ast.BadExpr into an *ast.ArrayType.
573 // go/parser often turns lone array types like "[]int" into BadExprs
574 // if it isn't expecting a type.
575 func fixArrayType(bad *ast.BadExpr, parent ast.Node, tok *token.File, src []byte) bool {
576 // Our expected input is a bad expression that looks like "[]someExpr".
577
578 from, to := bad.Pos(), bad.End()
579 fromOffset, toOffset, err := safetoken.Offsets(tok, from, to)
580 if err != nil {
581 return false
582 }
583
584 exprBytes := bytes.TrimSpace(slices.Clone(src[fromOffset:toOffset]))
585
586 // If our expression ends in "]" (e.g. "[]"), add a phantom selector
587 // so we can complete directly after the "[]".
588 if bytes.HasSuffix(exprBytes, []byte("]")) {
589 exprBytes = append(exprBytes, '_')
590 }
591
592 // Add "{}" to turn our ArrayType into a CompositeLit. This is to
593 // handle the case of "[...]int" where we must make it a composite
594 // literal to be parseable.
595 exprBytes = append(exprBytes, '{', '}')
596
597 expr, err := parseExpr(tok, from, exprBytes)
598 if err != nil {
599 return false
600 }
601
602 cl, _ := expr.(*ast.CompositeLit)
603 if cl == nil {
604 return false
605 }
606
607 at, _ := cl.Type.(*ast.ArrayType)
608 if at == nil {
609 return false
610 }
611
612 return replaceNode(parent, bad, at)
613 }
614
615 // precedingToken scans src to find the token preceding pos.
616 func precedingToken(pos token.Pos, tok *token.File, src []byte) token.Token {
617 s := &scanner.Scanner{}
618 s.Init(tok, src, nil, 0)
619
620 var lastTok token.Token
621 for {
622 p, t, _ := s.Scan()
623 if t == token.EOF || p >= pos {
624 break
625 }
626
627 lastTok = t
628 }
629 return lastTok
630 }
631
632 // fixDeferOrGoStmt tries to parse an *ast.BadStmt into a defer or a go statement.
633 //
634 // go/parser packages a statement of the form "defer x." as an *ast.BadStmt because
635 // it does not include a call expression. This means that go/types skips type-checking
636 // this statement entirely, and we can't use the type information when completing.
637 // Here, we try to generate a fake *ast.DeferStmt or *ast.GoStmt to put into the AST,
638 // instead of the *ast.BadStmt.
639 func fixDeferOrGoStmt(bad *ast.BadStmt, parent ast.Node, tok *token.File, src []byte) bool {
640 // Check if we have a bad statement containing either a "go" or "defer".
641 s := &scanner.Scanner{}
642 s.Init(tok, src, nil, 0)
643
644 var (
645 pos token.Pos
646 tkn token.Token
647 )
648 for {
649 if tkn == token.EOF {
650 return false
651 }
652 if pos >= bad.From {
653 break
654 }
655 pos, tkn, _ = s.Scan()
656 }
657
658 var stmt ast.Stmt
659 switch tkn {
660 case token.DEFER:
661 stmt = &ast.DeferStmt{
662 Defer: pos,
663 }
664 case token.GO:
665 stmt = &ast.GoStmt{
666 Go: pos,
667 }
668 default:
669 return false
670 }
671
672 var (
673 from, to, last token.Pos
674 lastToken token.Token
675 braceDepth int
676 phantomSelectors []token.Pos
677 )
678 FindTo:
679 for {
680 to, tkn, _ = s.Scan()
681
682 if from == token.NoPos {
683 from = to
684 }
685
686 switch tkn {
687 case token.EOF:
688 break FindTo
689 case token.SEMICOLON:
690 // If we aren't in nested braces, end of statement means
691 // end of expression.
692 if braceDepth == 0 {
693 break FindTo
694 }
695 case token.LBRACE:
696 braceDepth++
697 }
698
699 // This handles the common dangling selector case. For example in
700 //
701 // defer fmt.
702 // y := 1
703 //
704 // we notice the dangling period and end our expression.
705 //
706 // If the previous token was a "." and we are looking at a "}",
707 // the period is likely a dangling selector and needs a phantom
708 // "_". Likewise if the current token is on a different line than
709 // the period, the period is likely a dangling selector.
710 if lastToken == token.PERIOD && (tkn == token.RBRACE || safetoken.Line(tok, to) > safetoken.Line(tok, last)) {
711 // Insert phantom "_" selector after the dangling ".".
712 phantomSelectors = append(phantomSelectors, last+1)
713 // If we aren't in a block then end the expression after the ".".
714 if braceDepth == 0 {
715 to = last + 1
716 break
717 }
718 }
719
720 lastToken = tkn
721 last = to
722
723 switch tkn {
724 case token.RBRACE:
725 braceDepth--
726 if braceDepth <= 0 {
727 if braceDepth == 0 {
728 // +1 to include the "}" itself.
729 to += 1
730 }
731 break FindTo
732 }
733 }
734 }
735
736 fromOffset, toOffset, err := safetoken.Offsets(tok, from, to)
737 if err != nil {
738 return false
739 }
740 if !from.IsValid() || fromOffset >= len(src) {
741 return false
742 }
743 if !to.IsValid() || toOffset >= len(src) {
744 return false
745 }
746
747 // Insert any phantom selectors needed to prevent dangling "." from messing
748 // up the AST.
749 exprBytes := make([]byte, 0, int(to-from)+len(phantomSelectors))
750 for i, b := range src[fromOffset:toOffset] {
751 if len(phantomSelectors) > 0 && from+token.Pos(i) == phantomSelectors[0] {
752 exprBytes = append(exprBytes, '_')
753 phantomSelectors = phantomSelectors[1:]
754 }
755 exprBytes = append(exprBytes, b)
756 }
757
758 if len(phantomSelectors) > 0 {
759 exprBytes = append(exprBytes, '_')
760 }
761
762 expr, err := parseExpr(tok, from, exprBytes)
763 if err != nil {
764 return false
765 }
766
767 // Package the expression into a fake *ast.CallExpr and re-insert
768 // into the function.
769 call := &ast.CallExpr{
770 Fun: expr,
771 Lparen: to,
772 Rparen: to,
773 }
774
775 switch stmt := stmt.(type) {
776 case *ast.DeferStmt:
777 stmt.Call = call
778 case *ast.GoStmt:
779 stmt.Call = call
780 }
781
782 return replaceNode(parent, bad, stmt)
783 }
784
785 // parseStmt parses the statement in src and updates its position to
786 // start at pos.
787 //
788 // tok is the original file containing pos. Used to ensure that all adjusted
789 // positions are valid.
790 func parseStmt(tok *token.File, pos token.Pos, src []byte) (ast.Stmt, error) {
791 // Wrap our expression to make it a valid Go file we can pass to ParseFile.
792 fileSrc := slices.Concat([]byte("package fake;func _(){"), src, []byte("}"))
793
794 // Use ParseFile instead of ParseExpr because ParseFile has
795 // best-effort behavior, whereas ParseExpr fails hard on any error.
796 fakeFile, err := parser.ParseFile(token.NewFileSet(), "", fileSrc, parser.SkipObjectResolution)
797 if fakeFile == nil {
798 return nil, fmt.Errorf("error reading fake file source: %v", err)
799 }
800
801 // Extract our expression node from inside the fake file.
802 if len(fakeFile.Decls) == 0 {
803 return nil, fmt.Errorf("error parsing fake file: %v", err)
804 }
805
806 fakeDecl, _ := fakeFile.Decls[0].(*ast.FuncDecl)
807 if fakeDecl == nil || len(fakeDecl.Body.List) == 0 {
808 return nil, fmt.Errorf("no statement in %s: %v", src, err)
809 }
810
811 stmt := fakeDecl.Body.List[0]
812
813 // parser.ParseFile returns undefined positions.
814 // Adjust them for the current file.
815 offsetPositions(tok, stmt, pos-1-(stmt.Pos()-1))
816
817 return stmt, nil
818 }
819
820 // parseExpr parses the expression in src and updates its position to
821 // start at pos.
822 func parseExpr(tok *token.File, pos token.Pos, src []byte) (ast.Expr, error) {
823 stmt, err := parseStmt(tok, pos, src)
824 if err != nil {
825 return nil, err
826 }
827
828 exprStmt, ok := stmt.(*ast.ExprStmt)
829 if !ok {
830 return nil, fmt.Errorf("no expr in %s: %v", src, err)
831 }
832
833 return exprStmt.X, nil
834 }
835
836 var tokenPosType = reflect.TypeFor[token.Pos]()
837
838 // offsetPositions applies an offset to the positions in an ast.Node.
839 func offsetPositions(tok *token.File, n ast.Node, offset token.Pos) {
840 fileBase := token.Pos(tok.Base())
841 fileEnd := fileBase + token.Pos(tok.Size())
842 ast.Inspect(n, func(n ast.Node) bool {
843 if n == nil {
844 return false
845 }
846
847 v := reflect.ValueOf(n).Elem()
848
849 switch v.Kind() {
850 case reflect.Struct:
851 for i := 0; i < v.NumField(); i++ {
852 f := v.Field(i)
853 if f.Type() != tokenPosType {
854 continue
855 }
856
857 if !f.CanSet() {
858 continue
859 }
860
861 pos := token.Pos(f.Int())
862
863 // Don't offset invalid positions: they should stay invalid.
864 if !pos.IsValid() {
865 continue
866 }
867
868 // Clamp value to valid range; see #64335.
869 //
870 // TODO(golang/go#64335): this is a hack, because our fixes should not
871 // produce positions that overflow (but they do; see golang/go#64488,
872 // #73438, #66790, #66683, #67704).
873 pos = min(max(pos+offset, fileBase), fileEnd)
874
875 f.SetInt(int64(pos))
876 }
877 }
878
879 return true
880 })
881 }
882
883 // replaceNode updates parent's child oldChild to be newChild. It
884 // returns whether it replaced successfully.
885 func replaceNode(parent, oldChild, newChild ast.Node) bool {
886 if parent == nil || oldChild == nil || newChild == nil {
887 return false
888 }
889
890 parentVal := reflect.ValueOf(parent).Elem()
891 if parentVal.Kind() != reflect.Struct {
892 return false
893 }
894
895 newChildVal := reflect.ValueOf(newChild)
896
897 tryReplace := func(v reflect.Value) bool {
898 if !v.CanSet() || !v.CanInterface() {
899 return false
900 }
901
902 // If the existing value is oldChild, we found our child. Make
903 // sure our newChild is assignable and then make the swap.
904 if v.Interface() == oldChild && newChildVal.Type().AssignableTo(v.Type()) {
905 v.Set(newChildVal)
906 return true
907 }
908
909 return false
910 }
911
912 // Loop over parent's struct fields.
913 for i := 0; i < parentVal.NumField(); i++ {
914 f := parentVal.Field(i)
915
916 switch f.Kind() {
917 // Check interface and pointer fields.
918 case reflect.Interface, reflect.Pointer:
919 if tryReplace(f) {
920 return true
921 }
922
923 // Search through any slice fields.
924 case reflect.Slice:
925 for i := 0; i < f.Len(); i++ {
926 if tryReplace(f.Index(i)) {
927 return true
928 }
929 }
930 }
931 }
932
933 return false
934 }