|
| 1 | +// Copyright 2025 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 modernize |
| 6 | + |
| 7 | +import ( |
| 8 | + _ "embed" |
| 9 | + "go/ast" |
| 10 | + "go/token" |
| 11 | + "go/types" |
| 12 | + "strings" |
| 13 | + |
| 14 | + "fmt" |
| 15 | + |
| 16 | + "golang.org/x/tools/go/analysis" |
| 17 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 18 | + "golang.org/x/tools/go/ast/inspector" |
| 19 | + "golang.org/x/tools/go/types/typeutil" |
| 20 | + "golang.org/x/tools/internal/analysisinternal" |
| 21 | +) |
| 22 | + |
| 23 | +var NewExprAnalyzer = &analysis.Analyzer{ |
| 24 | + Name: "newexpr", |
| 25 | + Doc: analysisinternal.MustExtractDoc(doc, "newexpr"), |
| 26 | + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize#newexpr", |
| 27 | + Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 28 | + Run: run, |
| 29 | + FactTypes: []analysis.Fact{&newLike{}}, |
| 30 | +} |
| 31 | + |
| 32 | +func run(pass *analysis.Pass) (any, error) { |
| 33 | + var ( |
| 34 | + inspect = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 35 | + info = pass.TypesInfo |
| 36 | + ) |
| 37 | + |
| 38 | + // Detect functions that are new-like, i.e. have the form: |
| 39 | + // |
| 40 | + // func f(x T) *T { return &x } |
| 41 | + // |
| 42 | + // meaning that it is equivalent to new(x), if x has type T. |
| 43 | + for curFuncDecl := range inspect.Root().Preorder((*ast.FuncDecl)(nil)) { |
| 44 | + decl := curFuncDecl.Node().(*ast.FuncDecl) |
| 45 | + fn := info.Defs[decl.Name].(*types.Func) |
| 46 | + if decl.Body != nil && len(decl.Body.List) == 1 { |
| 47 | + if ret, ok := decl.Body.List[0].(*ast.ReturnStmt); ok && len(ret.Results) == 1 { |
| 48 | + if unary, ok := ret.Results[0].(*ast.UnaryExpr); ok && unary.Op == token.AND { |
| 49 | + if id, ok := unary.X.(*ast.Ident); ok { |
| 50 | + if v, ok := info.Uses[id].(*types.Var); ok { |
| 51 | + sig := fn.Signature() |
| 52 | + if sig.Results().Len() == 1 && |
| 53 | + is[*types.Pointer](sig.Results().At(0).Type()) && // => no iface conversion |
| 54 | + sig.Params().Len() == 1 && |
| 55 | + sig.Params().At(0) == v { |
| 56 | + |
| 57 | + // Export a fact for each one. |
| 58 | + pass.ExportObjectFact(fn, &newLike{}) |
| 59 | + |
| 60 | + // Check file version. |
| 61 | + file := enclosingFile(curFuncDecl) |
| 62 | + if !fileUses(info, file, "go1.26") { |
| 63 | + continue // new(expr) not available in this file |
| 64 | + } |
| 65 | + |
| 66 | + var edits []analysis.TextEdit |
| 67 | + |
| 68 | + // If 'new' is not shadowed, replace func body: &x -> new(x). |
| 69 | + // This makes it safely and cleanly inlinable. |
| 70 | + curRet, _ := curFuncDecl.FindNode(ret) |
| 71 | + if lookup(info, curRet, "new") == builtinNew { |
| 72 | + edits = []analysis.TextEdit{ |
| 73 | + // return &x |
| 74 | + // ---- - |
| 75 | + // return new(x) |
| 76 | + { |
| 77 | + Pos: unary.OpPos, |
| 78 | + End: unary.OpPos + token.Pos(len("&")), |
| 79 | + NewText: []byte("new("), |
| 80 | + }, |
| 81 | + { |
| 82 | + Pos: unary.X.End(), |
| 83 | + End: unary.X.End(), |
| 84 | + NewText: []byte(")"), |
| 85 | + }, |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + // Disabled until we resolve https://go.dev/issue/75726 |
| 90 | + // (Go version skew between caller and callee in inliner.) |
| 91 | + // TODO(adonovan): fix and reenable. |
| 92 | + // |
| 93 | + // Also, restore these lines to our section of doc.go: |
| 94 | + // //go:fix inline |
| 95 | + // ... |
| 96 | + // (The directive comment causes the inline analyzer to suggest |
| 97 | + // that calls to such functions are inlined.) |
| 98 | + if false { |
| 99 | + // Add a //go:fix inline annotation, if not already present. |
| 100 | + // TODO(adonovan): use ast.ParseDirective when go1.26 is assured. |
| 101 | + if !strings.Contains(decl.Doc.Text(), "go:fix inline") { |
| 102 | + edits = append(edits, analysis.TextEdit{ |
| 103 | + Pos: decl.Pos(), |
| 104 | + End: decl.Pos(), |
| 105 | + NewText: []byte("//go:fix inline\n"), |
| 106 | + }) |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + if len(edits) > 0 { |
| 111 | + pass.Report(analysis.Diagnostic{ |
| 112 | + Pos: decl.Name.Pos(), |
| 113 | + End: decl.Name.End(), |
| 114 | + Message: fmt.Sprintf("%s can be an inlinable wrapper around new(expr)", decl.Name), |
| 115 | + SuggestedFixes: []analysis.SuggestedFix{ |
| 116 | + { |
| 117 | + Message: "Make %s an inlinable wrapper around new(expr)", |
| 118 | + TextEdits: edits, |
| 119 | + }, |
| 120 | + }, |
| 121 | + }) |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + // Report and transform calls, when safe. |
| 132 | + // In effect, this is inlining the new-like function |
| 133 | + // even before we have marked the callee with //go:fix inline. |
| 134 | + for curCall := range inspect.Root().Preorder((*ast.CallExpr)(nil)) { |
| 135 | + call := curCall.Node().(*ast.CallExpr) |
| 136 | + var fact newLike |
| 137 | + if fn, ok := typeutil.Callee(info, call).(*types.Func); ok && |
| 138 | + pass.ImportObjectFact(fn, &fact) { |
| 139 | + |
| 140 | + // Check file version. |
| 141 | + file := enclosingFile(curCall) |
| 142 | + if !fileUses(info, file, "go1.26") { |
| 143 | + continue // new(expr) not available in this file |
| 144 | + } |
| 145 | + |
| 146 | + // Check new is not shadowed. |
| 147 | + if lookup(info, curCall, "new") != builtinNew { |
| 148 | + continue |
| 149 | + } |
| 150 | + |
| 151 | + // The return type *T must exactly match the argument type T. |
| 152 | + // (We formulate it this way--not in terms of the parameter |
| 153 | + // type--to support generics.) |
| 154 | + var targ types.Type |
| 155 | + { |
| 156 | + arg := call.Args[0] |
| 157 | + tvarg := info.Types[arg] |
| 158 | + |
| 159 | + // Constants: we must work around the type checker |
| 160 | + // bug that causes info.Types to wrongly report the |
| 161 | + // "typed" type for an untyped constant. |
| 162 | + // (See "historical reasons" in issue go.dev/issue/70638.) |
| 163 | + // |
| 164 | + // We don't have a reliable way to do this but we can attempt |
| 165 | + // to re-typecheck the constant expression on its own, in |
| 166 | + // the original lexical environment but not as a part of some |
| 167 | + // larger expression that implies a conversion to some "typed" type. |
| 168 | + // (For the genesis of this idea see (*state).arguments |
| 169 | + // in ../../../../internal/refactor/inline/inline.go.) |
| 170 | + if tvarg.Value != nil { |
| 171 | + info2 := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} |
| 172 | + if err := types.CheckExpr(token.NewFileSet(), pass.Pkg, token.NoPos, arg, info2); err != nil { |
| 173 | + continue // unexpected error |
| 174 | + } |
| 175 | + tvarg = info2.Types[arg] |
| 176 | + } |
| 177 | + |
| 178 | + targ = types.Default(tvarg.Type) |
| 179 | + } |
| 180 | + if !types.Identical(types.NewPointer(targ), info.TypeOf(call)) { |
| 181 | + continue |
| 182 | + } |
| 183 | + |
| 184 | + pass.Report(analysis.Diagnostic{ |
| 185 | + Pos: call.Pos(), |
| 186 | + End: call.End(), |
| 187 | + Message: fmt.Sprintf("call of %s(x) can be simplified to new(x)", fn.Name()), |
| 188 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 189 | + Message: fmt.Sprintf("Simplify %s(x) to new(x)", fn.Name()), |
| 190 | + TextEdits: []analysis.TextEdit{{ |
| 191 | + Pos: call.Fun.Pos(), |
| 192 | + End: call.Fun.End(), |
| 193 | + NewText: []byte("new"), |
| 194 | + }}, |
| 195 | + }}, |
| 196 | + }) |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + return nil, nil |
| 201 | +} |
| 202 | + |
| 203 | +// A newLike fact records that its associated function is "new-like". |
| 204 | +type newLike struct{} |
| 205 | + |
| 206 | +func (*newLike) AFact() {} |
| 207 | +func (*newLike) String() string { return "newlike" } |
0 commit comments