Source file src/simd/archsimd/_gen/specgen/expandtype.go

     1  // Copyright 2026 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 specgen
     6  
     7  import (
     8  	"fmt"
     9  	"go/types"
    10  	"simd/archsimd/_gen/specgen/specexpr"
    11  	"strings"
    12  )
    13  
    14  // expand instantiates t over all solutions of its type parameters, producing
    15  // one TypeDecl per API type.
    16  func (t *specType) expand(ctx context, opts *LoadOptions) []*TypeDecl {
    17  	ctx = ctx.at(t.Pos)
    18  
    19  	var solver specexpr.Solver
    20  
    21  	if opts.Trace != nil {
    22  		fmt.Fprintf(opts.Trace, "## type %s\n", t.Name)
    23  		solver.SetTrace(opts.Trace)
    24  	}
    25  
    26  	// Declare domains of type parameters
    27  	typeParamVars := make(map[*types.TypeParam]specexpr.Variable)
    28  	for _, param := range t.TypeParams {
    29  		domain, err := constraintToDomain(t.Pkg, param.Constraint())
    30  		if err != nil {
    31  			panic(err)
    32  		}
    33  		varDef := specexpr.Variable("$" + param.String())
    34  		solver.Declare(varDef, domain)
    35  		typeParamVars[param] = varDef
    36  	}
    37  
    38  	// Bind the shape of the Vec this type is defined as
    39  	b := &argBinder{ctx, t.Pkg, &solver, typeParamVars}
    40  	get := b.bindArg("T", t.Def)
    41  	if get == nil {
    42  		return nil
    43  	}
    44  
    45  	defer func() {
    46  		p := recover()
    47  		if p != nil {
    48  			var buf strings.Builder
    49  			solver.Fprint(&buf)
    50  			panic(fmt.Sprintf("%s: %s\n%s", ctx.root.fset.Position(t.Pos), p, buf.String()))
    51  		}
    52  	}()
    53  	var decls []*TypeDecl
    54  	for soln, err := range solver.Solve() {
    55  		if err != nil {
    56  			ctx.errorf("%s", err)
    57  			continue
    58  		}
    59  
    60  		shape, ok := get(soln).(specexpr.Vector)
    61  		if !ok {
    62  			ctx.errorf("type %s does not describe a vector type", t.Name)
    63  			continue
    64  		}
    65  
    66  		name, rawDoc := t.expandNameAndDoc(ctx, soln)
    67  		if name != shape.String() {
    68  			// API type names are determined by their shape, and consumers
    69  			// look up types by name, so the name template must agree.
    70  			ctx.errorf("type %s: name template produced %q for shape %s (use //specgen:name {{.T}})", t.Name, name, shape)
    71  			continue
    72  		}
    73  
    74  		decls = append(decls, &TypeDecl{
    75  			Name:  name,
    76  			Shape: shape,
    77  			Doc:   parseSpecDoc(ctx, rawDoc),
    78  			Pos:   t.Pkg.Fset.Position(t.Pos),
    79  		})
    80  	}
    81  
    82  	if len(decls) == 0 {
    83  		ctx.errorf("impossible constraints for type %s", t.Name)
    84  	}
    85  
    86  	return decls
    87  }
    88  

View as plain text