go-hep.org/x/hep@v0.38.1/groot/rdict/gen.go (about)

     1  // Copyright ©2018 The go-hep 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 rdict
     6  
     7  import (
     8  	"go/types"
     9  	"strings"
    10  
    11  	"go-hep.org/x/hep/groot/rmeta"
    12  )
    13  
    14  // Generator is the interface used to generate ROOT related code.
    15  type Generator interface {
    16  	// Generate generates code for a given type.
    17  	Generate(typ string) error
    18  
    19  	// Format formats the Go generated code.
    20  	Format() ([]byte, error)
    21  }
    22  
    23  func gotype2RMeta(t types.Type) rmeta.Enum {
    24  	switch ut := t.Underlying().(type) {
    25  	case *types.Basic:
    26  		switch ut.Kind() {
    27  		case types.Bool:
    28  			return rmeta.Bool
    29  		case types.Uint8:
    30  			return rmeta.Uint8
    31  		case types.Uint16:
    32  			return rmeta.Uint16
    33  		case types.Uint32, types.Uint:
    34  			return rmeta.Uint32
    35  		case types.Uint64:
    36  			return rmeta.Uint64
    37  		case types.Int8:
    38  			return rmeta.Int8
    39  		case types.Int16:
    40  			return rmeta.Int16
    41  		case types.Int32, types.Int:
    42  			return rmeta.Int32
    43  		case types.Int64:
    44  			return rmeta.Int64
    45  		case types.Float32:
    46  			return rmeta.Float32
    47  		case types.Float64:
    48  			return rmeta.Float64
    49  		case types.String:
    50  			return rmeta.TString
    51  		}
    52  	case *types.Struct:
    53  		return rmeta.Any
    54  	case *types.Slice:
    55  		return rmeta.STL
    56  	case *types.Array:
    57  		return rmeta.OffsetL + gotype2RMeta(ut.Elem())
    58  	}
    59  	return -1
    60  }
    61  
    62  // GoName2Cxx translates a fully-qualified Go type name to a C++ one.
    63  // e.g.:
    64  //   - go-hep.org/x/hep/hbook.H1D -> go_hep_org::x::hep::hbook::H1D
    65  func GoName2Cxx(name string) string {
    66  	repl := strings.NewReplacer(
    67  		"-", "_",
    68  		"/", "::",
    69  		".", "_",
    70  	)
    71  	i := strings.LastIndex(name, ".")
    72  	if i > 0 {
    73  		name = name[:i] + "::" + name[i+1:]
    74  	}
    75  	return repl.Replace(name)
    76  }
    77  
    78  // Typename returns a language dependent typename, usually encoded inside a
    79  // StreamerInfo's title.
    80  func Typename(name, title string) (string, bool) {
    81  	if title == "" {
    82  		return name, false
    83  	}
    84  	i := strings.Index(title, ";")
    85  	if i <= 0 {
    86  		return name, false
    87  	}
    88  	lang := title[:i]
    89  	title = strings.TrimSpace(title[i+1:])
    90  	switch lang {
    91  	case "Go":
    92  		return title, GoName2Cxx(title) == name
    93  	default:
    94  		return title, false
    95  	}
    96  }