github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/vector/generate/def.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  )
     7  
     8  type Config struct {
     9  	Package string
    10  
    11  	Unroll  int
    12  	Type    Type
    13  	Counter bool
    14  	Pointer bool
    15  }
    16  
    17  func (c Config) GetConfig() Config { return c }
    18  
    19  type Context interface {
    20  	GetConfig() Config
    21  
    22  	In(output string) File
    23  }
    24  
    25  type File interface {
    26  	GetConfig() Config
    27  
    28  	Func(
    29  		signature string,
    30  		template Template,
    31  	)
    32  }
    33  
    34  type Type struct {
    35  	Name string
    36  	Size int
    37  }
    38  
    39  func Range(name string, start, count any) It {
    40  	return It{
    41  		Kind:  ItRange,
    42  		Name:  name,
    43  		Start: ExprFrom(start),
    44  		Inc:   Expr{Const: 1},
    45  		Count: ExprFrom(count),
    46  	}
    47  }
    48  
    49  func Slice(name string, start, inc any) It {
    50  	return It{
    51  		Kind:  ItSlice,
    52  		Name:  name,
    53  		Start: ExprFrom(start),
    54  		Inc:   ExprFrom(inc),
    55  		Count: Expr{Derived: true},
    56  	}
    57  }
    58  
    59  type Template interface {
    60  	isTemplate()
    61  }
    62  
    63  type Iterate struct {
    64  	Ranges []It
    65  	For    string
    66  }
    67  
    68  func (Iterate) isTemplate() {}
    69  
    70  type It struct {
    71  	Kind  ItKind
    72  	Name  string
    73  	Start Expr
    74  	Inc   Expr
    75  	Count Expr
    76  }
    77  
    78  type ItKind byte
    79  
    80  const (
    81  	ItRange = 1
    82  	ItSlice = 2
    83  )
    84  
    85  type Expr struct {
    86  	Const   int
    87  	Expr    string
    88  	Derived bool
    89  }
    90  
    91  func Var(v string) Expr {
    92  	return Expr{Expr: v}
    93  }
    94  
    95  func Const(v int) Expr {
    96  	return Expr{Const: v}
    97  }
    98  
    99  func ExprFrom(v any) Expr {
   100  	switch v := v.(type) {
   101  	case int:
   102  		return Expr{Const: v}
   103  	case string:
   104  		return Expr{Expr: v}
   105  	default:
   106  		panic(fmt.Sprintf("unhandled %T", v))
   107  	}
   108  }
   109  
   110  func (num Expr) String() string {
   111  	switch {
   112  	case num.Derived:
   113  		panic("cannot automatically derive")
   114  	case num.Expr != "":
   115  		return num.Expr
   116  	default:
   117  		return strconv.Itoa(num.Const)
   118  	}
   119  }