github.com/taylorchu/generic@v0.0.0-20171113184323-cd81575befa2/cmd/generic/type_map.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"strings"
     6  
     7  	"github.com/taylorchu/generic/rewrite"
     8  )
     9  
    10  // ParseTypeMap parses raw strings to type replacements.
    11  func ParseTypeMap(args []string) (map[string]rewrite.Type, error) {
    12  	typeMap := make(map[string]rewrite.Type)
    13  
    14  	for _, arg := range args {
    15  		part := strings.Split(arg, "->")
    16  
    17  		if len(part) != 2 {
    18  			return nil, errors.New("RULE must be in form of `TypeXXX->OtherType`")
    19  		}
    20  
    21  		var (
    22  			from = strings.TrimSpace(part[0])
    23  			to   = strings.TrimSpace(part[1])
    24  		)
    25  
    26  		if !strings.HasPrefix(from, "Type") {
    27  			return nil, errors.New("REPL type must start with `Type`")
    28  		}
    29  
    30  		var t rewrite.Type
    31  		if strings.Contains(to, ":") {
    32  			toPart := strings.Split(to, ":")
    33  
    34  			if len(toPart) != 2 {
    35  				return nil, errors.New("REPL type must be in form of DESTPATH:OtherType")
    36  			}
    37  
    38  			t.Import = []string{strings.TrimSpace(toPart[0])}
    39  			t.Expr = strings.TrimSpace(toPart[1])
    40  			if strings.Count(t.Expr, ".") != 1 {
    41  				return nil, errors.New("REPL type must contain one `.`")
    42  			}
    43  		} else {
    44  			t.Expr = to
    45  			if strings.Count(t.Expr, ".") != 0 {
    46  				return nil, errors.New("REPL type must not contain `.`")
    47  			}
    48  		}
    49  		if t.Expr == "" {
    50  			return nil, errors.New("REPL type cannot be empty")
    51  		}
    52  
    53  		typeMap[from] = t
    54  	}
    55  	return typeMap, nil
    56  }