|
| 1 | +// Copyright 2022 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// See the License for the specific language governing permissions and |
| 6 | +// limitations under the License. |
| 7 | + |
| 8 | +//go:build go1.18 |
| 9 | +// +build go1.18 |
| 10 | + |
| 11 | +package main |
| 12 | + |
| 13 | +import ( |
| 14 | + "go/ast" |
| 15 | + "strings" |
| 16 | + |
| 17 | + "github.com/golang/mock/mockgen/model" |
| 18 | +) |
| 19 | + |
| 20 | +func getTypeSpecTypeParams(ts *ast.TypeSpec) []*ast.Field { |
| 21 | + if ts == nil || ts.TypeParams == nil { |
| 22 | + return nil |
| 23 | + } |
| 24 | + return ts.TypeParams.List |
| 25 | +} |
| 26 | + |
| 27 | +func (p *fileParser) parseGenericType(pkg string, typ ast.Expr, tps map[string]bool) (model.Type, error) { |
| 28 | + switch v := typ.(type) { |
| 29 | + case *ast.IndexExpr: |
| 30 | + m, err := p.parseType(pkg, v.X, tps) |
| 31 | + if err != nil { |
| 32 | + return nil, err |
| 33 | + } |
| 34 | + nm, ok := m.(*model.NamedType) |
| 35 | + if !ok { |
| 36 | + return m, nil |
| 37 | + } |
| 38 | + t, err := p.parseType(pkg, v.Index, tps) |
| 39 | + if err != nil { |
| 40 | + return nil, err |
| 41 | + } |
| 42 | + nm.TypeParams = &model.TypeParametersType{TypeParameters: []model.Type{t}} |
| 43 | + return m, nil |
| 44 | + case *ast.IndexListExpr: |
| 45 | + m, err := p.parseType(pkg, v.X, tps) |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + nm, ok := m.(*model.NamedType) |
| 50 | + if !ok { |
| 51 | + return m, nil |
| 52 | + } |
| 53 | + var ts []model.Type |
| 54 | + for _, expr := range v.Indices { |
| 55 | + t, err := p.parseType(pkg, expr, tps) |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + ts = append(ts, t) |
| 60 | + } |
| 61 | + nm.TypeParams = &model.TypeParametersType{TypeParameters: ts} |
| 62 | + return m, nil |
| 63 | + } |
| 64 | + return nil, nil |
| 65 | +} |
| 66 | + |
| 67 | +func getIdentTypeParams(decl interface{}) string { |
| 68 | + if decl == nil { |
| 69 | + return "" |
| 70 | + } |
| 71 | + ts, ok := decl.(*ast.TypeSpec) |
| 72 | + if !ok { |
| 73 | + return "" |
| 74 | + } |
| 75 | + if ts.TypeParams == nil || len(ts.TypeParams.List) == 0 { |
| 76 | + return "" |
| 77 | + } |
| 78 | + var sb strings.Builder |
| 79 | + sb.WriteString("[") |
| 80 | + for i, v := range ts.TypeParams.List { |
| 81 | + if i != 0 { |
| 82 | + sb.WriteString(", ") |
| 83 | + } |
| 84 | + sb.WriteString(v.Names[0].Name) |
| 85 | + } |
| 86 | + sb.WriteString("]") |
| 87 | + return sb.String() |
| 88 | +} |
0 commit comments