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.
18 "golang.org/x/tools/internal/event"
19 "golang.org/x/tools/internal/lsp/debug/tag"
20 "golang.org/x/tools/internal/lsp/protocol"
21 "golang.org/x/tools/internal/lsp/source"
22 "golang.org/x/tools/internal/memoize"
23 "golang.org/x/tools/internal/span"
24 errors "golang.org/x/xerrors"
27 // parseKey uniquely identifies a parsed Go file.
28 type parseKey struct {
29 file source.FileIdentity
33 // astCacheKey is similar to parseKey, but is a distinct type because
34 // it is used to key a different value within the same map.
35 type astCacheKey parseKey
37 type parseGoHandle struct {
38 handle *memoize.Handle
39 file source.FileHandle
41 astCacheHandle *memoize.Handle
44 type parseGoData struct {
45 parsed *source.ParsedGoFile
47 // If true, we adjusted the AST to make it type check better, and
48 // it may not match the source code.
50 err error // any other errors
53 func (s *snapshot) parseGoHandle(ctx context.Context, fh source.FileHandle, mode source.ParseMode) *parseGoHandle {
55 file: fh.FileIdentity(),
58 if pgh := s.getGoFile(key); pgh != nil {
61 parseHandle := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
62 snapshot := arg.(*snapshot)
63 return parseGo(ctx, snapshot.view.session.cache.fset, fh, mode)
66 astHandle := s.generation.Bind(astCacheKey(key), func(ctx context.Context, arg memoize.Arg) interface{} {
67 snapshot := arg.(*snapshot)
68 return buildASTCache(ctx, snapshot, parseHandle)
71 pgh := &parseGoHandle{
75 astCacheHandle: astHandle,
77 return s.addGoFile(key, pgh)
80 func (pgh *parseGoHandle) String() string {
81 return pgh.File().URI().Filename()
84 func (pgh *parseGoHandle) File() source.FileHandle {
88 func (pgh *parseGoHandle) Mode() source.ParseMode {
92 func (s *snapshot) ParseGo(ctx context.Context, fh source.FileHandle, mode source.ParseMode) (*source.ParsedGoFile, error) {
93 pgh := s.parseGoHandle(ctx, fh, mode)
94 pgf, _, err := s.parseGo(ctx, pgh)
98 func (s *snapshot) parseGo(ctx context.Context, pgh *parseGoHandle) (*source.ParsedGoFile, bool, error) {
99 d, err := pgh.handle.Get(ctx, s.generation, s)
101 return nil, false, err
103 data := d.(*parseGoData)
104 return data.parsed, data.fixed, data.err
107 func (s *snapshot) PosToDecl(ctx context.Context, pgf *source.ParsedGoFile) (map[token.Pos]ast.Decl, error) {
108 fh, err := s.GetFile(ctx, pgf.URI)
113 pgh := s.parseGoHandle(ctx, fh, pgf.Mode)
114 d, err := pgh.astCacheHandle.Get(ctx, s.generation, s)
119 data := d.(*astCacheData)
120 return data.posToDecl, data.err
123 func (s *snapshot) PosToField(ctx context.Context, pgf *source.ParsedGoFile) (map[token.Pos]*ast.Field, error) {
124 fh, err := s.GetFile(ctx, pgf.URI)
129 pgh := s.parseGoHandle(ctx, fh, pgf.Mode)
130 d, err := pgh.astCacheHandle.Get(ctx, s.generation, s)
131 if err != nil || d == nil {
135 data := d.(*astCacheData)
136 return data.posToField, data.err
139 type astCacheData struct {
142 posToDecl map[token.Pos]ast.Decl
143 posToField map[token.Pos]*ast.Field
146 // buildASTCache builds caches to aid in quickly going from the typed
147 // world to the syntactic world.
148 func buildASTCache(ctx context.Context, snapshot *snapshot, parseHandle *memoize.Handle) *astCacheData {
150 // path contains all ancestors, including n.
152 // decls contains all ancestors that are decls.
156 v, err := parseHandle.Get(ctx, snapshot.generation, snapshot)
158 return &astCacheData{err: err}
160 file := v.(*parseGoData).parsed.File
162 return &astCacheData{err: fmt.Errorf("nil file")}
165 data := &astCacheData{
166 posToDecl: make(map[token.Pos]ast.Decl),
167 posToField: make(map[token.Pos]*ast.Field),
170 ast.Inspect(file, func(n ast.Node) bool {
172 lastP := path[len(path)-1]
173 path = path[:len(path)-1]
174 if len(decls) > 0 && decls[len(decls)-1] == lastP {
175 decls = decls[:len(decls)-1]
180 path = append(path, n)
182 switch n := n.(type) {
184 addField := func(f ast.Node) {
185 if f.Pos().IsValid() {
186 data.posToField[f.Pos()] = n
188 data.posToDecl[f.Pos()] = decls[len(decls)-1]
193 // Add mapping for *ast.Field itself. This handles embedded
194 // fields which have no associated *ast.Ident name.
197 // Add mapping for each field name since you can have
198 // multiple names for the same type expression.
199 for _, name := range n.Names {
203 // Also map "X" in "...X" to the containing *ast.Field. This
204 // makes it easy to format variadic signature params
206 if elips, ok := n.Type.(*ast.Ellipsis); ok && elips.Elt != nil {
210 decls = append(decls, n)
212 if n.Name != nil && n.Name.Pos().IsValid() {
213 data.posToDecl[n.Name.Pos()] = n
216 decls = append(decls, n)
218 for _, spec := range n.Specs {
219 switch spec := spec.(type) {
221 if spec.Name != nil && spec.Name.Pos().IsValid() {
222 data.posToDecl[spec.Name.Pos()] = n
225 for _, id := range spec.Names {
226 if id != nil && id.Pos().IsValid() {
227 data.posToDecl[id.Pos()] = n
240 func parseGo(ctx context.Context, fset *token.FileSet, fh source.FileHandle, mode source.ParseMode) *parseGoData {
241 ctx, done := event.Start(ctx, "cache.parseGo", tag.File.Of(fh.URI().Filename()))
244 if fh.Kind() != source.Go {
245 return &parseGoData{err: errors.Errorf("cannot parse non-Go file %s", fh.URI())}
247 buf, err := fh.Read()
249 return &parseGoData{err: err}
252 parserMode := parser.AllErrors | parser.ParseComments
253 if mode == source.ParseHeader {
254 parserMode = parser.ImportsOnly | parser.ParseComments
256 file, parseError := parser.ParseFile(fset, fh.URI().Filename(), buf, parserMode)
260 tok = fset.File(file.Pos())
262 tok = fset.AddFile(fh.URI().Filename(), -1, len(buf))
263 tok.SetLinesForContent(buf)
265 parsed: &source.ParsedGoFile{
271 Mapper: &protocol.ColumnMapper{
274 Converter: span.NewTokenConverter(fset, tok),
276 ParseErr: parseError,
281 // Fix any badly parsed parts of the AST.
282 fixed = fixAST(ctx, file, tok, buf)
284 // Fix certain syntax errors that render the file unparseable.
285 newSrc := fixSrc(file, tok, buf)
287 newFile, _ := parser.ParseFile(fset, fh.URI().Filename(), newSrc, parserMode)
289 // Maintain the original parseError so we don't try formatting the doctored file.
292 tok = fset.File(file.Pos())
294 fixed = fixAST(ctx, file, tok, buf)
298 if mode == source.ParseExported {
302 // A missing file is always an error; use the parse error or make one up if there isn't one.
304 if parseError == nil {
305 parseError = errors.Errorf("parsing %s failed with no parse error reported", fh.URI())
309 m := &protocol.ColumnMapper{
311 Converter: span.NewTokenConverter(fset, tok),
316 parsed: &source.ParsedGoFile{
323 ParseErr: parseError,
330 // trimAST clears any part of the AST not relevant to type checking
331 // expressions at pos.
332 func trimAST(file *ast.File) {
333 ast.Inspect(file, func(n ast.Node) bool {
337 switch n := n.(type) {
342 case *ast.CaseClause:
344 case *ast.CommClause:
346 case *ast.CompositeLit:
347 // types.Info.Types for long slice/array literals are particularly
348 // expensive. Try to clear them out.
349 at, ok := n.Type.(*ast.ArrayType)
353 // Removing the elements from an ellipsis array changes its type.
354 // Try to set the length explicitly so we can continue.
355 if _, ok := at.Len.(*ast.Ellipsis); ok {
356 length, ok := arrayLength(n)
360 at.Len = &ast.BasicLit{
362 Value: fmt.Sprint(length),
363 ValuePos: at.Len.Pos(),
372 // arrayLength returns the length of some simple forms of ellipsis array literal.
373 // Notably, it handles the tables in golang.org/x/text.
374 func arrayLength(array *ast.CompositeLit) (int, bool) {
375 litVal := func(expr ast.Expr) (int, bool) {
376 lit, ok := expr.(*ast.BasicLit)
380 val, err := strconv.ParseInt(lit.Value, 10, 64)
384 return int(val), true
387 for _, elt := range array.Elts {
388 kve, ok := elt.(*ast.KeyValueExpr)
392 switch key := kve.Key.(type) {
394 if val, ok := litVal(key); ok && largestKey < val {
397 case *ast.BinaryExpr:
398 // golang.org/x/text uses subtraction (and only subtraction) in its indices.
399 if key.Op != token.SUB {
402 x, ok := litVal(key.X)
406 y, ok := litVal(key.Y)
410 if val := x - y; largestKey < val {
415 if largestKey != -1 {
416 return largestKey + 1, true
418 return len(array.Elts), true
421 // fixAST inspects the AST and potentially modifies any *ast.BadStmts so that it can be
422 // type-checked more effectively.
423 func fixAST(ctx context.Context, n ast.Node, tok *token.File, src []byte) (fixed bool) {
425 walkASTWithParent(n, func(n, parent ast.Node) bool {
426 switch n := n.(type) {
428 if fixed = fixDeferOrGoStmt(n, parent, tok, src); fixed {
429 // Recursively fix in our fixed node.
430 _ = fixAST(ctx, parent, tok, src)
432 err = errors.Errorf("unable to parse defer or go from *ast.BadStmt: %v", err)
436 if fixed = fixArrayType(n, parent, tok, src); fixed {
437 // Recursively fix in our fixed node.
438 _ = fixAST(ctx, parent, tok, src)
442 // Fix cases where parser interprets if/for/switch "init"
443 // statement as "cond" expression, e.g.:
445 // // "i := foo" is init statement, not condition.
448 fixInitStmt(n, parent, tok, src)
451 case *ast.SelectorExpr:
452 // Fix cases where a keyword prefix results in a phantom "_" selector, e.g.:
454 // foo.var<> // want to complete to "foo.variance"
456 fixPhantomSelector(n, tok, src)
460 switch parent.(type) {
461 case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
462 // Adjust closing curly brace of empty switch/select
463 // statements so we can complete inside them.
464 fixEmptySwitch(n, tok, src)
475 // walkASTWithParent walks the AST rooted at n. The semantics are
476 // similar to ast.Inspect except it does not call f(nil).
477 func walkASTWithParent(n ast.Node, f func(n ast.Node, parent ast.Node) bool) {
478 var ancestors []ast.Node
479 ast.Inspect(n, func(n ast.Node) (recurse bool) {
482 ancestors = append(ancestors, n)
487 ancestors = ancestors[:len(ancestors)-1]
492 if len(ancestors) > 0 {
493 parent = ancestors[len(ancestors)-1]
500 // fixSrc attempts to modify the file's source code to fix certain
501 // syntax errors that leave the rest of the file unparsed.
502 func fixSrc(f *ast.File, tok *token.File, src []byte) (newSrc []byte) {
503 walkASTWithParent(f, func(n, parent ast.Node) bool {
508 switch n := n.(type) {
510 newSrc = fixMissingCurlies(f, n, parent, tok, src)
511 case *ast.SelectorExpr:
512 newSrc = fixDanglingSelector(n, tok, src)
521 // fixMissingCurlies adds in curly braces for block statements that
522 // are missing curly braces. For example:
529 func fixMissingCurlies(f *ast.File, b *ast.BlockStmt, parent ast.Node, tok *token.File, src []byte) []byte {
530 // If the "{" is already in the source code, there isn't anything to
531 // fix since we aren't missing curlies.
532 if b.Lbrace.IsValid() {
533 braceOffset := tok.Offset(b.Lbrace)
534 if braceOffset < len(src) && src[braceOffset] == '{' {
539 parentLine := tok.Line(parent.Pos())
541 if parentLine >= tok.LineCount() {
542 // If we are the last line in the file, no need to fix anything.
546 // Insert curlies at the end of parent's starting line. The parent
547 // is the statement that contains the block, e.g. *ast.IfStmt. The
548 // block's Pos()/End() can't be relied upon because they are based
549 // on the (missing) curly braces. We assume the statement is a
550 // single line for now and try sticking the curly braces at the end.
551 insertPos := tok.LineStart(parentLine+1) - 1
553 // Scootch position backwards until it's not in a comment. For example:
555 // if foo<> // some amazing comment |
558 // insertPos will be located at "|", so we back it out of the comment.
562 for _, c := range f.Comments {
563 if c.Pos() < insertPos && insertPos <= c.End() {
570 // Bail out if line doesn't end in an ident or ".". This is to avoid
571 // cases like below where we end up making things worse by adding
576 switch precedingToken(insertPos, tok, src) {
577 case token.IDENT, token.PERIOD:
584 buf.Grow(len(src) + 3)
585 buf.Write(src[:tok.Offset(insertPos)])
587 // Detect if we need to insert a semicolon to fix "for" loop situations like:
589 // for i := foo(); foo<>
591 // Just adding curlies is not sufficient to make things parse well.
592 if fs, ok := parent.(*ast.ForStmt); ok {
593 if _, ok := fs.Cond.(*ast.BadExpr); !ok {
594 if xs, ok := fs.Post.(*ast.ExprStmt); ok {
595 if _, ok := xs.X.(*ast.BadExpr); ok {
602 // Insert "{}" at insertPos.
605 buf.Write(src[tok.Offset(insertPos):])
609 // fixEmptySwitch moves empty switch/select statements' closing curly
610 // brace down one line. This allows us to properly detect incomplete
611 // "case" and "default" keywords as inside the switch statement. For
623 // Later we manually pull out the "def" token, but we need to detect
624 // that our "<>" position is inside the switch block. To do that we
625 // move the curly brace so it looks like:
631 func fixEmptySwitch(body *ast.BlockStmt, tok *token.File, src []byte) {
632 // We only care about empty switch statements.
633 if len(body.List) > 0 || !body.Rbrace.IsValid() {
637 // If the right brace is actually in the source code at the
638 // specified position, don't mess with it.
639 braceOffset := tok.Offset(body.Rbrace)
640 if braceOffset < len(src) && src[braceOffset] == '}' {
644 braceLine := tok.Line(body.Rbrace)
645 if braceLine >= tok.LineCount() {
646 // If we are the last line in the file, no need to fix anything.
650 // Move the right brace down one line.
651 body.Rbrace = tok.LineStart(braceLine + 1)
654 // fixDanglingSelector inserts real "_" selector expressions in place
655 // of phantom "_" selectors. For example:
660 // var x struct { i int }
662 // To fix completion at "<>", we insert a real "_" after the "." so the
663 // following declaration of "x" can be parsed and type checked
665 func fixDanglingSelector(s *ast.SelectorExpr, tok *token.File, src []byte) []byte {
666 if !isPhantomUnderscore(s.Sel, tok, src) {
670 if !s.X.End().IsValid() {
674 // Insert directly after the selector's ".".
675 insertOffset := tok.Offset(s.X.End()) + 1
676 if src[insertOffset-1] != '.' {
681 buf.Grow(len(src) + 1)
682 buf.Write(src[:insertOffset])
684 buf.Write(src[insertOffset:])
688 // fixPhantomSelector tries to fix selector expressions with phantom
689 // "_" selectors. In particular, we check if the selector is a
690 // keyword, and if so we swap in an *ast.Ident with the keyword text. For example:
694 // yields a "_" selector instead of "var" since "var" is a keyword.
695 func fixPhantomSelector(sel *ast.SelectorExpr, tok *token.File, src []byte) {
696 if !isPhantomUnderscore(sel.Sel, tok, src) {
700 // Only consider selectors directly abutting the selector ".". This
701 // avoids false positives in cases like:
703 // foo. // don't think "var" is our selector
706 if sel.Sel.Pos() != sel.X.End()+1 {
710 maybeKeyword := readKeyword(sel.Sel.Pos(), tok, src)
711 if maybeKeyword == "" {
715 replaceNode(sel, sel.Sel, &ast.Ident{
717 NamePos: sel.Sel.Pos(),
721 // isPhantomUnderscore reports whether the given ident is a phantom
722 // underscore. The parser sometimes inserts phantom underscores when
723 // it encounters otherwise unparseable situations.
724 func isPhantomUnderscore(id *ast.Ident, tok *token.File, src []byte) bool {
725 if id == nil || id.Name != "_" {
729 // Phantom underscore means the underscore is not actually in the
731 offset := tok.Offset(id.Pos())
732 return len(src) <= offset || src[offset] != '_'
735 // fixInitStmt fixes cases where the parser misinterprets an
736 // if/for/switch "init" statement as the "cond" conditional. In cases
737 // like "if i := 0" the user hasn't typed the semicolon yet so the
738 // parser is looking for the conditional expression. However, "i := 0"
739 // are not valid expressions, so we get a BadExpr.
740 func fixInitStmt(bad *ast.BadExpr, parent ast.Node, tok *token.File, src []byte) {
741 if !bad.Pos().IsValid() || !bad.End().IsValid() {
745 // Try to extract a statement from the BadExpr.
746 stmtBytes := src[tok.Offset(bad.Pos()) : tok.Offset(bad.End()-1)+1]
747 stmt, err := parseStmt(bad.Pos(), stmtBytes)
752 // If the parent statement doesn't already have an "init" statement,
753 // move the extracted statement into the "init" field and insert a
754 // dummy expression into the required "cond" field.
755 switch p := parent.(type) {
774 case *ast.SwitchStmt:
783 // readKeyword reads the keyword starting at pos, if any.
784 func readKeyword(pos token.Pos, tok *token.File, src []byte) string {
786 for i := tok.Offset(pos); i < len(src); i++ {
787 // Use a simplified identifier check since keywords are always lowercase ASCII.
788 if src[i] < 'a' || src[i] > 'z' {
791 kwBytes = append(kwBytes, src[i])
793 // Stop search at arbitrarily chosen too-long-for-a-keyword length.
794 if len(kwBytes) > 15 {
799 if kw := string(kwBytes); token.Lookup(kw).IsKeyword() {
806 // fixArrayType tries to parse an *ast.BadExpr into an *ast.ArrayType.
807 // go/parser often turns lone array types like "[]int" into BadExprs
808 // if it isn't expecting a type.
809 func fixArrayType(bad *ast.BadExpr, parent ast.Node, tok *token.File, src []byte) bool {
810 // Our expected input is a bad expression that looks like "[]someExpr".
815 if !from.IsValid() || !to.IsValid() {
819 exprBytes := make([]byte, 0, int(to-from)+3)
820 // Avoid doing tok.Offset(to) since that panics if badExpr ends at EOF.
821 exprBytes = append(exprBytes, src[tok.Offset(from):tok.Offset(to-1)+1]...)
822 exprBytes = bytes.TrimSpace(exprBytes)
824 // If our expression ends in "]" (e.g. "[]"), add a phantom selector
825 // so we can complete directly after the "[]".
826 if len(exprBytes) > 0 && exprBytes[len(exprBytes)-1] == ']' {
827 exprBytes = append(exprBytes, '_')
830 // Add "{}" to turn our ArrayType into a CompositeLit. This is to
831 // handle the case of "[...]int" where we must make it a composite
832 // literal to be parseable.
833 exprBytes = append(exprBytes, '{', '}')
835 expr, err := parseExpr(from, exprBytes)
840 cl, _ := expr.(*ast.CompositeLit)
845 at, _ := cl.Type.(*ast.ArrayType)
850 return replaceNode(parent, bad, at)
853 // precedingToken scans src to find the token preceding pos.
854 func precedingToken(pos token.Pos, tok *token.File, src []byte) token.Token {
855 s := &scanner.Scanner{}
856 s.Init(tok, src, nil, 0)
858 var lastTok token.Token
861 if t == token.EOF || p >= pos {
870 // fixDeferOrGoStmt tries to parse an *ast.BadStmt into a defer or a go statement.
872 // go/parser packages a statement of the form "defer x." as an *ast.BadStmt because
873 // it does not include a call expression. This means that go/types skips type-checking
874 // this statement entirely, and we can't use the type information when completing.
875 // Here, we try to generate a fake *ast.DeferStmt or *ast.GoStmt to put into the AST,
876 // instead of the *ast.BadStmt.
877 func fixDeferOrGoStmt(bad *ast.BadStmt, parent ast.Node, tok *token.File, src []byte) bool {
878 // Check if we have a bad statement containing either a "go" or "defer".
879 s := &scanner.Scanner{}
880 s.Init(tok, src, nil, 0)
887 if tkn == token.EOF {
893 pos, tkn, _ = s.Scan()
899 stmt = &ast.DeferStmt{
911 from, to, last token.Pos
912 lastToken token.Token
914 phantomSelectors []token.Pos
918 to, tkn, _ = s.Scan()
920 if from == token.NoPos {
927 case token.SEMICOLON:
928 // If we aren't in nested braces, end of statement means
929 // end of expression.
937 // This handles the common dangling selector case. For example in
942 // we notice the dangling period and end our expression.
944 // If the previous token was a "." and we are looking at a "}",
945 // the period is likely a dangling selector and needs a phantom
946 // "_". Likewise if the current token is on a different line than
947 // the period, the period is likely a dangling selector.
948 if lastToken == token.PERIOD && (tkn == token.RBRACE || tok.Line(to) > tok.Line(last)) {
949 // Insert phantom "_" selector after the dangling ".".
950 phantomSelectors = append(phantomSelectors, last+1)
951 // If we aren't in a block then end the expression after the ".".
966 // +1 to include the "}" itself.
974 if !from.IsValid() || tok.Offset(from) >= len(src) {
978 if !to.IsValid() || tok.Offset(to) >= len(src) {
982 // Insert any phantom selectors needed to prevent dangling "." from messing
984 exprBytes := make([]byte, 0, int(to-from)+len(phantomSelectors))
985 for i, b := range src[tok.Offset(from):tok.Offset(to)] {
986 if len(phantomSelectors) > 0 && from+token.Pos(i) == phantomSelectors[0] {
987 exprBytes = append(exprBytes, '_')
988 phantomSelectors = phantomSelectors[1:]
990 exprBytes = append(exprBytes, b)
993 if len(phantomSelectors) > 0 {
994 exprBytes = append(exprBytes, '_')
997 expr, err := parseExpr(from, exprBytes)
1002 // Package the expression into a fake *ast.CallExpr and re-insert
1003 // into the function.
1004 call := &ast.CallExpr{
1010 switch stmt := stmt.(type) {
1011 case *ast.DeferStmt:
1017 return replaceNode(parent, bad, stmt)
1020 // parseStmt parses the statement in src and updates its position to
1022 func parseStmt(pos token.Pos, src []byte) (ast.Stmt, error) {
1023 // Wrap our expression to make it a valid Go file we can pass to ParseFile.
1024 fileSrc := bytes.Join([][]byte{
1025 []byte("package fake;func _(){"),
1030 // Use ParseFile instead of ParseExpr because ParseFile has
1031 // best-effort behavior, whereas ParseExpr fails hard on any error.
1032 fakeFile, err := parser.ParseFile(token.NewFileSet(), "", fileSrc, 0)
1033 if fakeFile == nil {
1034 return nil, errors.Errorf("error reading fake file source: %v", err)
1037 // Extract our expression node from inside the fake file.
1038 if len(fakeFile.Decls) == 0 {
1039 return nil, errors.Errorf("error parsing fake file: %v", err)
1042 fakeDecl, _ := fakeFile.Decls[0].(*ast.FuncDecl)
1043 if fakeDecl == nil || len(fakeDecl.Body.List) == 0 {
1044 return nil, errors.Errorf("no statement in %s: %v", src, err)
1047 stmt := fakeDecl.Body.List[0]
1049 // parser.ParseFile returns undefined positions.
1050 // Adjust them for the current file.
1051 offsetPositions(stmt, pos-1-(stmt.Pos()-1))
1056 // parseExpr parses the expression in src and updates its position to
1058 func parseExpr(pos token.Pos, src []byte) (ast.Expr, error) {
1059 stmt, err := parseStmt(pos, src)
1064 exprStmt, ok := stmt.(*ast.ExprStmt)
1066 return nil, errors.Errorf("no expr in %s: %v", src, err)
1069 return exprStmt.X, nil
1072 var tokenPosType = reflect.TypeOf(token.NoPos)
1074 // offsetPositions applies an offset to the positions in an ast.Node.
1075 func offsetPositions(n ast.Node, offset token.Pos) {
1076 ast.Inspect(n, func(n ast.Node) bool {
1081 v := reflect.ValueOf(n).Elem()
1084 case reflect.Struct:
1085 for i := 0; i < v.NumField(); i++ {
1087 if f.Type() != tokenPosType {
1095 f.SetInt(f.Int() + int64(offset))
1103 // replaceNode updates parent's child oldChild to be newChild. It
1104 // returns whether it replaced successfully.
1105 func replaceNode(parent, oldChild, newChild ast.Node) bool {
1106 if parent == nil || oldChild == nil || newChild == nil {
1110 parentVal := reflect.ValueOf(parent).Elem()
1111 if parentVal.Kind() != reflect.Struct {
1115 newChildVal := reflect.ValueOf(newChild)
1117 tryReplace := func(v reflect.Value) bool {
1118 if !v.CanSet() || !v.CanInterface() {
1122 // If the existing value is oldChild, we found our child. Make
1123 // sure our newChild is assignable and then make the swap.
1124 if v.Interface() == oldChild && newChildVal.Type().AssignableTo(v.Type()) {
1132 // Loop over parent's struct fields.
1133 for i := 0; i < parentVal.NumField(); i++ {
1134 f := parentVal.Field(i)
1137 // Check interface and pointer fields.
1138 case reflect.Interface, reflect.Ptr:
1143 // Search through any slice fields.
1145 for i := 0; i < f.Len(); i++ {
1146 if tryReplace(f.Index(i)) {